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_SYJB
    {
        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);
                    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;
                        var askbillnum = p_entity.AskBillNum;
                        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 (p_entity.Site == "0210")
                            {
                                string datestr= p_entity.Batch;
                                if (p_entity.ProduceDate != null)
                                {
                                    DateTime dttemp;                                   
                                    if (DateTime.TryParse(p_entity.ProduceDate.ToString(), out dttemp))
                                    {
                                        datestr = dttemp.ToString("yyMMdd");//到货日期
                                    }
                                }
                                code = GetLastBarCode_SYJB(p_entity.PartCode, datestr, 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.Remark,
                                PackQty = 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(barcode, askbillnum);
                            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(TS_BARCODE barcode, string askbillnum)
        {
            var fullcode = string.Empty;
            switch (ScpCache.Config.二维码格式)
            {
                case "1":
                    fullcode = GetFullCode(barcode.BarCode, barcode.Qty, barcode.VendId, barcode.VendBatch, barcode.BillNum,
                        barcode.PoBillLine, barcode.ProduceDate, askbillnum,barcode.PoBillNum);
                    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.VendBatch,
                        //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 askbillnum,string pobillnum)
        {
            string sp = ";";
            string fullCode = string.Empty;
            fullCode += code + sp;
            fullCode += qty + sp;
            fullCode += vendId + sp;
            fullCode += vendBatch + sp;
            //fullCode += billnum + "." + linnum + sp;
            fullCode += pobillnum + "." + linnum + sp;
            fullCode += productDate.ToString("yyyy/MM/dd") + sp;
            fullCode += askbillnum + 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;

        }


        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 GetLastBarCode_SYJB(string partcode, string  producedate, int lastnum)
        {

            var barcode = string.Empty;
            barcode += partcode + ScpCache.Config.条码分隔符;

            if (ScpCache.Config.条码包含供应商简称)
            {
                barcode += producedate + ScpCache.Config.条码分隔符;
            }
            else
            {
                barcode += producedate + ScpCache.Config.条码分隔符;
            }
            barcode += lastnum.ToString(ScpCache.Config.条码序列号格式);
            return barcode;
        }
    }
    public class TS_BARCODE_S_SYJB
    {
        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

    }
}