using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Migrations;
using System.Data.Entity.Validation;
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;
using CK.SCP.Models.AppBoxEntity;
using CK.SCP.Models.ScpEntity.ExcelExportEnttity;
using System.Data.SqlClient;

namespace CK.SCP.Controller
{
    public class SCP_ASN_CONTROLLER
    {

        public static DataTable Get_CUSTOM_PAGE_List(V_TB_ASN p_entity)
        {
            string _sql= "SELECT COUNT(*) 标包数量,SUM(Qty) 发货数量,BillNum 发货单号,PoBillLine 行号,PoUnit 单位,PartDesc1 +PartDesc2 as 零件描述,a.PartCode 零件编号,'' as 分包数量\n" +
       "  from TS_BARCODE_CUSTOM    A left join TA_PART B ON A.PartCode=B.PartCode AND A.Site=B.Site  where BillNum='{0}' GROUP by a.PartCode,BillNum,PoBillLine,PoUnit,PartDesc1,PartDesc2";
            string _sql1 = "select qty FROM [TS_BARCODE_CUSTOM] where billnum ='{0}' and partcode='{1}'";
            DataTable dt = new DataTable();          
            var dbSetting = GlobalConfig.ScpDatabase;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            try
            {
                var strConn = EntitiesFactory.GetEfConnectionString(dbSetting);

                conn.ConnectionString = strConn;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = string.Format(_sql, p_entity.AsnBillNum);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(dt);
                foreach (DataRow row in dt.Rows)
                {
                    DataTable dt1 = new DataTable();
                    SqlCommand cmd1 = new SqlCommand();
                    cmd1.Connection = conn;
                    cmd1.CommandText = string.Format(_sql1, p_entity.AsnBillNum,row["零件编号"].ToString());
                    SqlDataAdapter adapter1 = new SqlDataAdapter(cmd1);
                    adapter1.Fill(dt1);
                    if (dt1.Rows.Count > 0)
                    {
                        List<string> _ls = new List<string>();
                        foreach (DataRow _row in dt1.Rows)
                        {
                            _ls.Add(_row[0].ToString());
                        }
                        row["分包数量"] = string.Join("("+row["单位"].ToString() +")"+ ";", _ls.ToArray())+ "("+row["单位"].ToString()+")";
                    }
                }
            }
            catch(Exception e)
            {
                conn.Close();
                throw e;
            }
            return dt;            
        }
        public static void Get_V_TB_ASN_List(V_TB_ASN p_entity, Action<ResultObject<IQueryable<V_TB_ASN>>> p_action,string p_language="CN")
        {
            ResultObject<IQueryable<V_TB_ASN>> _ret = new ResultObject<IQueryable<V_TB_ASN>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_ASN> q = db.V_TB_ASN;

                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum==p_entity.AsnBillNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AskBillNum))
                    {
                        q = q.Where(p => p.AskBillNum==p_entity.AskBillNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum==p_entity.PoBillNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId==p_entity.VendId);
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ShipUser))
                    {
                        q = q.Where(p => p.ShipUser.Contains(p_entity.ShipUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceiveUser))
                    {
                        q = q.Where(p => p.ReceiveUser.Contains(p_entity.ReceiveUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ErpBillNum))
                    {
                        q = q.Where(p => p.ErpBillNum.Contains(p_entity.ErpBillNum));
                    }
                    if (p_entity.ModType != null)
                    {
                        q = q.Where(p => p.ModType == p_entity.ModType);
                    }
                    //if (!string.IsNullOrEmpty(p_entity.Contacter))
                    //{
                    //    q = q.Where(p => p.Contacter.Contains(p_entity.Contacter));
                    //}
                    if (!string.IsNullOrEmpty(p_entity.Buyer))
                    {
                        q = q.Where(p => p.Buyer.Contains(p_entity.Buyer));
                    }

                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }

                    if (!string.IsNullOrEmpty(p_entity.State_DESC))
                    {
                        q = q.Where(p => p.State_DESC.Contains(p_entity.State_DESC));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ModType_DESC))
                    {
                        q = q.Where(p => p.ModType_DESC.Contains(p_entity.ModType_DESC));
                    }
                    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);
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }
                    if (p_entity.UserInVendIds != null && p_entity.UserInVendIds.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInVendIds.Contains(p.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.SubSite))
                    {
                        q = q.Where(p => p.SubSite == p_entity.SubSite);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Extend1))
                    {
                        q = q.Where(p => p.Extend1 == p_entity.Extend1);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Extend2))
                    {
                        q = q.Where(p => p.Extend2 == p_entity.Extend2);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Extend3))
                    {
                        q = q.Where(p => p.Extend3 == p_entity.Extend3);
                    }
                    _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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_List", e.Message);
                throw e;
            }
        }
        public static void Get_V_TB_ASN_DETAIL_List(V_TB_ASN_DETAIL p_entity, Action<ResultObject<IQueryable<V_TB_ASN_DETAIL>>> p_action)
        {
            ResultObject<IQueryable<V_TB_ASN_DETAIL>> _ret = new ResultObject<IQueryable<V_TB_ASN_DETAIL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_ASN_DETAIL> q = db.V_TB_ASN_DETAIL;

                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (p_entity.PoLine != 0)
                    {
                        q = q.Where(p => p.PoLine == p_entity.PoLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    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.Price != 0)
                    {
                        q = q.Where(p => p.Price == p_entity.Price);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Currency))
                    {
                        q = q.Where(p => p.Currency.Contains(p_entity.Currency));
                    }
                    if (p_entity.PackQty != 0)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                    if (p_entity.UnConv != 0)
                    {
                        q = q.Where(p => p.UnConv == p_entity.UnConv);
                    }
                    if (!string.IsNullOrEmpty(p_entity.DockCode))
                    {
                        q = q.Where(p => p.DockCode.Contains(p_entity.DockCode));
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    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.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CurrencyDesc))
                    {
                        q = q.Where(p => p.CurrencyDesc.Contains(p_entity.CurrencyDesc));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch.Contains(p_entity.VendBatch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }

                    _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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_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_ASN_CONTROLLER), "Get_V_TB_ASN_DETAIL_List", e.Message);
                throw e;
            }

        }

        public static ResultObject<bool> Save_TB_ASN_STATE(List<string> p_list, AsnState p_state)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    if (db.TB_ASN.Where(p => p_list.Contains(p.AsnBillNum) && p.IsDeleted ==false).Count() == 0)
                    {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                            _ret.Message = "存在删除记录不能操作!";                           
                    }
                    else
                    { 
                        if (p_state == AsnState.New)
                        {
                            var _ls = db.TB_ASN.Where(p => p_list.Contains(p.AsnBillNum)).ToList();
                            _ls.ForEach(p => p.State = (int)AskState.New);
                            db.TB_ASN.AddOrUpdate(p => p.AsnBillNum, _ls.ToArray());
                        }
                        //if (p_state == AsnState.Ship)
                        //{
                        //    var _ls = db.TB_ASN.Where(p => p_list.Contains(p.AsnBillNum) && p.IsDeleted == false).ToList();
                        //    if (_ls.Count(p => p.State == (int)ShipState.New) == _ls.Count)
                        //    {
                        //        var p = _ls[0];
                        //        #region 代办流程提示收货人
                        //        TB_PENING_ITEMS pending = new TB_PENING_ITEMS();
                        //        pending.ITEM_NO = p.AsnBillNum;
                        //        pending.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.NEW_ASN;
                        //        pending.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        //        pending.GUID = Guid.NewGuid();
                        //        pending.VEND_ID = p.VendId;
                        //        pending.ROLE_NAME = "物流人员";
                        //        pending.SENDER = p.CreateUser;
                        //        pending.SENDING_TIME = p.CreateTime;
                        //        pending.RENEWER = p.CreateUser;
                        //        pending.RENEW_TIME = p.CreateTime;
                        //        pending.ITEM_CONTENT = string.Format("订单编号{0}发货单编号{1}已发货", p.PoBillNum, p.AsnBillNum);
                        //        db.TB_PENING_ITEMS.Add(pending);
                        //        #endregion;

                        //    }
                        //    else
                        //    {
                        //        _ret.State = ReturnStatus.Failed;
                        //        _ret.Result = false;
                        //        _ret.Message = "选择数据有不是新建状态单据!";
                        //    }
                        //}
                        if (p_state == AsnState.Reject)
                        {
                            var _ls = db.TB_ASN.Where(p => p_list.Contains(p.AsnBillNum)).ToList();
                            int count = _ls.Count(p => p.State == (int)AsnState.New);
                            if (_ls.Count == count)
                            {
                                List<string> _askbill = new List<string>();
                                _ls.ForEach(p => {
                                    
                                    p.State = (int)AskState.Reject;
                                    p.IsDeleted = true;
                                    var asnDetail = db.TB_ASN_DETAIL.Where(itm => itm.AsnBillNum == p.AsnBillNum).ToList();
                                    asnDetail.ForEach(itm =>{
                                        itm.IsDeleted = true;
                                        itm.State= (int)AskState.Reject;
                                    });
                                    db.TB_ASN_DETAIL.AddOrUpdate(itm => itm.UID, asnDetail.ToArray());

                                });
                                db.TB_ASN.AddOrUpdate(p => p.AsnBillNum, _ls.ToArray());
                                
                                
                            }
                            else
                            {
                                _ret.State = ReturnStatus.Failed;
                                _ret.Result = false;
                                _ret.Message = string.Format("选择记录中有,不是新建状态不能作废!");
                            }

                        }
                        if (string.IsNullOrEmpty(_ret.Message))
                        {
                            if (db.SaveChanges() != -1)
                            {
                                _ret.State = ReturnStatus.Succeed;
                                _ret.Result = true;
                            }
                            else
                            {
                                _ret.State = ReturnStatus.Failed;
                                _ret.Result = false;
                                _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.Result = false;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_ASN_CONTROLLER), "Save_TB_ASN_STATE", 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_ASN_CONTROLLER), "Save_TB_ASN_STATE", 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_ASN_CONTROLLER), "Save_TB_ASN_STATE", 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_ASN_CONTROLLER), "Save_TB_ASN_STATE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static DataSet ASN_REPORT(string p_AsnBillNum)
        {
            DataSet ds = new DataSet();
            SCP_ASN_CONTROLLER.Get_V_TB_ASN_List(new V_TB_ASN { AsnBillNum = p_AsnBillNum }, (ret) =>
            {
                if (ret.State == ReturnStatus.Succeed)
                {
                    if (ret.Result.Count() > 0)
                    {
                        var _asn = ret.Result.FirstOrDefault();
                        V_ASN_PRINT _print = new V_ASN_PRINT();
                        _print.FileNo = "";
                        _print.DeliveryNo = _asn.AsnBillNum;
                        _print.ChineseAddress = _asn.Site_Desc;
                        _print.EnglishAddress = "";
                        _print.SupplierNo = _asn.VendId;
                        _print.SupplierName = _asn.VendName;
                        _print.SupplierContacter = _asn.ShipUser;
                        _print.DueDeliveryDate = _asn.ReceiveTime.ToString();
                        _print.MaterialPlanner = _asn.Buyer;
                        _print.CAAIPhone = "";
                        _print.CAAIFax = "";
                        _print.Site = _asn.Site;
          
                        using (AppBoxContext _appdb = EntitiesFactory.CreateAppBoxInstance())
                        {
                            StringBuilder _buffer = new StringBuilder();
                            var _ls = _appdb.Users.Where(p => p.Roles.Select(itm => itm.Name).Contains("物流人员") && p.TA_FACTORY.Select(itm => itm.ErpDomain).Contains(_asn.Site)).ToList();
                            _ls.ForEach(itm =>
                            {
                                _buffer.Append(itm.ChineseName + "/" + itm.CellPhone + ";");
                            });
                            _print.CAAIPhone = _buffer.ToString();
                        }
                        var dt = ConvertHelper.ToDataTable(new List<V_ASN_PRINT> { _print });
                        ds.Tables.Add(dt);
                        List<V_TB_PO_DETAIL> _lst = new List<V_TB_PO_DETAIL>();
                        SCP_PO_CONTROLLER.Get_V_TB_PO_DETAIL_List(new V_TB_PO_DETAIL() { PoBillNum = _asn.PoBillNum },rs=>{

                            if (rs.State == ReturnStatus.Succeed)
                            {
                               _lst= rs.Result.ToList();
                            }

                        });
                        SCP_ASN_CONTROLLER.Get_V_TB_ASN_DETAIL_List(new V_TB_ASN_DETAIL() { AsnBillNum = p_AsnBillNum }, (retobj) =>
                        {
                            if (retobj.State == ReturnStatus.Succeed)
                            {
                                List<V_ASN_PRINT_DETAIL> _lsDetail = new List<V_ASN_PRINT_DETAIL>();
                                var _ls = retobj.Result.OrderByDescending(p=>p.PoLine).ToList();
                                _ls.ForEach(p =>
                                {
                                    V_ASN_PRINT_DETAIL _detail = new V_ASN_PRINT_DETAIL();
                                    _detail.PartNo = p.PartCode;
                                    _detail.PartDesc = p.PartDesc1;
                                    _detail.Unit = p.PoUnit;
                                    _detail.STD = p.PackQty.ToString();
                                    _detail.Boxes = (Math.Truncate((p.Qty / p.PackQty)) + (((p.Qty % p.PackQty) > 0) ? 1 : 0)).ToString();
                                    _detail.DeliverQty = p.Qty.ToString();
                                    _detail.ReceiveQty = p.Qty.ToString();
                                    _detail.PoNo = p.PoBillNum+"."+p.AskBillNum;
                                    _detail.LineNO = p.PoLine.ToString();
                                    _detail.Memo = p.Remark;
                                    _detail.Batch = p.Batch;
                                    _detail.DockCode = p.DockCode;
                                    _detail.ProjectId = _lst.Where(itm => itm.PartCode == p.PartCode).FirstOrDefault().ProjectId;
                                    _lsDetail.Add(_detail);
                                });
                                
                                var tb = ConvertHelper.ToDataTable(_lsDetail);
                                ds.Tables.Add(tb);
                            }
                        });
                    }
                }
            });
            return ds;
        }

        public static DataSet ARRIVE_REPORT(string p_AsnBillNum)
        {
            DataSet ds = new DataSet();
            SCP_ASN_CONTROLLER.Get_V_TB_ASN_List(new V_TB_ASN { AsnBillNum = p_AsnBillNum }, (ret) => {
                if (ret.State == ReturnStatus.Succeed)
                {
                    if (ret.Result.Count() > 0)
                    {
                        var _asn = ret.Result.FirstOrDefault();
                        V_ARRIVE_PRINT _print = new V_ARRIVE_PRINT();
                        if (_asn.ShipTime != null)
                        {
                            DateTime dttemp;
                            if (DateTime.TryParse(_asn.ShipTime.ToString(), out dttemp))
                            {
                                _print.ShipTimeDate = dttemp.ToString("yyyy-MM-dd");//发货日期
                            }
                        }
                        if (_asn.ReceiveTime != null)
                        {
                            DateTime dttemp;
                            if (DateTime.TryParse(_asn.ReceiveTime.ToString(), out dttemp))
                            {
                                _print.DueDeliveryDate = dttemp.ToString("yyyy-MM-dd");//到货日期
                            }
                        }
                        _print.SupplierName = _asn.VendName;//发货单位
                        _print.SupplierNo = _asn.VendId;//供应商代码
                        _print.SupplierContacter = _asn.ShipUser;//供应商联系人
                        _print.DeliveryNo = _asn.AsnBillNum;
                        _print.ChineseAddress = _asn.Site_Desc;
                        _print.EnglishAddress = "";
                        _print.MaterialPlanner = _asn.Buyer;//采购联系人
                        _print.MaterialPhone = _asn.BuyerPhone;//采购联系人电话
                        _print.CAAIPhone = "";
                        _print.CAAIFax = "";
                        _print.STDCOUNT = "0";
                        var dt = ConvertHelper.ToDataTable(new List<V_ARRIVE_PRINT> { _print });
                        ds.Tables.Add(dt);

                        SCP_ASN_CONTROLLER.Get_V_TB_ASN_DETAIL_List(new V_TB_ASN_DETAIL() { AsnBillNum = p_AsnBillNum }, (retobj) => {
                            decimal stdtemp = 0;

                            if (retobj.State == ReturnStatus.Succeed)
                            {
                                List<V_ARRIVE_PRINT_DETAIL> _lsDetail = new List<V_ARRIVE_PRINT_DETAIL>();
                                var _ls = retobj.Result.ToList();
                                _ls.ForEach(p => {

                                    V_ARRIVE_PRINT_DETAIL _detail = new V_ARRIVE_PRINT_DETAIL();
                                    _detail.PartNo = p.PartCode;
                                    _detail.PartDesc = p.PartDesc1;
                                    _detail.Unit = p.PoUnit;
                                    _detail.STD = p.PackQty.ToString();
                                    _detail.Boxes = (Math.Truncate((p.Qty / p.PackQty)) + (((p.Qty % p.PackQty) > 0) ? 1 : 0)).ToString();
                                    _detail.DeliverQty = p.Qty.ToString();
                                    _detail.ReceiveQty = p.Qty.ToString();
                                    _detail.PoNo = _print.DeliveryNo+"("+p.PoBillNum+")";
                                    _detail.LineNO = p.PoLine.ToString();
                                    _detail.Memo = p.Remark;
                                    _detail.DockCode = p.DockCode;
                                    _detail.ArriveState = GetArriveState(p.PoBillNum, p.PoLine, p.PartCode, p.Batch);
                                    _detail.SpecialState = string.Empty;
                                    _detail.VendBatch = p.VendBatch;
                                    if (p.ProduceDate!= null)
                                    {
                                        DateTime dttemp;
                                        if (DateTime.TryParse(p.ProduceDate.ToString(), out dttemp))
                                        {
                                        _detail.ProduecDate = dttemp.ToString("yyyy-MM-dd");//到货日期
                                        }
                                    }
                                    //  stdtemp +=_detail.Boxes;
                                    stdtemp += Convert.ToDecimal( _detail.Boxes);
                                    _lsDetail.Add(_detail);
                                });
                                ds.Tables[0].Rows[0]["STDCOUNT"] = stdtemp.ToString();
                                var tb = ConvertHelper.ToDataTable(_lsDetail);
                                ds.Tables.Add(tb);
                            }
                        });

                    }
                }
            });
            return ds;
        }
        
        private static string GetArriveState(string PoBillNum, int PoLine, string PartCode, string Batch)
        {
            string strResult = "未到货";
            using (ScpEntities db = EntitiesFactory.CreateScpInstance())
            {
                TB_ARRIVE_DETAIL det = db.TB_ARRIVE_DETAIL.FirstOrDefault(p => p.PoBillNum == PoBillNum && p.PoLine == PoLine && p.PartCode == PartCode && p.Batch == Batch);

                if (det != null)
                {
                    strResult = "已到货";
                }
            }

            return strResult;
        }
        public static ResultObject<bool> Del_TB_ASN(List<TB_ASN> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_ASN.Remove(itm);
                    }
                    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_ASN_CONTROLLER), "Del_TB_ASN", 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_ASN_CONTROLLER), "Del_TB_ASN", 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_ASN_CONTROLLER), "Del_TB_ASN", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_ASN_CONTROLLER), "Del_TB_ASN", e.Message); throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> Save_TB_CREATE_BARCODE_CUSTOM(List<V_TB_ASK_DETAIL_PACKAGE> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    List<TS_BARCODE_CUSTOM> _ls = new List<TS_BARCODE_CUSTOM>();
                    if (p_list.Count > 0)
                    {
                        string _asnBillNum = p_list[0].PoBillNum;
                        var _asn = db.TB_PO.Where(p => p.IsDeleted == false && p.PoBillNum == _asnBillNum).FirstOrDefault();
                        List<V_TB_ASK_DETAIL_PACKAGE> _asnList = new List<V_TB_ASK_DETAIL_PACKAGE>();
                        p_list.ForEach(p =>
                        {
                            int _qty = 0;
                            int _packQty = 0;
                            if (int.TryParse(p.Qty.ToString(), out _qty) && int.TryParse(p.PackQty.ToString(), out _packQty))
                            {
                                int _count = _qty / _packQty;
                                if (_qty / _packQty > 0)
                                {
                                    for (int i = 0; i < _count; i++)
                                    {
                                        V_TB_ASK_DETAIL_PACKAGE _asndetail = new V_TB_ASK_DETAIL_PACKAGE();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _packQty;
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asnList.Add(_asndetail);
                                    }
                                    if (_qty % _packQty > 0)
                                    {
                                        V_TB_ASK_DETAIL_PACKAGE _asndetail = new V_TB_ASK_DETAIL_PACKAGE();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty % _packQty;
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                                else
                                {
                                    if (_qty > 0)
                                    {
                                        V_TB_ASK_DETAIL_PACKAGE _asndetail = new V_TB_ASK_DETAIL_PACKAGE();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty;
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                            }
                        });
                        foreach (var itm in _asnList)
                        {
                            var _bar = SCP_BARCODE_CONTROLLER_CUSTOM.CreateBarcode(itm);
                            _ls.Add(_bar);

                        }
                        db.TS_BARCODE_CUSTOM.AddOrUpdate(p => new { p.BarCode, p.BillNum }, _ls.ToArray());
                    }
                    else
                    {
                        _ret.MessageList.Add("选择的发货明细数量为零!");
                    }
                    if (_ret.MessageList.Count == 0)
                    {
                        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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }






        public static ResultObject<bool> Save_TB_CREATE_BARCODE(List<V_TB_ASN_DETAIL> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    List<TS_BARCODE> _ls = new List<TS_BARCODE>();
                    if (p_list.Count > 0)
                    {
                        string _asnBillNum = p_list[0].AsnBillNum;
                        var _asn = db.TB_ASN.Where(p => p.IsDeleted == false && p.AsnBillNum == _asnBillNum).FirstOrDefault();
                        List<V_TB_ASN_DETAIL> _asnList = new List<V_TB_ASN_DETAIL>();
                        p_list.ForEach(p =>
                        {
                            decimal _qty = 0;
                            decimal _packQty = 0;
                            if (decimal.TryParse(p.Qty.ToString(), out _qty) && decimal.TryParse(p.PackQty.ToString(), out _packQty))
                            {
                                decimal _n = _qty / _packQty;
                               var  _count=int.Parse(  Math.Truncate(_n).ToString());
                                if (_qty / _packQty > 0)
                                {
                                    for (int i = 0; i < _count; i++)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _packQty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asndetail.UpdateInfo = p.UpdateInfo;
                                        _asnList.Add(_asndetail);
                                    }
                                    if (_qty % _packQty > 0)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty % _packQty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.UpdateInfo = p.UpdateInfo;
                                        _asndetail.Site = p.Site;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                                else
                                {
                                    if (_qty > 0)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asndetail.UpdateInfo = p.UpdateInfo;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                            }
                        });
                        foreach (var itm in _asnList)
                        {
                            var _bar = SCP_BARCODE_CONTROLLER.CreateBarcode(itm);
                            _ls.Add(_bar);
                        }
                        db.TS_BARCODE.AddOrUpdate(p => new { p.BarCode, p.BillNum }, _ls.ToArray());
                    }
                    else
                    {
                        _ret.MessageList.Add("选择的发货明细数量为零!");
                    }
                    if (_ret.MessageList.Count == 0)
                    {
                        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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        public static ResultObject<bool> Save_TB_CREATE_BARCODE_SYJB(List<V_TB_ASN_DETAIL> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    List<TS_BARCODE> _ls = new List<TS_BARCODE>();
                    if (p_list.Count > 0)
                    {
                        string _asnBillNum = p_list[0].AsnBillNum;
                        var _asn = db.TB_ASN.Where(p => p.IsDeleted == false && p.AsnBillNum == _asnBillNum).FirstOrDefault();
                        List<V_TB_ASN_DETAIL> _asnList = new List<V_TB_ASN_DETAIL>();
                        p_list.ForEach(p =>
                        {
                            int _qty = 0;
                            int _packQty = 0;
                            if (int.TryParse(p.Qty.ToString(), out _qty) && int.TryParse(p.PackQty.ToString(), out _packQty))
                            {
                                int _count = _qty / _packQty;
                                if (_qty / _packQty > 0)
                                {
                                    for (int i = 0; i < _count; i++)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _packQty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asndetail.AskBillNum=p.AskBillNum;
                                        _asnList.Add(_asndetail);
                                    }
                                    if (_qty % _packQty > 0)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty % _packQty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asndetail.AskBillNum = p.AskBillNum;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                                else
                                {
                                    if (_qty > 0)
                                    {
                                        V_TB_ASN_DETAIL _asndetail = new V_TB_ASN_DETAIL();
                                        _asndetail.PoBillNum = p.PoBillNum;
                                        _asndetail.Batch = p.Batch;
                                        _asndetail.PartCode = p.PartCode;
                                        _asndetail.ProduceDate = p.ProduceDate;
                                        _asndetail.Qty = _qty;
                                        _asndetail.AsnBillNum = p.AsnBillNum;
                                        _asndetail.PoLine = p.PoLine;
                                        _asndetail.VendId = p.VendId;
                                        _asndetail.VendBatch = p.VendBatch;
                                        _asndetail.CreateTime = p.CreateTime;
                                        _asndetail.CreateUser = p.CreateUser;
                                        _asndetail.Remark = p.Remark;
                                        _asndetail.PackQty = p.PackQty;
                                        _asndetail.PoUnit = p.PoUnit;
                                        _asndetail.Site = p.Site;
                                        _asndetail.AskBillNum = p.AskBillNum;
                                        _asnList.Add(_asndetail);
                                    }
                                }
                            }

                        });
                        foreach (var itm in _asnList)
                        {
                            var _bar = SCP_BARCODE_CONTROLLER_SYJB.CreateBarcode(itm);
                            _ls.Add(_bar);

                        }
                        db.TS_BARCODE.AddOrUpdate(p => new { p.BarCode, p.BillNum }, _ls.ToArray());
                    }
                    else
                    {
                        _ret.MessageList.Add("选择的发货明细数量为零!");
                    }
                    if (_ret.MessageList.Count == 0)
                    {
                        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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_CREATE_BARCODE", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        public static ResultObject<bool> Get_TS_UNI_API(V_TB_ASN p_asn)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _list = db.TS_UNI_API.Where(p => p.BillNum == p_asn.AsnBillNum).ToList();
                    if (_list.Count > 0)
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;                 
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                }
            }
            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_ASN_CONTROLLER), "Get_TS_UNI_API", 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_ASN_CONTROLLER), "Get_TS_UNI_API", 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_ASN_CONTROLLER), "Get_TS_UNI_API", 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_ASN_CONTROLLER), "Get_TS_UNI_API", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        public static ResultObject<bool> Save_TB_ASN_DETAIL(V_TB_ASN p_asn, List<V_TB_ASN_DETAIL> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {

                    DateTime now = DateTime.Now;
                    List<TB_ASN_DETAIL> _ls = new List<TB_ASN_DETAIL>();
                    var _asn =db.TB_ASN.Where(p => p.IsDeleted == false && p.AsnBillNum == p_asn.AsnBillNum).ToList();
                    if (_asn != null && _asn.Count>0)
                    {
                        _asn.ForEach(p => {
                            p.State = (int)AsnState.Ship;
                            p.CreateTime = now;
                            });
                        db.TB_ASN.AddOrUpdate(p => p.UID, _asn.ToArray());
                        var ask = db.TB_ASK.Where(p => p.IsDeleted == false && p.AskBillNum == p_asn.AskBillNum).ToList();
                        ask.ForEach(p => p.State = (int)AskState.Ship);
                        db.TB_ASK.AddOrUpdate(p => p.UID, ask.ToArray());                     
                        p_entitys.ForEach(itm =>
                        {

                            var _sum = db.V_TB_ASK_DETAIL.Where(p => p.AskBillNum == p_asn.AskBillNum && p.PartCode == itm.PartCode
                              && p.PoBillNum == p_asn.PoBillNum && p.PoLine == itm.PoLine && p.IsDeleted == false).Select(p => p.AskQty).Sum();//要货单要货数量
                            var _currSum = db.V_TB_ASN_DETAIL.Where(p => p.AskBillNum == p_asn.AskBillNum && p.PartCode == itm.PartCode
                              && p.PoBillNum == p_asn.PoBillNum && p.PoLine == itm.PoLine && p.IsDeleted == false).Select(p => p.Qty).Sum();//当前存在发货单数量
                            var _curr = db.V_TB_ASN_DETAIL.Where(p => p.AsnBillNum == p_asn.AsnBillNum && p.PartCode == itm.PartCode
                              && p.PoBillNum == p_asn.PoBillNum && p.PoLine == itm.PoLine && p.IsDeleted == false).Select(p => p.Qty).Sum();
                               var _rejct = db.TB_ARRIVE_DETAIL.Where(p => p.Remark == p_asn.AskBillNum && p.PartCode == itm.PartCode
                            && p.PoBillNum == p_asn.PoBillNum && p.PoLine == itm.PoLine && p.IsDeleted == false&&p.BillType==3).Select(p => p.Qty).ToList().Sum();
                            if (_currSum - _curr + itm.Qty- Math.Abs(_rejct) <= _sum)
                            {
                                TB_ASN_DETAIL _detail = new TB_ASN_DETAIL();
                                _detail.UID = itm.UID;
                                _detail.UnConv = itm.UnConv;
                                _detail.AsnBillNum = itm.AsnBillNum;
                                _detail.DockCode = itm.DockCode;
                                _detail.Currency = itm.Currency;
                                _detail.Batch = itm.Batch;
                                _detail.CreateUser = itm.CreateUser;
                                _detail.CreateTime = now;
                                _detail.PackQty = itm.PackQty;
                                _detail.PartCode = itm.PartCode;
                                _detail.PoLine = itm.PoLine;
                                _detail.PoBillNum = itm.PoBillNum;
                                _detail.Price = itm.Price;
                                _detail.VendBatch = itm.VendBatch;
                                _detail.ProduceDate = itm.ProduceDate;
                                _detail.Remark = itm.Remark;
                                _detail.Qty = itm.Qty;
                                _detail.PoUnit = itm.PoUnit;
                                _detail.LocUnit = itm.LocUnit;
                                _detail.IsDeleted = itm.IsDeleted;
                                _detail.State = (int)AsnState.Ship;

                                _detail.GUID = itm.Guid;
                                _ls.Add(_detail);


                                TS_UNI_API api = UniApiController.CreateBy(p_asn, itm, UniApiType.Receive);
                                api.State = 1;
                                db.TS_UNI_API.AddOrUpdate(api);//同步更新中间表
                            }
                            else
                            {
                                _ret.MessageList.Add(string.Format("行号{0}零件名称:{1}数量合计已大于要货单{2}数量", itm.PoLine, itm.PartDesc1, itm.AskBillNum));
                            }
                        }
                       );
                        var _asnBillNum = _asn[0].AsnBillNum;
                        //var _barcodeList=db.TS_BARCODE.Where(p => p.BillNum == _asnBillNum).ToList();                    
                        //_barcodeList.ForEach(itm => {
                        //   TS_UNI_API _api =UniApiController.CreateBy(_asn[0], itm, UniApiType.BarCode);
                        //    _api.State = 1;
                        //    db.TS_UNI_API.AddOrUpdate(_api);
                        //});
                    }
                    if (_ret.MessageList.Count > 0)
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                    else
                    {
                        db.TB_ASN_DETAIL.AddOrUpdate(p => p.UID, _ls.ToArray());

                        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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", 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_ASN_CONTROLLER), "Save_TB_ASN_DETAIL", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }



        public static ResultObject<bool> Del_TB_ASK_DETAIL(List<TB_ASK_DETAIL> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_ASK_DETAIL.Remove(itm);
                    }
                    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_ASN_CONTROLLER), "Del_TB_ASK_DETAIL", 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_ASN_CONTROLLER), "Del_TB_ASK_DETAIL", 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_ASN_CONTROLLER), "Del_TB_ASK_DETAIL", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_ASN_CONTROLLER), "Del_TB_ASK_DETAIL", e.Message); throw e;
            }
            return _ret;
        }


        public static void Get_V_TB_ASN_DETAIL_VIEW_List(V_TB_ASN_DETAIL_VIEW p_entity, Action<ResultObject<IQueryable<V_TB_ASN_DETAIL_VIEW>>> p_action)
        {
            ResultObject<IQueryable<V_TB_ASN_DETAIL_VIEW>> _ret = new ResultObject<IQueryable<V_TB_ASN_DETAIL_VIEW>>();
          
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_ASN_DETAIL_VIEW> q = db.V_TB_ASN_DETAIL_VIEW;
                    
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (p_entity.PoLine != 0)
                    {
                        q = q.Where(p => p.PoLine == p_entity.PoLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                 
                    if (p_entity.Price != 0)
                    {
                        q = q.Where(p => p.Price == p_entity.Price);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Currency))
                    {
                        q = q.Where(p => p.Currency.Contains(p_entity.Currency));
                    }
                    if (p_entity.PackQty != 0)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                 
                    if (!string.IsNullOrEmpty(p_entity.DockCode))
                    {
                        q = q.Where(p => p.DockCode.Contains(p_entity.DockCode));
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                   
                    if (!string.IsNullOrEmpty(p_entity.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    
                  
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc2))
                    {
                        q = q.Where(p => p.PartDesc2.Contains(p_entity.PartDesc2));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch.Contains(p_entity.VendBatch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId==p_entity.VendId);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AskBillNum))
                    {
                        q = q.Where(p => p.AskBillNum.Contains(p_entity.AskBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceivedPort))
                    {
                        q = q.Where(p => p.ReceivedPort.Contains(p_entity.ReceivedPort));
                    } 
                    if (!string.IsNullOrEmpty(p_entity.PlateNumber))
                    {
                        q = q.Where(p => p.PlateNumber.Contains(p_entity.PlateNumber));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ShipUser))
                    {
                        q = q.Where(p => p.ShipUser.Contains(p_entity.ShipUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceiveUser))
                    {
                        q = q.Where(p => p.ReceiveUser.Contains(p_entity.ReceiveUser));
                    }
                    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);

                    if (p_entity.ShipTimeBegin != null)
                    {

                        q = q.Where(p => p.ShipTime>=p_entity.ShipTimeBegin);
                    }

                    if (p_entity.ShipTimeEnd != null)
                    {
                        q = q.Where(p => p.ShipTime <= p_entity.ShipTimeEnd);


                    }
                    if (p_entity.ReceiveTimeBegin != null)
                    {

                        q = q.Where(p => p.ReceiveTime >= p_entity.ReceiveTimeBegin);
                    }

                    if (p_entity.ReceiveTimeEnd != null)
                    {
                        q = q.Where(p => p.ReceiveTime <= p_entity.ReceiveTimeEnd);


                    }
                    if (p_entity.UserInVendIds != null && p_entity.UserInVendIds.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInVendIds.Contains(p.VendId));
                    }
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_ASN_CONTROLLER), "Get_V_TB_ASN__DETAIL_View_List", e.Message);
                throw e;
            }
      
        }




        //public static List<V_TB_ASK_DETAIL> Get_CAN_SHIPQTY(List<V_TB_ASK_DETAIL> p_list)
        //{
        //    using (ScpEntities db = EntitiesFactory.CreateScpInstance())
        //    {
        //        var detail = p_list[0];
        //        var list = db.V_TB_ASN_DETAIL.Where(p => p.IsDeleted == false && detail.AskBillNum == p.AskBillNum).ToList();

        //        var groupList = list.GroupBy(p => new { p.PoBillNum, p.PoLine, p.PartCode, p.AskBillNum }).Select(
        //        p => new {
        //            ShipSum = p.Sum(itm => itm.Qty),
        //            PoLine = p.Key.PoLine,
        //            PoBillNum = p.Key.PoBillNum,
        //            PartCode = p.Key.PartCode,
        //            AskBillNum = p.Key.AskBillNum
        //        }).ToList();

        //        p_list.ForEach(itm => {

        //            groupList.ForEach(p =>
        //            {
        //                if (p.PoBillNum == itm.PoBillNum && p.PoLine == itm.PoLine && p.PartCode == itm.PartCode)
        //                {
        //                    itm.ShippedQty = p.ShipSum;
        //                }
        //            });
        //            decimal a = itm.AskQty - (itm.ShippedQty == null ? 0 : (decimal)itm.ShippedQty);
        //            itm.CanQty = a;
        //            itm.PackQty = (itm.PackQty == 0) ? 1 : itm.PackQty;
        //        });
        //    }
        //    return p_list;
        //}

        public static List<V_TB_ASN_DETAIL> Get_CAN_PALLET_QTY(List<V_TB_ASN_DETAIL> p_list)
        {
            using (ScpEntities db = EntitiesFactory.CreateScpInstance())
            {


                var detail = p_list[0];
                var list = db.V_TB_PALLET_DETAIL.Where(p => p.IsDeleted == false && detail.AsnBillNum == p.AsnBillNum).ToList();

                var groupList=list.GroupBy(p => new { p.AsnBillNum, p.PoBillNum, p.PoLine, p.PartCode })
                    .Select(

                    p => new
                    {
                        PalletSum = p.Sum(itm => itm.Qty),
                        PoLine = p.Key.PoLine,
                        PoBillNum = p.Key.PoBillNum,
                        PartCode = p.Key.PartCode,
                        AsnBillNum=p.Key.AsnBillNum,
                    }

                    ).ToList();
             
                p_list.ForEach(itm =>
                {
                    decimal palletedNum = 0;
                    groupList.ForEach(p =>
                    {
                        if (p.PoBillNum == itm.PoBillNum && p.PoLine == itm.PoLine && p.PartCode == itm.PartCode)
                        {
                            palletedNum = p.PalletSum;
                        }
                    });
                    decimal a = itm.Qty- palletedNum;
                    itm.CanQty = a;
                    itm.PackQty = (itm.PackQty == 0) ? 1 : itm.PackQty;
                });
            }
            return p_list;
        }

        /// <summary>
        /// 创建发货单
        /// </summary>
        /// <param name="p_ask"></param>
        /// <param name="p_list"></param>
        /// <param name="p_PlateNumber"></param>
        /// <param name="p_buyer"></param>
        /// <param name="p_buyerPhone"></param>
        /// <returns></returns>
        public static ResultObject<bool> Save_ASN_TO_PALLET(V_TB_ASN p_ask, List<V_TB_ASN_DETAIL> p_list, string p_PlateNumber
        , string p_buyer, string p_buyerPhone)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _asn=db.V_TB_ASN.Where(p => p.AsnBillNum == p_ask.AsnBillNum).FirstOrDefault();
                    TB_PALLET _t = new TB_PALLET();
                    _t.AsnBillNum = _asn.AsnBillNum;
                    _t.PalletNum=    SCP_BILLCODE_CONTROLLER.MakePalletCode();
                    _t.AskBillNum = _asn.AskBillNum;
                    _t.PoBillNum = _asn.PoBillNum;
                    _t.ReceivedPort = _asn.ReceivedPort;
                    _t.CreateUser = _asn.CreateUser;
                    _t.CreateTime = _asn.CreateTime;
                    _t.UpdateUser = p_buyer;
                    _t.UpdateTime = _asn.CreateTime;
                    _t.ReceiveUser = _asn.Buyer;
                    _t.ReceiveTime = _asn.ReceiveTime;
                    _t.VendId = _asn.VendId;
                    _t.IsDeleted = false;//操作员
                    _t.CreateTime = _asn.CreateTime;
                    _t.CreateUser = _asn.CreateUser;
                    _t.Site = _asn.Site;
                    _t.Remark = _asn.Remark;
                    _t.State = (int)AsnState.New;
                    _t.Remark = p_ask.Remark;
                    _t.GUID = Guid.NewGuid();
                    _t.PlateNumber = string.Empty;
                    _t.ShipUser = p_ask.ShipUser;
                    _t.ShipTime = p_ask.ShipTime;
                    _t.ReceiveTime = p_ask.ReceiveTime;
                    db.TB_PALLET.AddOrUpdate(p => p.PalletNum, _t);
                    List<TB_PALLET_DETAIL> _list = new List<TB_PALLET_DETAIL>();
                    foreach (var itm in p_list)
                    {
                        var _asndetail=db.V_TB_ASN_DETAIL.Where(p => p.AsnBillNum == itm.AsnBillNum && p.PartCode == itm.PartCode && p.PoBillNum == itm.PoBillNum && p.PoLine == itm.PoLine && p.IsDeleted==false).FirstOrDefault(); 
                        TB_PALLET_DETAIL _tDetail = new TB_PALLET_DETAIL();
                        _tDetail.PoBillNum = _t.PoBillNum;
                        _tDetail.AsnBillNum = _t.AsnBillNum;
                        _tDetail.PalletNum = _t.PalletNum;
                        _tDetail.PoLine = _asndetail.PoLine;
                        _tDetail.PoUnit = _asndetail.PoUnit;
                        _tDetail.Batch = _asndetail.Batch;
                        if (!string.IsNullOrEmpty(_asndetail.VendBatch))
                        {
                            _tDetail.VendBatch = _asndetail.VendBatch;
                        }
                        else
                        {
                            _tDetail.VendBatch = _asndetail.Batch;
                        }
                        _tDetail.PackQty = _asndetail.PackQty == 0 ? 1 : _asndetail.PackQty;
                        _tDetail.PartCode = _asndetail.PartCode;
                        _tDetail.State = (int)AsnState.New;

                        _tDetail.Qty = (decimal)itm.Qty;
                        _tDetail.Price = _asndetail.Price;
                        _tDetail.EndTime = _asndetail.EndTime;
                        _tDetail.CreateTime = _t.CreateTime;
                        _tDetail.CreateUser = _t.CreateUser;
                        _tDetail.ProduceDate = _asndetail.ProduceDate;
                        _tDetail.IsDeleted = false;
                        _tDetail.DockCode = _asndetail.ReceivedPort;
                        _tDetail.LocUnit = _asndetail.LocUnit;
                        _tDetail.UnConv = _asndetail.UnConv;
                        _tDetail.State = _t.State;
                        _tDetail.ReceivedPort = _asndetail.ReceivedPort;
                        _tDetail.GUID = Guid.NewGuid();
                        db.TB_PALLET_DETAIL.Add(_tDetail);
                        //var _order_detail = db.TB_ASK_DETAIL.Where(p => p.UID == itm.UID).FirstOrDefault();
                        //_order_detail.ShippedQty = (decimal)itm.ShippedQty;
                        //db.TB_ASK_DETAIL.AddOrUpdate(p => p.UID, _order_detail);
                    }
                    int state = db.SaveChanges();
                    if (state != -1)
                    {
                        //var _askDetailList = db.V_TB_ASK_DETAIL.Where(p => p.AskBillNum == p_ask.AskBillNum && p.IsDeleted == false).ToList();//查询要货单明细
                        //var _lst = Get_CAN_SHIPQTY(_askDetailList);//算出可发数量
                        //if (_lst.Select(p => p.CanQty).Sum() <= 0)//可发数量为零时,修改状态
                        //{
                        //    var _ary = db.TB_ASK.Where(p => p.AskBillNum == p_ask.AskBillNum && p.IsDeleted == false).ToList();
                        //    _ary.ForEach(p => p.State = (int)AskState.Ship);
                        //    if (_ary.Count() > 0)
                        //    {
                        //        db.TB_ASK.AddOrUpdate(_ary.ToArray());
                        //    }
                        //}
                        _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_ASK_CONTROLLER), "Save_ASK_TO_ASN", 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_ASK_CONTROLLER), "Save_ASK_TO_ASN", 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_ASK_CONTROLLER), "Save_ASK_TO_ASN", 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_ASK_CONTROLLER), "Save_ASK_TO_ASN", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }




    }
    
}