using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CK.SCP.Models;
using CK.SCP.Models.Enums;
using CK.SCP.Models.ScpEntity;
using CK.SCP.Utils;
using System.Data.Entity.Core;

namespace CK.SCP.Controller
{
    public static class SCP_BARCODE_CONTROLLER
    {

        public static ResultObject<bool> Save_TB_PRINT_COUNT(TB_PRINT_COUNT p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _print=db.TB_PRINT_COUNT.Where(p => p.BillNo == p_entity.BillNo).FirstOrDefault();
                    if (_print == null)
                    {
                        _print = new TB_PRINT_COUNT();
                        _print.BillNo = p_entity.BillNo;
                        _print.PrintType = p_entity.PrintType;
                        _print.PrintCount = 1;
                    }                  
                    db.TB_PRINT_COUNT.AddOrUpdate(p => new {p.PrintType,p.BillNo }, p_entity);
                    
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();
                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {
                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Save_TB_PRINT_COUNT", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Save_TB_PRINT_COUNT", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Save_TB_PRINT_COUNT", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;                    
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Save_TB_PRINT_COUNT", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }


        public static ResultObject<List<TB_PRINT_COUNT>> Get_TB_PRINT_COUNT_List(TB_PRINT_COUNT p_entity)
        {
            ResultObject<List<TB_PRINT_COUNT>> _ret = new ResultObject<List<TB_PRINT_COUNT>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TB_PRINT_COUNT> q = db.TB_PRINT_COUNT;
                    if (!string.IsNullOrEmpty(p_entity.BillNo))
                    {
                        q = q.Where(p => p.BillNo.Contains(p_entity.BillNo));
                    }
                    if (p_entity.PrintCount != 0)
                    {
                        q = q.Where(p => p.PrintCount == p_entity.PrintCount);
                    }
                    if (p_entity.PrintType != 0)
                    {
                        q = q.Where(p => p.PrintType == p_entity.PrintType);
                    }
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }

                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q.ToList();
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TB_PRINT_COUNT_List", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TB_PRINT_COUNT_List", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                

                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TB_PRINT_COUNT_List", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;

                    
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TB_PRINT_COUNT_List", e.Message);
                throw e;
            }
            return _ret;
        }

