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

namespace CK.SCP.Controller
{


    public class SCP_CONTRACT_CONTROLLER
    {   
        public static void  Get_TB_CONTRACT_List(TB_CONTRACT p_entity, Action<ResultObject<IQueryable<TB_CONTRACT>>> p_action)
        {
            ResultObject<IQueryable<TB_CONTRACT>> _ret = new ResultObject<IQueryable<TB_CONTRACT>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TB_CONTRACT> q = db.TB_CONTRACT;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ContractNo))
                    {
                        q = q.Where(p => p.ContractNo.Contains(p_entity.ContractNo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    {
                        q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateInfo))
                    {
                        q = q.Where(p => p.UpdateInfo.Contains(p_entity.UpdateInfo));
                    }
                    if (p_entity.IsDeleted != false)
                    {
                        q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    }
                    if (!string.IsNullOrEmpty(p_entity.BillNo))
                    {
                        q = q.Where(p => p.BillNo.Contains(p_entity.BillNo));
                    }
                  
                    _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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_List", e.Message);
                throw e;
            }
           
        }
        public static ResultObject<List<TB_CONTRACT_DETAIL>> Get_TB_CONTRACT_DETAIL_List(TB_CONTRACT_DETAIL p_entity)
        {
            ResultObject<List<TB_CONTRACT_DETAIL>> _ret = new ResultObject<List<TB_CONTRACT_DETAIL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TB_CONTRACT_DETAIL> q = db.TB_CONTRACT_DETAIL;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.BillNo))
                    {
                        q = q.Where(p => p.BillNo.Contains(p_entity.BillNo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ContractNo))
                    {
                        q = q.Where(p => p.ContractNo.Contains(p_entity.ContractNo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartName))
                    {
                        q = q.Where(p => p.PartName.Contains(p_entity.PartName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Unit))
                    {
                        q = q.Where(p => p.Unit.Contains(p_entity.Unit));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    {
                        q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateInfo))
                    {
                        q = q.Where(p => p.UpdateInfo.Contains(p_entity.UpdateInfo));
                    }
                    
                    q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    
                   
                    _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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_List", e.Message);
                throw e;
            }
            return _ret;
        }

        public static List<string> NOTIFY_COMPARE_PRICE(List<TB_CONTRACT_DETAIL_PRICE> p_priceList, List<V_TB_PO_DETAIL> p_polist)
        {
            List<string> msgList = new List<string>();
            var ret= from po in p_polist
            join price in p_priceList on po.PartCode equals price.PartCode
            select new { VAL1 = po, VAL2 = price };
            var list = ret.Where(p=> p.VAL1.BeginTime>=p.VAL2.BeginTime && p.VAL1.BeginTime<=p.VAL2.EndTime && p.VAL1.PlanQty>=p.VAL2.QtyBegin && p.VAL1.PlanQty < p.VAL2.QtyEnd && (p.VAL1.Price> p.VAL2.Price || p.VAL1.Price==0));
            foreach(var itm in list)
            {
                msgList.Add(string.Format("物料编码{0}价格{1}与合同价格{2}不一致",itm.VAL1.PartCode, itm.VAL1.Price, itm.VAL2.Price));
            }
            return msgList;

        }



        //public static List<V_TB_RECEIVE_LIST> GET_TB_PRICE_LIST(List<V_TB_RECEIVE_LIST> p_list)
        //{
        //    if (p_list.Count > 0)
        //    {
        //        using (ScpEntities db = EntitiesFactory.CreateScpInstance())
        //        {
                   

        //        }
        //    }
        //}
        /// <summary>
        /// 发票申请差额
        /// </summary>
        /// <param name="p_list"></param>
        /// <returns></returns>
        public static List<V_TB_RECEIVE_LIST> GET_CONTRACT_PRICE_LIST(List<V_TB_RECEIVE_LIST> p_list)
        {
            if (p_list.Count > 0)
            {
                var ret= Get_TB_CONTRACT_DETAIL_PRICE_List(new TB_CONTRACT_DETAIL_PRICE() { VendId = p_list[0].VendId });
                if (ret.State == ReturnStatus.Succeed)
                {
                    var p_priceList = ret.Result;
                    List<string> msgList = new List<string>();
                    var ls = from po in p_list
                              join price in p_priceList on po.PartCode equals price.PartCode
                              select new { VAL1 = po, VAL2 = price };
                    var list = ls.Where(p => p.VAL1.BeginTime >= p.VAL2.BeginTime && p.VAL1.BeginTime <= p.VAL2.EndTime && p.VAL1.Qty >= p.VAL2.QtyBegin && p.VAL1.Qty < p.VAL2.QtyEnd);
                    p_list.ForEach(p =>
                    {
                        //p.PartDesc1 = p.PartDesc1+p.p
                        var _entity = list.ToList().Where(itm => itm.VAL1.PartCode == p.PartCode).FirstOrDefault();
                        if (_entity != null && _entity.VAL2 != null)
                        {
                            p.ContractPrice = _entity.VAL2.Price;
                            p.BlancePrice = p.ContractPrice - p.Price;
                        }
                        else
                        {
                            p.ContractPrice = p.Price;
                            p.BlancePrice = 0;
                        }
                    });
                }
            }
            return p_list;
        }
        /// <summary>
        /// 发票差额
        /// </summary>
        /// <param name="p_list"></param>
        /// <returns></returns>
        public static List<V_TB_INVOICE_DETAIL> GET_CONTRACT_PRICE_LIST(List<V_TB_INVOICE_DETAIL> p_list)
        {

            if (p_list.Count > 0)
            {
                var ret = Get_TB_CONTRACT_DETAIL_PRICE_List(new TB_CONTRACT_DETAIL_PRICE() { VendId = p_list[0].VendId });
                if (ret.State == ReturnStatus.Succeed)
                {
                    var p_priceList = ret.Result;
                    List<string> msgList = new List<string>();
                    var ls = from po in p_list
                             join price in p_priceList on po.PartCode equals price.PartCode
                             select new { VAL1 = po, VAL2 = price };
                    var list = ls.Where(p => p.VAL1.BeginTime >= p.VAL2.BeginTime && p.VAL1.BeginTime <= p.VAL2.EndTime && p.VAL1.Qty >= p.VAL2.QtyBegin && p.VAL1.Qty < p.VAL2.QtyEnd);
                    p_list.ForEach(p =>
                    {
                        var _entity = list.ToList().Where(itm => itm.VAL1.PartCode == p.PartCode).FirstOrDefault();
                        if (_entity != null && _entity.VAL2 != null)
                        {
                            p.ContractPrice = _entity.VAL2.Price;
                            p.BlancePrice = p.ContractPrice - p.Price;
                        }
                        else
                        {
                            p.ContractPrice = p.Price;
                            p.BlancePrice = 0;
                        }
                    });
                }
            }
            return p_list;
        }
        public static List<V_TB_PO_DETAIL> GET_CONTRACT_PRICE_LIST(List<V_TB_PO_DETAIL> p_list)
        {

            if (p_list.Count > 0)
            {
                var ret = Get_TB_CONTRACT_DETAIL_PRICE_List(new TB_CONTRACT_DETAIL_PRICE() { VendId = p_list[0].VendId });
                if (ret.State == ReturnStatus.Succeed)
                {
                    var p_priceList = ret.Result;
                    List<string> msgList = new List<string>();
                    var ls = from po in p_list
                             join price in p_priceList on po.PartCode equals price.PartCode
                             select new { VAL1 = po, VAL2 = price };
                    var list = ls.Where(p => p.VAL1.BeginTime >= p.VAL2.BeginTime && p.VAL1.BeginTime <= p.VAL2.EndTime && p.VAL1.TempQty >= p.VAL2.QtyBegin && p.VAL1.TempQty < p.VAL2.QtyEnd);
                    p_list.ForEach(p =>
                    {
                        var _entity = list.ToList().Where(itm => itm.VAL1.PartCode == p.PartCode).FirstOrDefault();
                        if (_entity != null)
                        {
                            p.ContractPrice = _entity.VAL2.Price;
                            p.BlancePrice = p.ContractPrice - p.Price;
                        }
                        else
                        {
                            p.ContractPrice = p.Price;
                            p.BlancePrice = 0;
                        }
                    });
                }
            }
            return p_list;
        }


        public static List<V_TB_ASK_DETAIL> GET_CONTRACT_PRICE_LIST(List<V_TB_ASK_DETAIL> p_list)
        {

            if (p_list.Count > 0)
            {
                var ret = Get_TB_CONTRACT_DETAIL_PRICE_List(new TB_CONTRACT_DETAIL_PRICE() { VendId = p_list[0].VendId });
                if (ret.State == ReturnStatus.Succeed)
                {
                    var p_priceList = ret.Result;
                    List<string> msgList = new List<string>();
                    var ls = from ask in p_list
                             join price in p_priceList on ask.PartCode equals price.PartCode
                             select new { VAL1 = ask, VAL2 = price };
                    var list = ls.Where(p => p.VAL1.BeginTime >= p.VAL2.BeginTime && p.VAL1.BeginTime <= p.VAL2.EndTime && p.VAL1.AskQty >= p.VAL2.QtyBegin && p.VAL1.AskQty < p.VAL2.QtyEnd);
                    p_list.ForEach(p =>
                    {
                        var _entity = list.ToList().Where(itm => itm.VAL1.PartCode == p.PartCode).FirstOrDefault();
                        if (_entity != null)
                        {
                            p.ContractPrice = _entity.VAL2.Price;
                            p.BlancePrice = p.ContractPrice - p.Price;
                        }
                        else
                        {
                            p.ContractPrice = p.Price;
                            p.BlancePrice = 0;
                        }
                    });
                }
            }
            return p_list;
        }


        public static ResultObject<List<TB_CONTRACT_DETAIL_PRICE>> Get_TB_CONTRACT_DETAIL_PRICE_List(TB_CONTRACT_DETAIL_PRICE p_entity,int p_qty=0)
        {
            ResultObject<List<TB_CONTRACT_DETAIL_PRICE>> _ret = new ResultObject<List<TB_CONTRACT_DETAIL_PRICE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {

                  
                    IQueryable<TB_CONTRACT_DETAIL_PRICE> q = db.TB_CONTRACT_DETAIL_PRICE;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.BillNo))
                    {
                        q = q.Where(p => p.BillNo.Contains(p_entity.BillNo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ContractNo))
                    {
                        q = q.Where(p => p.ContractNo.Contains(p_entity.ContractNo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (p_entity.QtyBegin != 0)
                    {
                        q = q.Where(p => p.QtyBegin == p_entity.QtyBegin);
                    }
                    if (p_entity.QtyEnd != 0)
                    {
                        q = q.Where(p => p.QtyBegin == p_entity.QtyBegin);
                    }
                    if (p_entity.Price != 0)
                    {
                        q = q.Where(p => p.Price == p_entity.Price);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                   
                    q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    
                  
                    _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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_PRICE_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_PRICE_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_PRICE_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_CONTRACT_CONTROLLER), "Get_TB_CONTRACT_DETAIL_PRICE_List", e.Message);
                throw e;
            }
            return _ret;
        }


        private static string IMPORT_CONTRACT_CHECK(SCP_CONTRACT_EXCEL itm)
        {

            StringBuilder _buffer = new StringBuilder();
            Regex reg = new Regex(@"^\d+(\.\d{1,5})?$");

            if (string.IsNullOrEmpty(itm.合同编号))
            {
                _buffer.AppendFormat(string.Format("导入错误合同编号未填写!")); 
            }
            if (string.IsNullOrEmpty(itm.供应商代码) || string.IsNullOrEmpty(itm.供应商名称))
            {
                _buffer.AppendFormat(string.Format("导入错误供应商编号或供应商名称未填写!")); 
            }
            if (string.IsNullOrEmpty(itm.供应商物料号) || string.IsNullOrEmpty(itm.物料描述))
            {
                _buffer.AppendFormat(string.Format("导入错误供应商物料号或供应商物料描述未填写!"));
            }

            if ((!string.IsNullOrEmpty(itm.价格1) && string.IsNullOrEmpty(itm.最小起订量1)) || (string.IsNullOrEmpty(itm.价格1) && !string.IsNullOrEmpty(itm.最小起订量1)))
            {
                _buffer.Append("导入错误价格1或最小起订量1为空!");
            }
            else
            {
                if (!string.IsNullOrEmpty(itm.价格1) && !string.IsNullOrEmpty(itm.最小起订量1))
                {
                    if (!reg.IsMatch(itm.价格1))
                    {
                        _buffer.Append("导入价格1格式有错误!");
                    }
                    if (!reg.IsMatch(itm.最小起订量1))
                    {
                        _buffer.Append("导入最小起订量1格式有错误!");
                    }

                }
            }

            if ((!string.IsNullOrEmpty(itm.价格2) && string.IsNullOrEmpty(itm.最小起订量2)) || (string.IsNullOrEmpty(itm.价格2) && !string.IsNullOrEmpty(itm.最小起订量2)))
            {
                _buffer.Append("导入错误价格2或最小起订量2为空!");
            }
            else
            {
                if (!string.IsNullOrEmpty(itm.价格2) && !string.IsNullOrEmpty(itm.最小起订量2))
                {
                    if (!reg.IsMatch(itm.价格2))
                    {
                        _buffer.Append("导入价格2格式有错误!");
                    }
                    if (!reg.IsMatch(itm.最小起订量2))
                    {
                        _buffer.Append("导入最小起订量2格式有错误!");
                    }

                }
            }
            if ((!string.IsNullOrEmpty(itm.价格3) && string.IsNullOrEmpty(itm.最小起订量3)) || (string.IsNullOrEmpty(itm.价格3) && !string.IsNullOrEmpty(itm.最小起订量3)))
            {
                _buffer.Append("导入错误价格3或最小起订量3为空!");
            }
            else
            {
                if (!string.IsNullOrEmpty(itm.价格3) && !string.IsNullOrEmpty(itm.最小起订量3))
                {
                    if (!reg.IsMatch(itm.价格3))
                    {
                        _buffer.Append("导入价格3格式有错误!");
                    }
                    if (!reg.IsMatch(itm.最小起订量3))
                    {
                        _buffer.Append("导入最小起订量3格式有错误!");
                    }
                }
            }

            if ((!string.IsNullOrEmpty(itm.价格4) && string.IsNullOrEmpty(itm.最小起订量4)) || (string.IsNullOrEmpty(itm.价格4) && !string.IsNullOrEmpty(itm.最小起订量4)))
            {
                _buffer.Append("导入错误价格4或最小起订量4为空!");
            }
            else
            {
                if (!string.IsNullOrEmpty(itm.价格4) && !string.IsNullOrEmpty(itm.最小起订量4))
                {
                    if (!reg.IsMatch(itm.价格4))
                    {
                        _buffer.Append("导入价格4格式有错误!");
                    }
                    if (!reg.IsMatch(itm.最小起订量4))
                    {
                        _buffer.Append("导入最小起订量4格式有错误!");
                    }

                }
            }
            if (_buffer.Length > 0)
            {
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_CONTRACT_CONTROLLER), "IMPORT_CONTRACT_CHECK",_buffer.ToString());
                return _buffer.ToString();
            }
            return string.Empty;
        }
        public static ResultObject<bool> EXCEL_IMPORT_CONTRACT(List<SCP_CONTRACT_EXCEL> p_contract_list, string p_creator, DateTime p_time)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            int line = 1;
           
            foreach (var itm in p_contract_list)
            {
                if (!string.IsNullOrEmpty(IMPORT_CONTRACT_CHECK(itm)))
                {
                    _ret.MessageList.Add(string.Format("第{0}行有错误!", line.ToString()));
                }
                line++;
            }
            try
            {
                if (_ret.MessageList.Count == 0)
                {
                    using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                    {
                        var _contract = p_contract_list.FirstOrDefault();
                        #region 删除老合同
                         var contract=db.TB_CONTRACT.Where(p => p.VendId == _contract.供应商代码 && p.ContractNo == _contract.合同编号);
                        if (contract.Count() > 0)
                        {
                            var c = contract.FirstOrDefault();
                            if (!string.IsNullOrEmpty(c.BillNo))
                            {
                                var detailPrice = db.TB_CONTRACT_DETAIL_PRICE.Where(p => p.BillNo ==c.BillNo);
                                db.TB_CONTRACT_DETAIL_PRICE.RemoveRange(detailPrice);
                                var detail=db.TB_CONTRACT_DETAIL.Where(p => p.BillNo ==c.BillNo);
                                db.TB_CONTRACT_DETAIL.RemoveRange(detail);
                                db.TB_CONTRACT.Remove(c);
                            }
                        }
                        #endregion
                        var _tbContract = new TB_CONTRACT();
                        _tbContract.BillNo = MakeCodeHelper.MakeBillCode("HT");
                        _tbContract.VendName = _contract.供应商名称;
                        _tbContract.VendId = _contract.供应商代码;
                        _tbContract.CreateUser = p_creator;
                        _tbContract.ContractNo = _contract.合同编号;
                        _tbContract.IsDeleted = false;
               
                        db.TB_CONTRACT.Add(_tbContract);


                      var list = p_contract_list.Distinct(new SCP_CONTRACT_EXCEL_COMPARE()).ToList();
                        foreach (var itm in list)
                        {
                            var _tbContract_detail = new TB_CONTRACT_DETAIL();
                            _tbContract_detail.ContractNo = _tbContract.ContractNo;
                            _tbContract_detail.BillNo = _tbContract.BillNo;
                            _tbContract_detail.PartCode = itm.供应商物料号;
                            _tbContract_detail.CreateUser = _tbContract.CreateUser;
                            _tbContract_detail.CreateTime = _tbContract.CreateTime;
                            _tbContract_detail.IsDeleted = _tbContract.IsDeleted;
                            _tbContract_detail.PartName = itm.物料描述;
                            _tbContract_detail.Unit = itm.单位;
                            db.TB_CONTRACT_DETAIL.Add(_tbContract_detail);
                        }
                        foreach (var itm in p_contract_list)
                        {

                            if (!string.IsNullOrEmpty(itm.价格1) && !string.IsNullOrEmpty(itm.最小起订量1))
                            {
                                var _detail_price = new TB_CONTRACT_DETAIL_PRICE();
                                _detail_price.BeginTime = ConvertHelper.To<DateTime>(itm.开始日期);
                                _detail_price.EndTime = ConvertHelper.To<DateTime>(itm.结束日期);
                                _detail_price.ContractNo = _tbContract.ContractNo;
                                _detail_price.QtyBegin = int.Parse(itm.最小起订量1);
                                _detail_price.QtyEnd = !string.IsNullOrEmpty(itm.最小起订量2)? int.Parse(itm.最小起订量2):999999999;
                                _detail_price.BillNo = _tbContract.BillNo;
                                _detail_price.IsDeleted = false;
                                _detail_price.PartCode = itm.供应商物料号;
                                _detail_price.Price = decimal.Parse(itm.价格1);
                                _detail_price.VendId = itm.供应商代码;
                                _detail_price.CreateUser = _tbContract.CreateUser;
                                _detail_price.CreateTime = _tbContract.CreateTime;
                                db.TB_CONTRACT_DETAIL_PRICE.Add(_detail_price);
                            }
                            if (!string.IsNullOrEmpty(itm.价格2) && !string.IsNullOrEmpty(itm.最小起订量2))
                            {
                                var _detail_price = new TB_CONTRACT_DETAIL_PRICE();
                                _detail_price.BeginTime = ConvertHelper.To<DateTime>(itm.开始日期);
                                _detail_price.EndTime = ConvertHelper.To<DateTime>(itm.结束日期);
                                _detail_price.ContractNo = _tbContract.ContractNo;
                                _detail_price.BillNo = _tbContract.BillNo;
                                _detail_price.IsDeleted = false;
                                _detail_price.PartCode = itm.供应商物料号;
                                _detail_price.QtyBegin = int.Parse(itm.最小起订量2);
                                _detail_price.QtyEnd = !string.IsNullOrEmpty(itm.最小起订量3) ? int.Parse(itm.最小起订量3) : 999999999;
                                _detail_price.Price = decimal.Parse(itm.价格2);
                                _detail_price.VendId = itm.供应商代码;
                                _detail_price.CreateUser = _tbContract.CreateUser;
                                _detail_price.CreateTime = _tbContract.CreateTime;
                                db.TB_CONTRACT_DETAIL_PRICE.Add(_detail_price);
                            }
                            if (!string.IsNullOrEmpty(itm.价格3) && !string.IsNullOrEmpty(itm.最小起订量3))
                            {
                                var _detail_price = new TB_CONTRACT_DETAIL_PRICE();
                                _detail_price.BeginTime = ConvertHelper.To<DateTime>(itm.开始日期);
                                _detail_price.EndTime = ConvertHelper.To<DateTime>(itm.结束日期);
                                _detail_price.ContractNo = _tbContract.ContractNo;
                                _detail_price.BillNo = _tbContract.BillNo;
                                _detail_price.IsDeleted = false;
                                _detail_price.PartCode = itm.供应商物料号;
                                _detail_price.QtyBegin = int.Parse(itm.最小起订量3);
                                _detail_price.QtyEnd = !string.IsNullOrEmpty(itm.最小起订量4) ? int.Parse(itm.最小起订量4) : 999999999;
                                _detail_price.CreateUser = _tbContract.CreateUser;
                                _detail_price.CreateTime = _tbContract.CreateTime;
                                _detail_price.Price = decimal.Parse(itm.价格3);
                                _detail_price.VendId = itm.供应商代码;
                                db.TB_CONTRACT_DETAIL_PRICE.Add(_detail_price);
                            }
                            if (!string.IsNullOrEmpty(itm.价格4) && !string.IsNullOrEmpty(itm.最小起订量4))
                            {
                                var _detail_price = new TB_CONTRACT_DETAIL_PRICE();
                                _detail_price.BeginTime = ConvertHelper.To<DateTime>(itm.开始日期);
                                _detail_price.EndTime = ConvertHelper.To<DateTime>(itm.结束日期);
                                _detail_price.ContractNo = _tbContract.ContractNo;
                                _detail_price.BillNo = _tbContract.BillNo;
                                _detail_price.IsDeleted = false;

                                _detail_price.PartCode = itm.供应商物料号;
                                _detail_price.QtyBegin = int.Parse(itm.最小起订量3);
                                _detail_price.QtyEnd = 999999999;
                                _detail_price.Price = decimal.Parse(itm.价格4);
                                _detail_price.VendId = itm.供应商代码;
                                _detail_price.CreateUser = _tbContract.CreateUser;
                                _detail_price.CreateTime = _tbContract.CreateTime;
                                db.TB_CONTRACT_DETAIL_PRICE.Add(_detail_price);
                            }
                        }



                        int state = db.SaveChanges();
                        if (state != -1)
                        {
                            _ret.State = ReturnStatus.Succeed;
                            _ret.Result = true;
                        }
                        else
                        {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                        }
                    }
                }
                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_CONTRACT_CONTROLLER), "EXCEL_IMPORT_CONTRACT", 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_CONTRACT_CONTROLLER), "EXCEL_IMPORT_CONTRACT", 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_CONTRACT_CONTROLLER), "EXCEL_IMPORT_CONTRACT", 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_CONTRACT_CONTROLLER), "EXCEL_IMPORT_CONTRACT", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;

        }


    }
}