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_CUSTOM
    {
        public static void Get_TS_BARCODE_List_CUSTOM(TS_BARCODE_CUSTOM p_entity, Action<ResultObject<IQueryable<TS_BARCODE_CUSTOM>>> p_action)
        {
            ResultObject<IQueryable<TS_BARCODE_CUSTOM>> _ret = new ResultObject<IQueryable<TS_BARCODE_CUSTOM>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TS_BARCODE_CUSTOM> q = db.TS_BARCODE_CUSTOM;

                    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 (!string.IsNullOrEmpty(p_entity.PartName))
                    {
                        q = q.Where(p => p.PartName.Contains(p_entity.PartName));
                    }
                 
                    _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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "Get_TS_BARCODE_List", e.Message);
                throw e;
            }

        }



        public static ResultObject<List<TS_BARCODE_CUSTOM>> CreateBarcodeList(V_TB_ASK_DETAIL_PACKAGE p_entity, int cnt = 1)
        {

            ResultObject<List<TS_BARCODE_CUSTOM>> _ret = new ResultObject<List<TS_BARCODE_CUSTOM>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var list = new List<TS_BARCODE_CUSTOM>();
                    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);
                    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_CUSTOM
                            {
                                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==null?0:(decimal)p_entity.Qty,
                                BarCodeType = 1,
                                BillNum = p_entity.PoBillNum,
                                PoBillNum=p_entity.PoBillNum,
                                PoBillLine = p_entity.PoLine,
                                VendId = p_entity.VendId,
                                VendBatch = p_entity.Batch,
                                CreateTime = p_entity.CreateTime,
                                CreateOper = p_entity.CreateUser,
                                State = 0,
                                Remark = p_entity.Remark,
                                PackQty = (decimal)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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "CreateBarcodeList", e.Message);
                throw e;
            }
            return _ret;
        }

        public static string GetFullCode(TS_BARCODE_CUSTOM 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_CUSTOM CreateBarcode(V_TB_ASK_DETAIL_PACKAGE p_entity)
        {
            var ret = CreateBarcodeList(p_entity);

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

        }


        private static ResultObject<TS_BARCODE_RULE_CUSTOM> GetBarcodeRule( string partcode, string batch, int cnt = 1)
        {
            ResultObject<TS_BARCODE_RULE_CUSTOM> _ret = new ResultObject<TS_BARCODE_RULE_CUSTOM>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {

                    var ruleBatch = batch.Substring(0, 4);
                    //var barcodeRule = db.TS_BARCODE_RULE_CUSTOM.Find(partcode, ruleBatch);
                    //if (barcodeRule == null)
                    //{
                      var  barcodeRule = new TS_BARCODE_RULE_CUSTOM
                        {
                            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_CUSTOM.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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "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_CUSTOM), "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;
        }


    }








    public class TS_BARCODE_S_CUSTOM
    {
        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

    }
}