        public static void Get_TS_BARCODE_List(TS_BARCODE p_entity, Action<ResultObject<IQueryable<TS_BARCODE>>> p_action)
        {
            ResultObject<IQueryable<TS_BARCODE>> _ret = new ResultObject<IQueryable<TS_BARCODE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TS_BARCODE> q = db.TS_BARCODE;

                    if (!string.IsNullOrEmpty(p_entity.BarCode))
                    {
                        q = q.Where(p => p.BarCode == p_entity.BarCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.FullBarCode))
                    {
                        q = q.Where(p => p.FullBarCode == p_entity.FullBarCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode == p_entity.PartCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendPartCode))
                    {
                        q = q.Where(p => p.VendPartCode == p_entity.VendPartCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch == p_entity.Batch);
                    }
                    if (p_entity.ManageType != 0)
                    {
                        q = q.Where(p => p.ManageType == p_entity.ManageType);
                    }
                    if (!string.IsNullOrEmpty(p_entity.SerialNum))
                    {
                        q = q.Where(p => p.SerialNum.Contains(p_entity.SerialNum));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (p_entity.BarCodeType != 0)
                    {
                        q = q.Where(p => p.BarCodeType == p_entity.BarCodeType);
                    }
                    if (!string.IsNullOrEmpty(p_entity.BillNum))
                    {
                        q = q.Where(p => p.BillNum.Contains(p_entity.BillNum));
                    }
                    if (p_entity.PoBillLine != 0)
                    {
                        q = q.Where(p => p.PoBillLine == p_entity.PoBillLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch == p_entity.VendBatch);
                    }
                    if (p_entity.PackQty != 0)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateOper))
                    {
                        q = q.Where(p => p.CreateOper.Contains(p_entity.CreateOper));
                    }
                    if (p_entity.State != 0)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoUnit))
                    {
                        q = q.Where(p => p.PoUnit.Contains(p_entity.PoUnit));
                    }
                    if (!string.IsNullOrEmpty(p_entity.LocUnit))
                    {
                        q = q.Where(p => p.LocUnit.Contains(p_entity.LocUnit));
                    }
                    if (p_entity.IsScanned)
                    {
                        q = q.Where(p => p.IsScanned==false);
                    }
                    //if (!string.IsNullOrEmpty(p_entity.PartName))
                    //{
                    //    q = q.Where(p => p.PartName.Contains(p_entity.PartName));
                    //}
                    //if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    //{
                    //    q = q.Where(p => p_entity.UserInAddress.Contains(p.Address));
                    //}
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException; 
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", e.Message);
                throw e;
            }

        }

        public static void Get_TS_BARCODE_SMALL_List(TS_BARCODE_SMALL p_entity, Action<ResultObject<IQueryable<TS_BARCODE_SMALL>>> p_action)
        {
            ResultObject<IQueryable<TS_BARCODE_SMALL>> _ret = new ResultObject<IQueryable<TS_BARCODE_SMALL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TS_BARCODE_SMALL> q = db.TS_BARCODE_SMALL;
                    if (!string.IsNullOrEmpty(p_entity.BarCode))
                    {
                        q = q.Where(p => p.BarCode == p_entity.BarCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.FullBarCode))
                    {
                        q = q.Where(p => p.FullBarCode == p_entity.FullBarCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode == p_entity.PartCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendPartCode))
                    {
                        q = q.Where(p => p.VendPartCode == p_entity.VendPartCode);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch == p_entity.Batch);
                    }
                    if (p_entity.ManageType != 0)
                    {
                        q = q.Where(p => p.ManageType == p_entity.ManageType);
                    }
                    if (!string.IsNullOrEmpty(p_entity.SerialNum))
                    {
                        q = q.Where(p => p.SerialNum.Contains(p_entity.SerialNum));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (p_entity.BarCodeType != 0)
                    {
                        q = q.Where(p => p.BarCodeType == p_entity.BarCodeType);
                    }
                    if (!string.IsNullOrEmpty(p_entity.BillNum))
                    {
                        q = q.Where(p => p.BillNum.Contains(p_entity.BillNum));
                    }
                    if (p_entity.PoBillLine != 0)
                    {
                        q = q.Where(p => p.PoBillLine == p_entity.PoBillLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch == p_entity.VendBatch);
                    }
                    if (p_entity.SmallPackQty != 0)
                    {
                        q = q.Where(p => p.SmallPackQty == p_entity.SmallPackQty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateOper))
                    {
                        q = q.Where(p => p.CreateOper.Contains(p_entity.CreateOper));
                    }
                    if (p_entity.State != 0)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoUnit))
                    {
                        q = q.Where(p => p.PoUnit.Contains(p_entity.PoUnit));
                    }
                    if (!string.IsNullOrEmpty(p_entity.LocUnit))
                    {
                        q = q.Where(p => p.LocUnit.Contains(p_entity.LocUnit));
                    }
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();
                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {
                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "Get_TS_BARCODE_List", e.Message);
                throw e;
            }
        }
        public static ResultObject<List<TS_BARCODE_SMALL>> CreateSmallBarcodeList(V_TB_ASN_DETAIL p_entity, int cnt = 1)
        {
            ResultObject<List<TS_BARCODE_SMALL>> _ret = new ResultObject<List<TS_BARCODE_SMALL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var list = new List<TS_BARCODE_SMALL>();
                    var part = db.TA_PART.FirstOrDefault(p => p.PartCode == p_entity.PartCode);
                    if (part == null)
                    {
                        _ret.MessageList.Add("������Ϣδ�ҵ��ñ�����!");
                    }
                    var vendPart= db.TA_VEND_PART.FirstOrDefault(p => p.PartCode == p_entity.PartCode && p.VendId == p_entity.VendId);
                    var ret = GetSmallBarcodeRule(p_entity.PartCode, p_entity.Batch, cnt);
                    var _part = db.TA_PART.FirstOrDefault(p => p.PartCode == p_entity.PartCode && p.Site == p_entity.Site);
                    if (ret.State == ReturnStatus.Succeed)
                    {
                        var barcodeRule = ret.Result;
                        for (int i = cnt; i > 0; i--)
                        {
                            var createTime = ScpCache.GetServerTime();
                            var code = GetLastSmallBarCode(p_entity.PartCode, p_entity.Batch, barcodeRule.LastNumber - i + 1);
                            if (part.PartDesc1.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("LEFT") ||
                                part.PartDesc2.ToUpper().Contains("��") || part.PartDesc2.ToUpper().Contains("LEFT"))
                                p_entity.Remark = "L" + p_entity.Remark;
                            if (part.PartDesc1.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("RIGHT") ||
                                part.PartDesc2.ToUpper().Contains("��") || part.PartDesc2.ToUpper().Contains("RIGHT"))
                                p_entity.Remark = "R" + p_entity.Remark;
                            string _check = (_part.Ischeck == false || _part.Ischeck == null) ? "" : "(���)";
                            var barcode = new TS_BARCODE_SMALL
                            {
                                BarCode = code,
                                PartCode = part.PartCode,
                                VendPartCode = vendPart?.VendPartCode,
                                Batch = p_entity.Batch,
                                ProduceDate = (DateTime)p_entity.ProduceDate,
                                SerialNum = barcodeRule.LastNumber.ToString(ScpCache.Config.�������кŸ�ʽ),
                                PoUnit = p_entity.PoUnit,
                                Qty = p_entity.Qty,
                                BarCodeType = 1,
                                BillNum = p_entity.AsnBillNum,
                                PoBillNum = p_entity.PoBillNum,
                                PoBillLine = p_entity.PoLine,
                                VendId = p_entity.VendId,
                                VendBatch = p_entity.VendBatch,
                                CreateTime = p_entity.CreateTime,
                                CreateOper = p_entity.CreateUser,
                                State = 0,
                                Remark = p_entity.Remark,
                                SmallPackQty = p_entity.PackQty,
                                Site = p_entity.Site
                            };
                            if (_part == null)
                            {
                                _ret.MessageList.Add("δ�ҵ����,�����������Ż�ص���Ϣ����,������" + p_entity.PartCode);
                                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", "δ�ҵ����,�����������Ż�ص���Ϣ����,������" + p_entity.PartCode);
                            }
                            else
                            {
                                var _isCheck = (_part.Ischeck == null) ? false : _part.Ischeck;
                                barcode.Qlevel = _part.Qlevel;
                                barcode.QMark = (_isCheck == true) ? "���" : "ȫ��";
                                barcode.ProjectId = _part.ProjectId;
                            }
                            var fullCode = GetFullCode_Small(barcode);
                            barcode.FullBarCode = fullCode;
                            list.Add(barcode);
                        }
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = list;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Message = "��������������!";
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();
                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {
                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateSmallBarcodeList", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateSmallBarcodeList", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateSmallBarcodeList", ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateSmallBarcodeList", e.Message);
                throw e;
            }
            return _ret;
        }
        public static ResultObject<List<TS_BARCODE>> CreateBarcodeList(V_TB_ASN_DETAIL p_entity, int cnt = 1)
        {

            ResultObject<List<TS_BARCODE>> _ret = new ResultObject<List<TS_BARCODE>>();
            try
            {
              
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var list = new List<TS_BARCODE>();
                    var part = db.TA_PART.FirstOrDefault(p => p.PartCode == p_entity.PartCode);
                    if (part == null)
                    {
                        _ret.MessageList.Add("������Ϣδ�ҵ��ñ�����!");
                        //throw e;
                    }
                    var vendPart
                       = db.TA_VEND_PART.FirstOrDefault(p => p.PartCode == p_entity.PartCode && p.VendId == p_entity.VendId && p.Site==p_entity.Site);
                    var ret = GetBarcodeRule(p_entity.PartCode, p_entity.Batch, cnt);

                    var _part=db.TA_PART.FirstOrDefault(p=>p.PartCode==p_entity.PartCode && p.Site==p_entity.Site);

                    if (ret.State == ReturnStatus.Succeed)
                    {
                        var barcodeRule = ret.Result;
                        for (int i = cnt; i > 0; i--)
                        {
                            var createTime = ScpCache.GetServerTime();
                            var code = GetLastBarCode(p_entity.PartCode, p_entity.Batch, barcodeRule.LastNumber - i + 1);
                            if (part.PartDesc1.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("LEFT") ||
                                part.PartDesc2.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("LEFT"))
                                p_entity.Remark = "L" + p_entity.Remark;
                            if (part.PartDesc1.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("LEFT") ||
                                part.PartDesc2.ToUpper().Contains("��") || part.PartDesc1.ToUpper().Contains("LEFT"))
                                p_entity.Remark = "R" + p_entity.Remark;
                            string _check = (_part.Ischeck == false || _part.Ischeck == null) ? "" : "(���)";
                            var barcode = new TS_BARCODE
                            {
                                BarCode = code,
                                PartCode = part.PartCode,
                                VendPartCode = vendPart?.VendPartCode,
                                Batch = p_entity.Batch,
                                ProduceDate = (DateTime)p_entity.ProduceDate,
                                SerialNum = barcodeRule.LastNumber.ToString(ScpCache.Config.�������кŸ�ʽ),
                                PoUnit = p_entity.PoUnit,
                                Qty = p_entity.Qty,
                                BarCodeType = 1,
                                BillNum = p_entity.AsnBillNum,
                                PoBillNum=p_entity.PoBillNum,
                                PoBillLine = p_entity.PoLine,
                                VendId = p_entity.VendId,
                                VendBatch = p_entity.VendBatch,
                              
                                CreateTime = p_entity.CreateTime,
                                CreateOper = p_entity.CreateUser,
                                State = 0,
                                Remark = p_entity.UpdateInfo,
                                PackQty = p_entity.PackQty,
                                Site = p_entity.Site,
                                IsScanned = false
                             
                            };

                            if (_part == null)
                            {
                                _ret.MessageList.Add("δ�ҵ����,�����������Ż�ص���Ϣ����,������"+ p_entity.PartCode);
                                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", "δ�ҵ����,�����������Ż�ص���Ϣ����,������" + p_entity.PartCode);
                            }
                            else
                            {
                                var _isCheck=(_part.Ischeck == null)?false:_part.Ischeck;
                                barcode.Qlevel = _part.Qlevel;
                                barcode.QMark = (_isCheck == true) ? "���" : "ȫ��";
                                barcode.ProjectId = _part.ProjectId;
                            }
                            var fullCode = GetFullCode(barcode);
                            barcode.FullBarCode = fullCode;
                            list.Add(barcode);
                        }

                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = list;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Message = "��������������!";
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                

                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;

                    
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "CreateBarcodeList", e.Message);
                throw e;
            }
            return _ret;
        }
        public static string GetFullCode_Small(TS_BARCODE_SMALL barcode)
        {
            var fullcode = string.Empty;
            switch (ScpCache.Config.��ά���ʽ)
            {
                case "1":
                    fullcode =
                        GetFullCode(barcode.BarCode, barcode.Qty, barcode.VendId, barcode.VendBatch, barcode.PoBillNum,
                        barcode.PoBillLine, barcode.ProduceDate, barcode.BillNum);
                    break;      
            }
            return fullcode;
        }
        public static string GetFullCode(TS_BARCODE barcode)
        {
            var fullcode = string.Empty;
            switch (ScpCache.Config.��ά���ʽ)
            {
                case "1":
                    fullcode =
                        GetFullCode(barcode.BarCode, barcode.Qty, barcode.VendId, barcode.VendBatch, barcode.PoBillNum,
                        barcode.PoBillLine, barcode.ProduceDate,barcode.BillNum);
                    break;
                //case "2":
                //    var barcodeS = new TS_BARCODE_S
                //    {
                //        B = barcode.BarCode,
                //        P = barcode.PartCode,
                //        T = barcode.Batch,
                //        D = barcode.ProduceDate.Date,
                //        Q = barcode.Qty,
                //        N = barcode.BillNum,
                //        L = barcode.PoBillLine,
                //        V = barcode.VendId,
                //        C = barcode.Batch,
                //        //E = barcode.EqptCode,
                //        K = barcode.PackQty,
                //    };
                 //   fullcode = JsonHelper.GetJson(barcodeS);
                 //   break;
            }
            return fullcode;
        }
        public static string GetFullCode(string code, decimal qty, string vendId, string vendBatch, string billnum, int linnum,
             DateTime productDate,string asnbillnum)
        {
            string sp = ";";
            string fullCode = string.Empty;
            fullCode += code + sp;
            fullCode += qty + sp;
            fullCode += vendId + sp;
            fullCode += vendBatch + sp;
            fullCode += billnum + "." + linnum + sp;
            fullCode += productDate.ToString("yyyy/MM/dd") + sp;
            fullCode += asnbillnum + sp; 

            return fullCode;
        }


        public static TS_BARCODE CreateBarcode(V_TB_ASN_DETAIL p_entity)
        {
            var ret = CreateBarcodeList(p_entity);

            if (ret.State == ReturnStatus.Succeed)
            {
                return ret.Result[0];
            }
            return null;

        }
        public static TS_BARCODE_SMALL CreateSmallBarcode(V_TB_ASN_DETAIL p_entity)
        {
            var ret = CreateSmallBarcodeList(p_entity);

            if (ret.State == ReturnStatus.Succeed)
            {
                return ret.Result[0];
            }
            return null;

        }
        private static ResultObject<TS_BARCODE_RULE_SMALL> GetSmallBarcodeRule(string partcode, string batch, int cnt = 1)
        {
            ResultObject<TS_BARCODE_RULE_SMALL> _ret = new ResultObject<TS_BARCODE_RULE_SMALL>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var ruleBatch = batch.Substring(0, 4);
                    var barcodeRule = db.TS_BARCODE_RULE_SMALL.Find(partcode, ruleBatch);
                    if (barcodeRule == null)
                    {
                        barcodeRule = new TS_BARCODE_RULE_SMALL
                        {
                            PartCode = partcode,
                            RuleBatch = ruleBatch,
                            LastNumber = cnt,
                            State = 0
                        };
                    }
                    else
                    {
                        barcodeRule.LastNumber += cnt;
                    }
                    barcodeRule.LastBarCode = GetLastSmallBarCode(partcode, batch, barcodeRule.LastNumber);
                    barcodeRule.LastTime = ScpCache.GetServerTime();
                    db.TS_BARCODE_RULE_SMALL.AddOrUpdate(p => new { p.PartCode, p.RuleBatch }, barcodeRule);
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = barcodeRule;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();
                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {
                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", e.Message);
                throw e;
            }
            return _ret;
        }
        private static ResultObject<TS_BARCODE_RULE> GetBarcodeRule( string partcode, string batch, int cnt = 1)
        {
            ResultObject<TS_BARCODE_RULE> _ret = new ResultObject<TS_BARCODE_RULE>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {

                    var ruleBatch = batch.Substring(0, 4);
                    var barcodeRule = db.TS_BARCODE_RULE.Find(partcode, ruleBatch);
                    if (barcodeRule == null)
                    {
                        barcodeRule = new TS_BARCODE_RULE
                        {
                            PartCode = partcode,
                            RuleBatch = ruleBatch,
                            LastNumber = cnt,
                            State = 0
                        };
                    }
                    else
                    {
                        barcodeRule.LastNumber += cnt;
                    }

                    barcodeRule.LastBarCode = GetLastBarCode(partcode, batch, barcodeRule.LastNumber);
                    barcodeRule.LastTime = ScpCache.GetServerTime();

                    db.TS_BARCODE_RULE.AddOrUpdate(p => new { p.PartCode, p.RuleBatch }, barcodeRule);
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = barcodeRule;
                       
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                      
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//����ʵ����֤�쳣
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("����{0}���ֶΣ�{1}����Ϣ��{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "�ֶ���֤ʧ��" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//������ͻ�쳣
            {
                
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;

                    
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_BARCODE_CONTROLLER), "GetBarcodeRule", e.Message);
                throw e;
            }
            return _ret;
        }
        private static string GetLastBarCode(string partcode, string batch, int lastnum)
        {

            var barcode = string.Empty;
            barcode += partcode + ScpCache.Config.����ָ���;

            if (ScpCache.Config.���������Ӧ�̼��)
            {
                barcode += batch + ScpCache.Config.����ָ���;
            }
            else
            {
                barcode += batch + ScpCache.Config.����ָ���;
            }
            barcode += lastnum.ToString(ScpCache.Config.�������кŸ�ʽ);
            return barcode;
        }

        private static string GetLastSmallBarCode(string partcode, string batch, int lastnum)
        {

            var barcode = string.Empty;
            barcode += partcode + ScpCache.Config.����ָ���;
            if (ScpCache.Config.���������Ӧ�̼��)
            {
                barcode += batch + ScpCache.Config.����ָ���;
            }
            else
            {
                barcode += batch + ScpCache.Config.����ָ���;
            }
            barcode += lastnum.ToString(ScpCache.Config.С��װ�������кŸ�ʽ);
            return barcode;
        }
    }

    public class TS_BARCODE_S
    {
        public string B { get; set; }//barcode

        public string P { get; set; }//partcode

        public string T { get; set; }//batch

        public DateTime D { get; set; }//producedate

        public decimal Q { get; set; }//qty

        public string N { get; set; }//billnum

        public int L { get; set; }//billline

        public string V { get; set; }//VendId

        public string C { get; set; }//vendbatch

        public string E { get; set; }//eqptcode

        public decimal K { get; set; }//packqty

    }
}