using CK.SCP.Models;
using CK.SCP.Models.Enums;
using CK.SCP.Models.ExchangeCenterTables;
using CK.SCP.Models.AppBoxEntity;
using CK.SCP.Models.ScpEntity;
using CK.SCP.Models.ScpEntity.ExcelExportEnttity;
using CK.SCP.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Data.Entity.Core;
//using WebSrvAPITest;

namespace CK.SCP.Controller
{
    public class SCP_DC_UNI_CONTROLLER
    {
        public SCP_DC_UNI_CONTROLLER()
        {

        }
        public static ResultObject<List<TEA_SUBSCRIBE>> Get_TEA_SUBSCRIBE_List(TEA_SUBSCRIBE p_entity)
        {
            ResultObject<List<TEA_SUBSCRIBE>> _ret = new ResultObject<List<TEA_SUBSCRIBE>>();
            try
            {
                using (var db =  EntitiesFactory.CreateExchangeCenterInstance())
                {
                    IQueryable<TEA_SUBSCRIBE> q = db.TEA_SUBSCRIBE;
                    if (!string.IsNullOrEmpty(p_entity.TableName))
                    {
                        q = q.Where(p => p.TableName.Contains(p_entity.TableName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Creator))
                    {
                        q = q.Where(p => p.Creator.Contains(p_entity.Creator));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Subscriber))
                    {
                        q = q.Where(p => p.Subscriber.Contains(p_entity.Subscriber));
                    }
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    {
                        q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    }
                    if (p_entity.IsChecked != false)
                    {
                        q = q.Where(p => p.IsChecked == p_entity.IsChecked);
                    }
                    if (p_entity.Enable != false)
                    {
                        q = q.Where(p => p.Enable == p_entity.Enable);
                    }
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q.ToList();
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Get_TEA_SUBSCRIBE_List", e.Message);
                throw e;
            }
            return _ret;
        }



        public ResultObject<bool> Save_TEA_SUBSCRIBE(List<TEA_SUBSCRIBE> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (var db =  EntitiesFactory.CreateExchangeCenterInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TEA_SUBSCRIBE.AddOrUpdate(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Save_TEA_SUBSCRIBE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }



        public ResultObject<bool> Del_TEA_SUBSCRIBE(List<TEA_SUBSCRIBE> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (var db =  EntitiesFactory.CreateExchangeCenterInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TEA_SUBSCRIBE.Remove(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Del_TEA_SUBSCRIBE", e.Message); throw e;
            }
            return _ret;
        }



        public static ResultObject<List<TEA_TASK_SUB>> Get_TEA_TASK_SUB_List(TEA_TASK_SUB p_entity)
        {
            ResultObject<List<TEA_TASK_SUB>> _ret = new ResultObject<List<TEA_TASK_SUB>>();
            try
            {
                using (var db =  EntitiesFactory.CreateExchangeCenterInstance())
                {
                    IQueryable<TEA_TASK_SUB> q = db.TEA_TASK_SUB;
                    if (!string.IsNullOrEmpty(p_entity.TableName))
                    {
                        q = q.Where(p => p.TableName.Contains(p_entity.TableName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Creator))
                    {
                        q = q.Where(p => p.Creator.Contains(p_entity.Creator));
                    }
                    if (p_entity.DataCount != 0)
                    {
                        q = q.Where(p => p.DataCount == p_entity.DataCount);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Subscriber))
                    {
                        q = q.Where(p => p.Subscriber.Contains(p_entity.Subscriber));
                    }
                    if (p_entity.FailedCount != 0)
                    {
                        q = q.Where(p => p.FailedCount == p_entity.FailedCount);
                    }
                    if (!string.IsNullOrEmpty(p_entity.FailedInfo))
                    {
                        q = q.Where(p => p.FailedInfo.Contains(p_entity.FailedInfo));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Domain))
                    {
                        q = q.Where(p => p.Domain.Contains(p_entity.Domain));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    {
                        q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    }
                    if (p_entity.IsChecked != false)
                    {
                        q = q.Where(p => p.IsChecked == p_entity.IsChecked);
                    }
                    //if (!string.IsNullOrEmpty(p_entity.TaskState))
                    //{
                    //    q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    //}
                    q = q.Where(p => p.TaskState==p_entity.TaskState);
                 
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q.OrderBy(p => p.CreateTime).ToList();
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Get_TEA_TASK_SUB_List", e.Message);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> Update_TEA_TASK_SUB(ExchangeCenterContext db, TEA_TASK_SUB p_task)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _task = db.TEA_TASK_SUB.Where(p => p.TaskID == p_task.TaskID && p.TableName == p.TableName && p.Subscriber == "SCP").FirstOrDefault();
                if (_task != null)
                {
                    _task.TaskState = EnumTaskState.Success;
                    _task.DataCount = p_task.DataCount;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Update_TEA_TASK_SUB", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> CREATE_TEA_TASK_SUB(ExchangeCenterContext db, bool p_ismasterslave ,TEA_TASK_SUB p_task)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {               
                var _list = db.TEA_SUBSCRIBE.Where(p => p.Creator == "SCP" && p.TableName == p_task.TableName).ToList();
                foreach (var itm in _list)
                {
                    var _task = new TEA_TASK_SUB();
                    _task.GUID = Guid.NewGuid();
                    _task.TaskID = p_task.TaskID;
                    _task.TaskState = EnumTaskState.Unread;
                    _task.TableName = p_task.TableName;
                    _task.Domain = p_task.Domain;
                    _task.Site = p_task.Site;
                    _task.DataCount = p_task.DataCount;
                    _task.Creator = itm.Creator;
                    _task.CreateTime = DateTime.Now;
                    _task.CreateUser = itm.CreateUser;
                    _task.UpdateTime = DateTime.Now;
                    _task.UpdateUser = itm.CreateUser;
                    _task.Subscriber = itm.Subscriber;
                    db.TEA_TASK_SUB.Add(_task);
                }
                var _task1 = new TEA_TASK();
                _task1.GUID = p_task.GUID;
                _task1.DataCount = _list.Count;
                _task1.TaskID = p_task.TaskID;
                _task1.TableName = p_task.TableName;
                _task1.Domain = p_task.Domain;
                _task1.Site = p_task.Site;
                _task1.IsMasterSlave = p_ismasterslave;
                _task1.Creator = "SCP";
                _task1.CreateTime = DateTime.Now;
                _task1.CreateUser = "SCP";
                _task1.UpdateTime = DateTime.Now;
                _task1.UpdateUser = "SCP";
                db.TEA_TASK.Add(_task1);
                _ret.State = ReturnStatus.Succeed;
            }
            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_ASK_CONTROLLER), "Get_V_TB_ASK_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_ASK_CONTROLLER), "Get_V_TB_ASK_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_ASK_CONTROLLER), "Get_V_TB_ASK_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;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "CREATE_TEA_TASK_SUB", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        public ResultObject<bool> Del_TEA_TASK_SUB(List<TEA_TASK_SUB> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (var db =  EntitiesFactory.CreateExchangeCenterInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TEA_TASK_SUB.Remove(itm);
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_DC_UNI_CONTROLLER), "Del_TEA_TASK_SUB", e.Message); throw e;
            }
            return _ret;
        }


        public static void ReadService(Action<ResultObject<bool>> p_action)
        {
            ResultObject<bool> result = new ResultObject<bool>();
           // ResultObject<List<LogModel>> result = new ResultObject<List<LogModel>>();
            var _result = Get_TEA_TASK_SUB_List(new TEA_TASK_SUB() { TaskState = EnumTaskState.Unread, Subscriber = "SCP"   });
             if (_result.State == ReturnStatus.Succeed)
            {
                foreach (var _task in _result.Result)
                {
                    ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
                    ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
                    DataCenterContext dc = EntitiesFactory.CreateDataCenterInstance();
                    AppBoxContext authdb = EntitiesFactory.CreateAppBoxInstance();
                    using (var scope =
                    new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
                    {
                        IsolationLevel = System.Transactions.IsolationLevel.Serializable,
                        Timeout = new TimeSpan(0, 20, 0)
                    }))
                    {
                        try
                        {
                            switch (_task.TableName)
                            {
                                //case "TED_POD":
                                //    result = UpdatePo(db, scpdb, _task);
                                //    break;
                                case "TED_RECEIPT_MSTR":
                                    if (_task.Creator == "QAD")
                                    {
                                        result = UpdateRecive(db, scpdb, _task);
                                        result.Message = _task.TaskID.ToString();
                                    }
                                    else
                                    {
                                        result = UpdateARRIVE(db, scpdb, _task);
                                        result.Message = _task.TaskID.ToString();
                                    }
                                    break;
                                case "TED_RETURN_MSTR":
                                    result = UpdateReturn(db, scpdb, _task);
                                    result.Message = _task.TaskID.ToString();
                                    break;
                                case "TES_SUPPLIER":
                                    result = UpdateSupplier(db, scpdb,authdb, _task);
                                    result.Message = _task.TaskID.ToString();
                                    break;
                                //case "TES_SUPPLIER_PART":
                                //    result = UpdateSupplierPart(dc, db, scpdb, _task);
                                //    break;
                                case "TES_PART_MSTR":
                                    result = UpdatePart(db, scpdb, _task);
                                    result.Message = _task.TaskID.ToString();
                                    break;
                                //case "TES_SITE":
                                //    result = UpdateFactory(db, scpdb, appscpdb, _task);
                                //    break;
                            }
                            Update_TEA_TASK_SUB(db, _task);
                            EntitiesFactory.SaveDb(scpdb);
                            EntitiesFactory.SaveDb(db);
                            EntitiesFactory.SaveDb(dc);
                            scope.Complete();
                            //  p_action(result);     
                            result.State = ReturnStatus.Succeed;
                            result.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);
                                });
                            }
                            scope.Dispose();
                            result.State = ReturnStatus.Failed;
                            result.ErrorList.Add(dbEx);
                        }
                        catch (OptimisticConcurrencyException ex)//并发冲突异常
                        {

                            scope.Dispose();
                            result.State = ReturnStatus.Failed;
                            result.ErrorList.Add(ex);
                        }
                        catch (Exception ex)
                        {
                            scope.Dispose();
                            result.State = ReturnStatus.Failed;
                            result.ErrorList.Add(ex);
                            result.Message = _task.TaskID.ToString();
                            // result.MessageList.Add("任务编号:" + _task.TaskID + "错误信息:" + ex.Message);
                        }
                    }
                    p_action(result);
                }
            }
            p_action(result);
        }

        public static void WriteService(Action<ResultObject<List<LogModel>>> p_action)
        {
            ResultObject<List<LogModel>> result = new ResultObject<List<LogModel>>();
            List<LogModel> _msglist = new List<LogModel>();
            using (var scope =
            new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
            {
                IsolationLevel = System.Transactions.IsolationLevel.Serializable,
                Timeout = new TimeSpan(0, 20, 0)
            }))
            {
                try
                {
                    ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
                    ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
                    var _list = scpdb.TS_UNI_API.Where(p => p.State == (int)DataState.Enabled).OrderBy(p => p.UID).ToList();
                    var billNumList = _list.Select(p => p.BillNum).Distinct();
                    //if (DateTime.Today.DayOfWeek.ToString() == "Sunday" && DateTime.Now.Hour == 12)//向历史记录表里写入记录
                    //{
                    //    List<TEA_TASK_SUB_HIS> _hisList = new List<TEA_TASK_SUB_HIS>();
                    //    var _taskList = db.TEA_TASK_SUB.Where(p => p.Subscriber == "SCP" && p.TaskState == EnumTaskState.Success).ToList();
                    //    foreach (var itm in _taskList)
                    //    {
                    //        TEA_TASK_SUB_HIS _entity = new TEA_TASK_SUB_HIS();
                    //        _entity.Creator = itm.Creator;
                    //        _entity.Subscriber = itm.Subscriber;                        
                    //        _entity.Domain = itm.Domain;
                    //        _entity.Site = itm.Site;
                    //        _entity.UID = itm.UID;
                    //        _entity.CreateUser = itm.CreateUser;
                    //        _entity.CreateTime = itm.CreateTime;
                    //        _entity.Remark = itm.Remark;
                    //        _entity.UpdateUser = itm.UpdateUser;
                    //        _entity.UpdateTime = itm.UpdateTime;
                    //        _entity.IsChecked = itm.IsChecked;
                    //        _entity.TaskID = itm.TaskID;
                    //        _entity.TaskState = itm.TaskState;
                    //        _entity.GUID = itm.GUID;
                    //        _hisList.Add(_entity);
                    //    }
                    //    db.TEA_TASK_SUB_HIS.AddOrUpdate(_hisList.ToArray());
                    //    db.TEA_TASK_SUB.RemoveRange(_taskList.ToArray());
                    //}
                    foreach (var itm in billNumList)
                    {
                        var _dataList = _list.Where(p => p.BillNum == itm).ToList();
                        var _asnList = _dataList.Where(P => P.InterfaceType == UniApiType.Receive.ToString()).ToList();
                        if (_asnList.Count > 0)
                        {
                            var _taskId = Guid.NewGuid();
                            _msglist.Add(new LogModel() { LogMessage = string.Format("发现发货单信息{0}条", _asnList.Count), LogTime = DateTime.Now.ToString(), TaskId = _taskId.ToString(), TableName = "TED_ASN_MSTR" });                          
                            var ret = UpdateAsn(db, scpdb, _asnList, _taskId);
                            if (ret.State == ReturnStatus.Succeed)
                            {
                                _msglist.Add(ret.Result);
                            }  
                        }
                        var _invoiceList = _dataList.Where(p => p.InterfaceType == UniApiType.Invoice.ToString()).ToList();
                        if (_invoiceList.Count > 0)
                        {
                            var _taskId = Guid.NewGuid();
                            _msglist.Add(new LogModel() { LogMessage = string.Format("发现发票信息{0}条", _invoiceList.Count), LogTime = DateTime.Now.ToString(), TaskId = _taskId.ToString(), TableName = "TED_INVOICE_MSTR" });
                            var ret = UpdateInvoice(db, scpdb,_invoiceList, _taskId);
                            if (ret.State == ReturnStatus.Succeed)
                            {
                                _msglist.Add(ret.Result);
                            }
                        }
                        Thread.Sleep(10);
                    }
                    EntitiesFactory.SaveDb(scpdb);
                    EntitiesFactory.SaveDb(db);
                    scope.Complete();
                    result.State = ReturnStatus.Succeed;
                    result.Result = _msglist;
                }
                catch(Exception e)
                {
                    _msglist.Add(new LogModel() { LogMessage = e.Message, LogTime = DateTime.Now.ToString(), TaskId =string.Empty, TableName = "ERROR" });
                   result.State = ReturnStatus.Failed;
                    result.Result = _msglist;
                    scope.Dispose();

                }
                //finally
                //{
                   
                //}

            }
            p_action(result);
        }

        //public static ResultObject<bool> UpdateAsnDetail(ExchangeCenterContext db, ScpEntities scpdb,List<TS_UNI_API> p_asnDetailList)
        //{
        //    ResultObject<bool> _ret = new ResultObject<bool>();
        //    try
        //    {
        //        foreach (var itm in p_asnDetailList)
        //        {

        //        }

        //    }
        //    catch (Exception e)
        //    {
        //        _ret.State = ReturnStatus.Failed;
        //        LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateAsnDetail", e.Message);
        //        _ret.Result = false;
        //        _ret.ErrorList.Add(e);
        //        throw e;
        //    }
        //    return _ret;
        //}

        public static List<TED_ASN_MSTR> GetASN(string p_asn)
        {
            List<TED_ASN_MSTR> _ls = new List<TED_ASN_MSTR>();

            using (var db = EntitiesFactory.CreateExchangeCenterInstance())
            {
                _ls = db.TED_ASN_MSTR.Where(p => p.ASN == p_asn).ToList();
            }
            return _ls;
        }



        public static ResultObject<LogModel> UpdateAsn(ExchangeCenterContext db, ScpEntities scpdb, List<TS_UNI_API> _asnList, Guid p_taskID/*EnumCommandType p_command*/)
        {
            ResultObject<LogModel> _ret = new ResultObject<LogModel>();
            try
            {
                List<TED_ASN_DET> _ls = new List<TED_ASN_DET>();

                if (_asnList.FirstOrDefault() != null)
                {
                    var _api = _asnList.FirstOrDefault();
                    TED_ASN_MSTR _asn = new TED_ASN_MSTR();
                    var asn = JsonConvert.DeserializeObject<V_TB_ASN>(_api.Extend1);
                    _asn.ASN = _api.BillNum;
                    _asn.CommandType = "A";
                    _asn.CreateTime = _api.CreateTime;
                    _asn.CreateUser = _api.CreateOper;
                    _asn.KanbanBillNum = asn.AskBillNum;
                    _asn.PurchaseOrder = asn.PoBillNum;
                    _asn.Site = asn.SubSite;
                    _asn.Domain = asn.Site;
                    _asn.Supplier = asn.VendId;
                    _asn.TaskID = p_taskID;
                    _asn.DataID = Guid.NewGuid();
                    _asn.ShippingDate = asn.ShipTime == null ? DateTime.Now : asn.ShipTime.Value;
                    _asn.PromiseDate = asn.ReceiveTime == null ? DateTime.Now : asn.ReceiveTime.Value;
                    db.TED_ASN_MSTR.Add(_asn);
                    foreach (var detail in _asnList)
                    {
                        TED_ASN_DET _entity = new TED_ASN_DET();
                        var asnDetail = JsonConvert.DeserializeObject<V_TB_ASN_DETAIL>(_api.Extend2);
                        _entity.ASN = detail.BillNum;
                        _entity.PurchaseOrder = asn.PoBillNum;
                        _entity.Line = detail.ErpLineNum;
                        _entity.PartCode = detail.PartCode;
                        _entity.Lot = detail.Batch;
                        _entity.Qty = detail.Qty;
                        _entity.TaskID = p_taskID;
                        _entity.PackQty = detail.PackQty;
                        _entity.Location = asnDetail.DockCode;
                        _entity.Reference = "";
                        _entity.SupplierLot = detail.VendBatch;
                        _entity.WareClass = "";
                        _entity.WareId = "";
                        _entity.Price = detail.Price;
                        _entity.PoUm = detail.PoUnit;
                        _entity.LocUm = detail.LocUnit;
                        _entity.Conv = detail.UmConv;
                        _entity.PartType = "";
                        _entity.VendBatch = detail.VendBatch;
                        _entity.ProduceDate = asnDetail.ProduceDate == null ? DateTime.Now : asnDetail.ProduceDate.Value;
                        _entity.DueDate = asnDetail.EndTime == null ? DateTime.Now : asnDetail.EndTime.Value;
                        _entity.CreateUser = detail.CreateOper;
                        _entity.CreateTime = detail.CreateTime;
                        _entity.CommandType = "A";
                        _entity.Domain = asn.Site;
                        _entity.Site = asn.SubSite;
                        _entity.DataID = Guid.NewGuid();
                        db.TED_ASN_DET.Add(_entity);
                        _ls.Add(_entity);
                        detail.State = (int)BillState.Finish;
                        detail.PutTime = DateTime.Now;

                    }
                  
                    var ret = CREATE_TEA_TASK_SUB(db, true, new TEA_TASK_SUB()
                    {
                        DataCount = _asnList.Count,
                        TaskID = p_taskID,
                        TableName = "TED_ASN_MSTR",
                        Site = asn.SubSite,
                        Domain = asn.Site,
                        CreateTime = _api.CreateTime,
                        CreateUser = _api.CreateOper,
                        Creator = "SCP",
                    });
                }
                _ret.State = ReturnStatus.Succeed;
                _ret.Result = new LogModel() { LogMessage=string.Format("成功发布发货单信息{0}条", _asnList.Count), LogTime=DateTime.Now.ToString(), TaskId= p_taskID.ToString(), TableName= "TED_ASN_MSTR" };
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateAsn", e.Message);
                _ret.Result = new LogModel() { LogMessage = "发布发货单信息失败", LogTime = DateTime.Now.ToString(), TaskId = p_taskID.ToString(), TableName = "TED_ASN_MSTR" }; ;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }


        public static ResultObject<bool> UpdateReciveDetail(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var scpRcveDetailList = new List<TB_RECEIVE_DETAIL_QAD>();
                var _reciveDetailList = db.TED_RECEIPT_DET.Where(p => p.TaskID == p_entity.TaskID).ToList();
                foreach (var detail in _reciveDetailList)
                {
                    var poLineNum = Convert.ToInt32(detail.Line);
                    var scpRcvDetail =
                        scpdb.TB_RECEIVE_DETAIL_QAD.SingleOrDefault(
                            p => p.RecvBillNum == detail.ReceiveNbr &&
                                 p.PoBillNum == detail.PurchaseOrder &&
                                 p.PoLine == detail.Line &&
                                 p.PartCode == detail.PartCode &&
                                 p.Batch == detail.Lot
                                 );
                    if (scpRcvDetail == null)
                    {
                        //int istate = 0;
                        //if (isRerviceOk == false)
                        //{
                        //    istate = (int)FormState.关闭;
                        //}
                        //else
                        //{
                        //    istate = (int)FormState.开放;
                        //}
                        scpRcvDetail = new TB_RECEIVE_DETAIL_QAD();
                        scpRcvDetail.RecvBillNum = detail.ReceiveNbr;//收货单号
                        scpRcvDetail.PoBillNum = detail.PurchaseOrder;//采购单
                        scpRcvDetail.PoLine = detail.Line;//订单行
                        scpRcvDetail.PartCode = detail.PartCode.ToUpper();//零件号
                        scpRcvDetail.Batch = detail.PartCode;//批次
                        scpRcvDetail.VendBatch = detail.SupplierLot;//供应商批号
                        scpRcvDetail.PoUnit = detail.Um;//采购单位
                        scpRcvDetail.LocUnit = detail.logisticsUm;//物流单位
                        scpRcvDetail.Qty = detail.ReceiveQuantity;//收货总量                          //DockCode = ?,//收货口
                        scpRcvDetail.State = 0;// (int)FormState.关闭,
                        scpRcvDetail.Remark = detail.Remark;
                        scpRcvDetail.CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                        scpRcvDetail.CreateUser = detail.CreateUser;//创建用户
                        scpRcvDetail.IsDeleted = false;
                        scpRcvDetail.GUID = detail.TaskID;
                        scpRcvDetail.BillType = 0;
                        scpRcvDetail.SubSite = detail.Shipto;
                        scpRcvDetail.Site = detail.Domain;
                        //scpRcvDetail.Currency = detail.Currency;
                        //scpRcvDetail.Currencyamount = detail.Currencyamount;
                 
                        //scpRcvDetail.ExchangeRateType = detail.Exchangeratetype;
                        //scpRcvDetail.WorkOrderID = detail.WorkOrderID;
                        //scpRcvDetail.POSite = detail.Posite;
                        //scpRcvDetail.POCost = detail.Purchasecost;
                        //scpRcvDetail.POStandardCost = detail.Purchasestandardcost;
                        //scpRcvDetail.ReceiptType = detail.receipttype;
                        //scpRcvDetail.ReturnReasonCode = detail.Returnreason;
                        //scpRcvDetail.Requestedby = detail.Requestby;
                        //scpRcvDetail.TaxEnvironment = detail.Taxenvironment;
                        //scpRcvDetail.TaxIn = detail.taxin;
                        //scpRcvDetail.TaxUsage = detail.Taxusage;
                        //scpRcvDetail.TaxClass = detail.Taxclass;
                        //scpRcvDetail.PurchaseType = detail.Purchasetype;
                        //scpRcvDetail.UMConversion = detail.Umconversion;
                        scpRcveDetailList.Add(scpRcvDetail);
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateAsnDetail", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;

        }

        public static ResultObject<bool> UpdateRecive(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _reciveList = db.TED_RECEIPT_MSTR.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _scpPoDetailList = new List<TB_RECEIVE_QAD>();
                foreach (var detail in _reciveList)
                {
                    var scpRcv = scpdb.TB_RECEIVE_QAD.SingleOrDefault(p => p.RecvBillNum != null && p.RecvBillNum == detail.ReceiveNbr && p.Site == detail.Domain && p.SubSite == detail.Site);
                    var scpRcvList = new List<TB_RECEIVE_QAD>();
                    bool isRerviceOk = false;
                    if (!string.IsNullOrEmpty(detail.Site) && !string.IsNullOrEmpty(detail.Domain))
                    {
                        string _domain = detail.Domain;
                        string _site = detail.Site;
                        List<TA_FACTORY_CONFIG> configs = scpdb.TA_FACTORY_CONFIG.Where(p => p.FactoryId == _domain).ToList();
                        foreach (TA_FACTORY_CONFIG cfg in configs)
                        {
                            TA_CONFIG tacfg = scpdb.TA_CONFIG.Where(p => p.UID == cfg.ConfigId).SingleOrDefault();
                            if (tacfg != null && !string.IsNullOrEmpty(tacfg.ParamName) && tacfg.ParamName == "收货自动审核")
                            {
                                if ("允许" == tacfg.ParamValue)
                                {
                                    isRerviceOk = true;
                                }
                            }
                        }
                    }
                    if (scpRcv == null)
                    {
                        int istate = 0;
                        if (isRerviceOk == false)
                        {
                            istate = (int)FormState.关闭;
                        }
                        else
                        {
                            istate = (int)FormState.开放;
                        }
                        scpRcv = new TB_RECEIVE_QAD
                        {
                            RecvBillNum = detail.ReceiveNbr,//收货单号                                                
                            State = istate,
                            Remark = "",
                            CreateTime = detail.ReceiptDate == null ? DateTime.Now : (DateTime)detail.ReceiptDate,//创建日期
                            CreateUser = detail.CreateUser,//创建用户
                            IsDeleted = false,
                            GUID = detail.TaskID,
                            BillType = 0
                        };
                        scpRcvList.Add(scpRcv);
                    }
                    scpRcv.PoBillNum = detail.PurchaseOrder;//采购单
                    scpRcv.AsnBillNum = detail.ASN;//发货单号
                    scpRcv.Site = detail.Domain;//地点
                    scpRcv.VendId = detail.Supplier;//供货商名称
                    scpRcv.ShipTime = detail.ReceiptDate;//收货日期
                    scpRcv.SubSite = detail.Site;
                    scpdb.TB_RECEIVE_QAD.AddOrUpdate(scpRcvList.ToArray());
                }

                var scpRcveDetailList = new List<TB_RECEIVE_DETAIL_QAD>();
                var _reciveDetailList = db.TED_RECEIPT_DET.Where(p => p.TaskID == p_entity.TaskID).ToList();
                foreach (var detail in _reciveDetailList)
                {
                    var poLineNum = Convert.ToInt32(detail.Line);
                    var scpRcvDetail =
                        scpdb.TB_RECEIVE_DETAIL_QAD.FirstOrDefault(
                            p => p.RecvBillNum == detail.ReceiveNbr &&
                                 p.PoBillNum == detail.PurchaseOrder &&
                                 p.PoLine == detail.Line &&
                                 p.PartCode == detail.PartCode 
                           
                                 && p.SubSite==detail.Site
                                 );
                    if (scpRcvDetail == null)
                    {

                        //int istate = 0;
                        //if (isRerviceOk == false)
                        //{
                        //    istate = (int)FormState.关闭;
                        //}
                        //else
                        //{
                        //    istate = (int)FormState.开放;
                        //}
                        scpRcvDetail = new TB_RECEIVE_DETAIL_QAD();
                        scpRcvDetail.RecvBillNum = detail.ReceiveNbr;//收货单号
                        scpRcvDetail.PoBillNum = detail.PurchaseOrder;//采购单
                        scpRcvDetail.PoLine = detail.Line;//订单行
                        scpRcvDetail.PartCode = detail.PartCode;//零件号
                        scpRcvDetail.Batch = detail.Lot;//批次
                        scpRcvDetail.VendBatch = detail.SupplierLot;//供应商批号
                        scpRcvDetail.PoUnit = detail.Um;//采购单位
                        scpRcvDetail.LocUnit = detail.logisticsUm;//物流单位
                       //收货总量                          //DockCode = ?,//收货口
                        scpRcvDetail.State = 1;// (int)FormState.关闭,
                        scpRcvDetail.Remark = detail.Remark;
                        scpRcvDetail.CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                        scpRcvDetail.CreateUser = detail.CreateUser;//创建用户
                        scpRcvDetail.IsDeleted = false;
                        scpRcvDetail.GUID = detail.TaskID;
                        scpRcvDetail.BillType = 0;
                        scpRcvDetail.SubSite = detail.Shipto;
                        scpRcvDetail.Site = detail.Domain;
                        //scpRcvDetail.Currency = detail.Currency;
                        //scpRcvDetail.Currencyamount = detail.Currencyamount;
                        //scpRcvDetail.ExchangeRate = detail.Exchangerate==null?"1":detail.Exchangerate.Value.ToString();
                        //scpRcvDetail.ExchangeRate1 = detail.Exchangerate2 == null ? "1" : detail.Exchangerate2.Value.ToString();
                        //scpRcvDetail.ExchangeRateType = detail.Exchangeratetype;
                        //scpRcvDetail.WorkOrderID = detail.WorkOrderID;
                        //scpRcvDetail.POSite = detail.Posite;
                        //scpRcvDetail.POCost = detail.Purchasecost;
                        //scpRcvDetail.POStandardCost = detail.Purchasestandardcost;
                        //scpRcvDetail.ReceiptType = detail.receipttype;
                        //scpRcvDetail.ReturnReasonCode = detail.Returnreason;
                        //scpRcvDetail.Requestedby = detail.Requestby;
                        //scpRcvDetail.TaxEnvironment = detail.Taxenvironment;
                        //scpRcvDetail.TaxIn = detail.taxin;
                        //scpRcvDetail.TaxUsage = detail.Taxusage;
                        //scpRcvDetail.TaxClass = detail.Taxclass;
                        //scpRcvDetail.PurchaseType = detail.Purchasetype;
                        //scpRcvDetail.UMConversion = detail.Umconversion;
                        scpRcveDetailList.Add(scpRcvDetail);
                    }
                    scpRcvDetail.Qty = detail.ReceiveQuantity;
                }
               // var _str=JsonHelper.GetJson<List<TB_RECEIVE_DETAIL>>(scpRcveDetailList);
                scpdb.TB_RECEIVE_DETAIL_QAD.AddOrUpdate(scpRcveDetailList.ToArray());
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("QAD收货单更新{0}任务编号{1}", _reciveDetailList.Count().ToString(), p_entity.TaskID));
                _ret.Result = true;
                // var retDetail=UpdateReciveDetail(db, scpdb, p_entity);
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateRecive", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                _ret.MessageList.Add(string.Format("QAD收货单更新失败任务编号{0}", p_entity.TaskID));
                throw e;
            }
            return _ret;
        }


        public static ResultObject<bool> UpdateARRIVE(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _reciveList = db.TED_RECEIPT_MSTR.Where(p => p.TaskID == p_entity.TaskID && !string.IsNullOrEmpty(p.ReceiveNbr)).ToList();
                var _scpPoDetailList = new List<TB_RECEIVE>();
                foreach (var detail in _reciveList)
                {
                    
                    var scpRcv = scpdb.TB_RECEIVE.SingleOrDefault(p => p.RecvBillNum != null && p.RecvBillNum == detail.ReceiveNbr && p.Site == detail.Domain && p.SubSite == detail.Site);
                    var scpRcvList = new List<TB_RECEIVE>();
                    bool isRerviceOk = false;
                    if (!string.IsNullOrEmpty(detail.Site) && !string.IsNullOrEmpty(detail.Domain))
                    {
                        string _domain = detail.Domain;
                        string _site = detail.Site;
                        List<TA_FACTORY_CONFIG> configs = scpdb.TA_FACTORY_CONFIG.Where(p => p.FactoryId == _domain).ToList();
                        foreach (TA_FACTORY_CONFIG cfg in configs)
                        {
                            TA_CONFIG tacfg = scpdb.TA_CONFIG.Where(p => p.UID == cfg.ConfigId).SingleOrDefault();
                            if (tacfg != null && !string.IsNullOrEmpty(tacfg.ParamName) && tacfg.ParamName == "收货自动审核")
                            {
                                if ("允许" == tacfg.ParamValue)
                                {
                                    isRerviceOk = true;
                                }
                            }
                        }
                    }
                    if (scpRcv == null)
                    {
                        int istate = 0;
                        if (isRerviceOk == false)
                        {
                            istate = (int)FormState.关闭;
                        }
                        else
                        {
                            istate = (int)FormState.开放;
                        }
                        scpRcv = new TB_RECEIVE
                        {
                             RecvBillNum = detail.ReceiveNbr,//收货单号                                                
                            State = istate,
                            Remark = "",
                            CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime,//创建日期
                            CreateUser = detail.CreateUser,//创建用户
                            IsDeleted = false,
                            GUID = detail.TaskID,
                            BillType = 0
                        };
                        scpRcvList.Add(scpRcv);
                    }
                    scpRcv.PoBillNum = detail.PurchaseOrder;//采购单
                    scpRcv.AsnBillNum = detail.ASN;//发货单号

                    if (!string.IsNullOrEmpty(detail.ASN))
                    {
                        var _entity=scpdb.TB_ASN.Where(p => p.AsnBillNum == detail.ASN).FirstOrDefault();
                        if (_entity != null)
                        {
                            _entity.State = 4;
                        }
                    }
                    scpRcv.Site = detail.Domain;//地点
                    scpRcv.VendId = detail.Supplier;//供货商名称
                    scpRcv.ShipTime = detail.ReceiptDate;//收货日期
                    scpRcv.SubSite = detail.Site;
                    scpdb.TB_RECEIVE.AddOrUpdate(scpRcvList.ToArray());
                }

                var scpRcveDetailList = new List<TB_RECEIVE_DETAIL>();
                var _reciveDetailList = db.TED_RECEIPT_DET.Where(p => p.TaskID == p_entity.TaskID && !string.IsNullOrEmpty(p.ReceiveNbr)).ToList();
                foreach (var detail in _reciveDetailList)
                {
                    var poLineNum = Convert.ToInt32(detail.Line);
                    var scpRcvDetail =
                        scpdb.TB_RECEIVE_DETAIL.SingleOrDefault(
                            p => p.RecvBillNum == detail.ReceiveNbr &&
                                 p.PoBillNum == detail.PurchaseOrder &&
                                 p.PoLine == detail.Line &&
                                 p.PartCode == detail.PartCode &&
                                 p.Batch == detail.Lot
                                 &&p.SubSite==detail.Site
                                 );
                    if (scpRcvDetail == null)
                    {

                        //int istate = 0;
                        //if (isRerviceOk == false)
                        //{
                        //    istate = (int)FormState.关闭;
                        //}
                        //else
                        //{
                        //    istate = (int)FormState.开放;
                        //}
                        scpRcvDetail = new TB_RECEIVE_DETAIL();
                        scpRcvDetail.RecvBillNum = detail.ReceiveNbr;//收货单号
                        scpRcvDetail.PoBillNum = detail.PurchaseOrder;//采购单
                        scpRcvDetail.PoLine = detail.Line;//订单行
                        scpRcvDetail.PartCode = detail.PartCode;//零件号
                        scpRcvDetail.Batch = detail.Lot;//批次
                        scpRcvDetail.VendBatch = detail.SupplierLot;//供应商批号
                        scpRcvDetail.PoUnit = detail.Um;//采购单位
                        scpRcvDetail.LocUnit = detail.logisticsUm;//物流单位
                        scpRcvDetail.Qty = detail.ReceiveQuantity;//收货总量                          //DockCode = ?,//收货口
                        scpRcvDetail.State = 1;// (int)FormState.关闭,
                        scpRcvDetail.Remark = detail.Remark;
                        scpRcvDetail.CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                        scpRcvDetail.CreateUser = detail.CreateUser;//创建用户
                        scpRcvDetail.IsDeleted = false;
                        scpRcvDetail.GUID = detail.TaskID;
                        scpRcvDetail.BillType = 0;
                        scpRcvDetail.SubSite = detail.Site;
                        scpRcvDetail.Site = detail.Domain;
                        scpRcveDetailList.Add(scpRcvDetail);
                    }
                }
                var _str = JsonHelper.GetJson<List<TB_RECEIVE_DETAIL>>(scpRcveDetailList);
                scpdb.TB_RECEIVE_DETAIL.AddOrUpdate(scpRcveDetailList.ToArray());
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("到货单更新{0}任务编号{1}", _reciveDetailList.Count().ToString(), p_entity.TaskID));
                _ret.Result = true;
                // var retDetail=UpdateReciveDetail(db, scpdb, p_entity);
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateRecive", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                _ret.MessageList.Add(string.Format("到货单更新失败任务编号{0}", p_entity.TaskID));
                throw e;
            }
            return _ret;
        }



        public static ResultObject<bool> UpdateInvoiceDetail(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {



            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateAsnDetail", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;

        }

        public static ResultObject<LogModel> UpdateInvoice(ExchangeCenterContext db, ScpEntities scpdb, List<TS_UNI_API> p_invoiceList, Guid p_taskId)
        {
            ResultObject<LogModel> _ret = new ResultObject<LogModel>();
            List<TED_INVOICE_MSTR> _mstList = new List<TED_INVOICE_MSTR>();
            List<TED_INVOICE_DET> _detList = new List<TED_INVOICE_DET>();
          //List<TED_INVOICE_ADD> _addList = new List<TED_INVOICE_ADD>();
            try
            {
                if (p_invoiceList.FirstOrDefault() != null)
                {
                    var _api = p_invoiceList.FirstOrDefault();
                    #region 发票主表
                    TED_INVOICE_MSTR _invMast = new TED_INVOICE_MSTR();
                    var _vinvoice = JsonConvert.DeserializeObject<V_TB_INVOICE>(_api.Extend1);
                    _invMast.GUID = Guid.NewGuid();
                    _invMast.Status = "0";
                    _invMast.Invoice_ID = 1000;
                    _invMast.InvoiceReference = _vinvoice.InvoiceNum;
    
                    _invMast.CreateInvoice = true;
                    _invMast.Supplier = _vinvoice.VendId.Trim();
                    _invMast.SupplierName = _vinvoice.VendName.Trim(); 
                    _invMast.Rowid = Guid.NewGuid().ToString();
                    _invMast.InvoiceIsTaxable = true;
                    _invMast.InvoiceHoldAmountTC = _vinvoice.Amount.Value;
                    _invMast.InvoiceVoucher = 0;
                    _invMast.InvoiceRegistrationNbr = 1000;
                    _invMast.PostingDate = DateTime.Now;
                    _invMast.Currency = "CNY";
        
                    _invMast.InvoiceDate = _vinvoice.UpdateTime == null ? DateTime.Now : _vinvoice.UpdateTime.Value;
                    _invMast.GUID = Guid.NewGuid();
                    _invMast.Invoice_ID = 1000;
                    _invMast.CreateInvoice = true;
                    _invMast.PaymentCondCode = "90";
                    _invMast.InvoiceDueDate = _invMast.InvoiceDate.AddDays(int.Parse(_invMast.PaymentCondCode));
                    _invMast.InvoiceIsStatusFinal = true;
                    _invMast.InvoicePostingYear = DateTime.Now.Year;
                    _invMast.APMatchingIsStatusFinal = true;
                    _invMast.InvoiceRemark = _vinvoice.InvcBillNum;//发票编号
                    _invMast.CreateWithAmountIsTax = true;
                    _invMast.InvoiceAmountTC = _vinvoice.TaxAmount == null ? 0 : _vinvoice.TaxAmount.Value;
                    _invMast.InvoiceIsTaxable = true;
                    _invMast.CreateUser = _vinvoice.CreateUser;
                    _invMast.CreateTime = DateTime.Now;
                    _invMast.Remark = _vinvoice.Remark;
                    _invMast.TaskID = p_taskId;
                    _invMast.CommandType = "A";
                    _invMast.DataID = Guid.NewGuid();
                    _invMast.Domain = _vinvoice.Site;
                    _invMast.Site = _vinvoice.SubSite;
                 //   _invMast.CInvoiceCostCenterCode = _vinvoice.CInvoiceCostCenterCode;
                    _invMast.CInvoiceReference = _vinvoice.InvoiceNum;
                   // _invMast.CInvoiceDescription = _vinvoice.CInvoiceDescription;
                 //   _invMast.CInvoiceType = _vinvoice.CInvoiceType;
                  //  _invMast.CInvoiceDivisionCode = _vinvoice.CInvoiceDivisionCode;

                    _mstList.Add(_invMast);
                    #endregion
                    #region 发票差异
                    if ((_vinvoice.ContractPrice != null && _vinvoice.ContractPrice.Value != 0) )
                    {
                        _invMast.InvoiceHoldAmountTC = _vinvoice.Amount.Value + _vinvoice.ContractPrice.Value;
                       
                        //_add.VatDebitCC = _vinvoice.ContractPrice.Value;//折扣
                        //_add.VatDebitLC = _vinvoice.BlancePrice.Value;//税额调整
                        //_add.VatDebitTC = _vinvoice.ContractPrice.Value;
                       // _addList.Add(_add);
                    }
                    if ((_vinvoice.BlancePrice != null && _vinvoice.BlancePrice.Value != 0))
                    {
                        _invMast.InvoiceAmountTC = (_vinvoice.TaxAmount == null ? 0 : _vinvoice.TaxAmount.Value) + _vinvoice.BlancePrice.Value;
                    }
                    #endregion
                    #region 发票明细
                    foreach (var detail in p_invoiceList)
                    {
                        TED_INVOICE_DET _entity = new TED_INVOICE_DET();
                        var _invDetail = JsonConvert.DeserializeObject<V_TB_INVOICE_DETAIL>(detail.Extend2);
                        _entity.CommandType = "A";
                        _entity.GUID = _invDetail.GUID;
                        _entity.Status =_invMast.Status;
                        _entity.PurchaseOrder = _invDetail.PoBillNum;
                        _entity.Line = _invDetail.PoLineNum;
                        _entity.ReceiveNbr = _invDetail.RecvBillNum;
                        _entity.MatchQuantity = _invDetail.Qty;
                        _entity.MatchPrice = _invDetail.Price + ((_invDetail.BlancePrice==null)?0: _invDetail.BlancePrice.Value);
                        _entity.IsPvodFinished = true;
                        _entity.UsageDate = DateTime.Now;
                        _entity.IsRecalculateTaxes = true;
                        _entity.ParentRowid = _invMast.Rowid;
                        _entity.CreateUser = _invDetail.CreateUser;
                        _entity.CreateTime = _invDetail.CreateTime;
                        _entity.Remark = _invDetail.Remark;
                        _entity.TaskID = p_taskId;
                        _entity.CommandType = "A";
                        _entity.DataID = Guid.NewGuid();
                        _entity.Domain = _invDetail.Site.Trim(); 
                        _entity.Site = _invDetail.SubSite.Trim(); 
                        _entity.PartCode = _invDetail.PartCode;
                        _entity.Tax = _invDetail.Tax.ToString();
                        _detList.Add(_entity);
                        detail.State = (int)BillState.Finish;
                        detail.PutTime = DateTime.Now;

                    }
                    #endregion
                    var ret = CREATE_TEA_TASK_SUB(db, true, new TEA_TASK_SUB()
                    {
                        DataCount = p_invoiceList.Count,
                        TaskID = p_taskId,
                        TableName = "TED_INVOICE_MSTR",
                        Site = _vinvoice.SubSite.Trim(),
                        Domain = _vinvoice.Site,
                        CreateTime = _api.CreateTime,
                        CreateUser = _api.CreateOper,
                        Creator = "SCP",
                    });
                }
                db.TED_INVOICE_MSTR.AddOrUpdate(_mstList.ToArray());
                db.TED_INVOICE_DET.AddOrUpdate(_detList.ToArray());
            

                var str=JsonHelper.GetJson(_mstList.ToArray());
                var str1=JsonHelper.GetJson(_detList.ToArray());

                _ret.State = ReturnStatus.Succeed;
                _ret.Result = new LogModel() { LogMessage = string.Format("成功发布发票信息{0}条",_detList.Count), LogTime = DateTime.Now.ToString(), TaskId = p_taskId.ToString(), TableName = "TED_INVOICE_MSTR" };

            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateInvoice", e.Message);
                _ret.Result = new LogModel() { LogMessage = "发布发票信息失败", LogTime = DateTime.Now.ToString(), TaskId = p_taskId.ToString(), TableName = "TED_INVOICE_MSTR" }; ;
                _ret.ErrorList.Add(e);
              
                throw e;
            }
            return _ret;

        }


        public static ResultObject<bool> UpdateReturn(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
             ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _reciveList = db.TED_RETURN_MSTR.Where(p => p.TaskID == p_entity.TaskID && !string.IsNullOrEmpty(p.ReturnNbr)).ToList();
                var _scpPoDetailList = new List<TB_RECEIVE>();
                foreach (var detail in _reciveList)
                {
                    var scpRcv = scpdb.TB_RECEIVE.SingleOrDefault(p => p.RecvBillNum != null && p.RecvBillNum == detail.ReturnNbr && p.Site == detail.Domain && p.SubSite == detail.Site);
                    var scpRcvList = new List<TB_RECEIVE>();
                    bool isRerviceOk = false;
                    if (!string.IsNullOrEmpty(detail.Site) && !string.IsNullOrEmpty(detail.Domain))
                    {
                        string _domain = detail.Domain;
                        string _site = detail.Site;
                        List<TA_FACTORY_CONFIG> configs = scpdb.TA_FACTORY_CONFIG.Where(p => p.FactoryId == _domain).ToList();
                        foreach (TA_FACTORY_CONFIG cfg in configs)
                        {
                            TA_CONFIG tacfg = scpdb.TA_CONFIG.Where(p => p.UID == cfg.ConfigId).SingleOrDefault();
                            if (tacfg != null && !string.IsNullOrEmpty(tacfg.ParamName) && tacfg.ParamName == "收货自动审核")
                            {
                                if ("允许" == tacfg.ParamValue)
                                {
                                    isRerviceOk = true;
                                }
                            }
                        }
                    }
                    if (scpRcv == null)
                    {
                        int istate = 0;
                        if (isRerviceOk == false)
                        {
                            istate = (int)FormState.关闭;
                        }
                        else
                        {
                            istate = (int)FormState.开放;
                        }
                        scpRcv = new TB_RECEIVE
                        {
                            RecvBillNum = detail.ReturnNbr,//收货单号                                                
                            State = istate,
                            Remark = "",
                            CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime,//创建日期
                            CreateUser = detail.CreateUser,//创建用户
                            IsDeleted = false,
                            GUID = detail.TaskID,
                            BillType = 1
                        };
                        scpRcvList.Add(scpRcv);
                    }
                    scpRcv.PoBillNum = detail.PurchaseOrder;//采购单
                    scpRcv.AsnBillNum = detail.ASN;//发货单号

                    if (!string.IsNullOrEmpty(detail.ASN))
                    {
                        var _entity=scpdb.TB_ASN.Where(p => p.AsnBillNum == detail.ASN).FirstOrDefault();
                        if (_entity != null)
                        {
                            _entity.State = 4;
                        }
                    }
                    scpRcv.Site = detail.Domain;//地点
                    scpRcv.VendId = detail.Supplier;//供货商名称
                    scpRcv.ShipTime = detail.ReturnDate;//收货日期
                    scpRcv.SubSite = detail.Site;
                    scpdb.TB_RECEIVE.AddOrUpdate(scpRcvList.ToArray());
                }

                var scpRcveDetailList = new List<TB_RECEIVE_DETAIL>();
                var _reciveDetailList = db.TED_RETURN_DET.Where(p => p.TaskID == p_entity.TaskID ).ToList();
                var _recive = db.TED_RETURN_MSTR.Where(p => p.TaskID == p_entity.TaskID && !string.IsNullOrEmpty(p.ReturnNbr)).FirstOrDefault();
                if (_recive != null)
                {
                    foreach (var detail in _reciveDetailList)
                    {
                        detail.ReturnNbr = _recive.ReturnNbr;
                        var poLineNum = Convert.ToInt32(detail.Line);
                        var scpRcvDetail =
                            scpdb.TB_RECEIVE_DETAIL.SingleOrDefault(
                                p => p.RecvBillNum == detail.ReturnNbr &&
                                     p.PoBillNum == detail.PurchaseOrder &&
                                     p.PoLine == detail.Line &&
                                     p.PartCode == detail.PartCode &&
                                     p.Batch == detail.Lot
                                     && p.SubSite == detail.Site
                                     );
                        if (scpRcvDetail == null)
                        {

                            //int istate = 0;
                            //if (isRerviceOk == false)
                            //{
                            //    istate = (int)FormState.关闭;
                            //}
                            //else
                            //{
                            //    istate = (int)FormState.开放;
                            //}
                            scpRcvDetail = new TB_RECEIVE_DETAIL();
                            scpRcvDetail.RecvBillNum = detail.ReturnNbr;//收货单号
                            scpRcvDetail.PoBillNum = detail.PurchaseOrder;//采购单
                            scpRcvDetail.PoLine = detail.Line;//订单行
                            scpRcvDetail.PartCode = detail.PartCode;//零件号
                            scpRcvDetail.Batch = detail.Lot;//批次
                            scpRcvDetail.VendBatch = detail.SupplierLot;//供应商批号
                            scpRcvDetail.PoUnit = detail.Um;//采购单位
                            scpRcvDetail.LocUnit = detail.logisticsUm;//物流单位
                            scpRcvDetail.Qty = detail.ReturnQuantity;//收货总量                          //DockCode = ?,//收货口
                            scpRcvDetail.State = 1;// (int)FormState.关闭,
                            scpRcvDetail.Remark = detail.Remark;
                            scpRcvDetail.CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                            scpRcvDetail.CreateUser = detail.CreateUser;//创建用户
                            scpRcvDetail.IsDeleted = false;
                            scpRcvDetail.GUID = detail.TaskID;
                            scpRcvDetail.BillType = 1;
                            scpRcvDetail.SubSite = detail.Site;
                            scpRcvDetail.Site = detail.Domain;

                            scpRcveDetailList.Add(scpRcvDetail);
                        }
                    }
                    var _str = JsonHelper.GetJson<List<TB_RECEIVE_DETAIL>>(scpRcveDetailList);
                    scpdb.TB_RECEIVE_DETAIL.AddOrUpdate(scpRcveDetailList.ToArray());
                }
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("退货单更新{0}任务编号{1}", _reciveDetailList.Count().ToString(), p_entity.TaskID));
                _ret.Result = true;
                // var retDetail=UpdateReciveDetail(db, scpdb, p_entity);
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateRecive", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                _ret.MessageList.Add(string.Format("退货单更新失败任务编号{0}", p_entity.TaskID));
                throw e;
            }
            return _ret;

        }


        public static ResultObject<bool> UpdatePoDetail(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _poDetailList = db.TED_POD_DET.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _scpPoDetailList = new List<TB_PO_DETAIL>();
                foreach (var detail in _poDetailList)
                {
                    var lineNum = Convert.ToInt32(detail.Line);
                    var PoDetail =
                       scpdb.TB_PO_DETAIL.SingleOrDefault(
                           p => p.PoBillNum == detail.PurchaseOrder && p.PoLine == lineNum && p.Remark == detail.Domain);
                    if (PoDetail == null)
                    {
                        PoDetail = new TB_PO_DETAIL
                        {
                            PoBillNum = detail.PurchaseOrder,//订单号
                            PoLine = lineNum,//订单行
                            IsDeleted = false,
                            GUID = detail.TaskID
                        };
                        _scpPoDetailList.Add(PoDetail);
                    }
                    PoDetail.PartCode = detail.PartCode;//零件号-物料号
                    PoDetail.PlanQty = detail.Qty;//订货数量-采购量
                    PoDetail.PoUnit = detail.PoUm;//采购单位
                    PoDetail.LocUnit = detail.LocUm;//存储单位
                    PoDetail.Price = ScpCache.Config.项目名称 == ProjectName.重庆北汽模塑.ToString()? 0 : detail.Price;
                    PoDetail.Currency = detail.Currency;//币种
                    PoDetail.PackQty = detail.PackQty;//标包数量
                    PoDetail.UnConv = detail.Conv;//转换率                    
                    PoDetail.State = Convert.ToInt32(detail.Status);//状态
                    PoDetail.Remark = detail.Domain;//备注
                    PoDetail.CreateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                    PoDetail.CreateUser = detail.CreateUser;//创建用户
                    PoDetail.UpdateTime = detail.CreateTime == null ? DateTime.Now : (DateTime)detail.CreateTime;//创建日期
                    PoDetail.UpdateUser = detail.CreateUser;//创建用户                    
                }
                scpdb.TB_PO_DETAIL.AddOrUpdate(_scpPoDetailList.ToArray());
                //Console.WriteLine($"更新 采购订单 数据:{qadPoDetailList.Count}");
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "Save_TEA_TASK_SUB", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> UpdatePo(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _poList = db.TED_PO_MSTR.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _scpPolist = new List<TB_PO>();
                foreach (var po in _poList)
                {
                    var _po = scpdb.TB_PO.SingleOrDefault(p => p.ErpBillNum == po.PurchaseOrder && p.Site == po.Domain);
                    if (_po == null)
                    {
                        int temp;
                        _po = new TB_PO
                        {
                            PoBillNum = po.PurchaseOrder,//订单号
                            ErpBillNum = po.PurchaseOrder,//ERP订单号
                            VendId = po.Supplier,//供应商编号
                            ModType = Int32.TryParse(po.ModeType, out temp) ? temp : (int?)null, //单据类型(1:日程单,2:离散订单)
                            Contacter = po.Contact,//联系人
                            Site = po.Domain,//地点
                            State = (int)FormState.开放,//状态
                            Remark = po.Remark,//说明
                            CreateTime = po.CreateTime == null ? DateTime.Now : (DateTime)po.CreateTime,//创建日期
                            CreateUser = po.CreateUser,//创建用户
                            IsDeleted = false,
                            GUID =po.TaskID,
                            BeginTime = po.OrderDate == null ? DateTime.Now : po.OrderDate,//创建日期
                            EndTime = po.DueDate//收货结束时间
                        };
                        int _count = _scpPolist.Count(p => p.ErpBillNum == po.PurchaseOrder && p.Site == po.Domain );
                        if (_count == 0)
                        {
                            _scpPolist.Add(_po);
                        }
                    }
                    _po.Contacter = po.Contact;
                    _po.Buyer = _po.Buyer;
                    _po.BuyerPhone = _po.BuyerPhone;
                    _po.UpdateTime = _po.UpdateTime;//更新日期
                    _po.UpdateUser = _po.UpdateUser;//更新用户
                }
                scpdb.TB_PO.AddOrUpdate(_scpPolist.ToArray());
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "Save_TEA_TASK_SUB", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        /// <summary>
        /// 更新供应商
        /// </summary>
        /// <param name="db"></param>
        /// <param name="scpdb"></param>
        /// <param name="p_entity"></param>
        /// <returns></returns>
        public static ResultObject<bool> UpdateSupplier(ExchangeCenterContext db, ScpEntities scpdb, AppBoxContext authdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _supplierlist = db.TES_SUPPLIER.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _venderlist = new List<TA_VENDER>();
                foreach (var supplier in _supplierlist)
                {
                    var _supplier = scpdb.TA_VENDER.SingleOrDefault(p => p.VendId == supplier.SupplierCode  );
                    if (_supplier == null)
                    {
                        _supplier = new TA_VENDER
                        {
                            VendId = supplier.SupplierCode.ToUpper(),
                            VendAbbCode = "0",
                            State = 1,
                        };
                    }
                    _supplier.VendName = string.IsNullOrEmpty(supplier.SupplierName) ? supplier.SupplierName : supplier.SupplierName;//供应商名称
                    //_supplier.VendType = supplier.SupplierType.ToUpper().ToString();//供应商类型
                    //_supplier.Country = supplier.Country;//国家
                    //_supplier.City = supplier.City;//城市
                    //_supplier.Currency = supplier.Currency.ToUpper();//币总
                    //_supplier.Address = supplier.Address1 + supplier.Address2 + supplier.Address3;//地址
                    //_supplier.ZipCode = supplier.ZipCode.ToString();//邮编
                    //_supplier.Contacter = supplier.ContactName;//联系人
                    //_supplier.Phone = supplier.Telephone.ToString();//电话
                    //_supplier.Fax = supplier.Fax.ToString();//传真
                    //_supplier.SubSite = string.IsNullOrEmpty(supplier.Site)?"BJ01" : supplier.Site;//域
                    _supplier.Site = string.IsNullOrEmpty(supplier.Domain)?"BJBMPT": supplier.Domain;//域
                    //_supplier.Tax = Convert.ToDecimal(supplier.TaxInCity);//税率
                  
                    _supplier.Remark = supplier.TaskID.ToString();//任务ID

                    var vendname = string.Format("{0}@{1}",_supplier.VendId.ToUpper(), _supplier.Site.ToUpper());
                    var _first = authdb.Users.Where(p => p.Name == vendname).FirstOrDefault();
                    var _vend = authdb.Roles.Where(p => p.Name == "供应商").FirstOrDefault();
                    var _factory = authdb.TA_FACTORY.Where(p => p.ErpDomain == _supplier.Site.ToUpper()).FirstOrDefault();
                    if (_first == null && _vend != null && _factory != null)
                    {
                        User _entity = new User();
                        _entity.Name = vendname;
                        _entity.Remark = _supplier.Site.ToUpper();
                        _entity.Password = PasswordUtil.CreateDbPassword("666666");
                        _entity.ChineseName = _supplier.VendName;
                        _entity.Email = _supplier + "@163.com";
                        _entity.Gender = "男";
                        _entity.Enabled = true;

                        _entity.Roles = new List<Role>();

                        Role t = authdb.Set<Role>().Local.Where(x => x.ID == _vend.ID).FirstOrDefault();
                        if (t == null)
                        {
                            t = new Role { ID = _vend.ID };
                            authdb.Set<Role>().Attach(t);
                        }
                        _entity.Roles.Add(t);

                        _entity.TA_FACTORY = new List<TA_FACTORY>();

                        TA_FACTORY f = authdb.Set<TA_FACTORY>().Local.Where(x => x.ID == _factory.ID).FirstOrDefault();
                        if (f == null)
                        {
                            f = new TA_FACTORY { ID = _factory.ID };
                            authdb.Set<TA_FACTORY>().Attach(f);
                        }
                        _entity.TA_FACTORY.Add(f);

                        authdb.Users.Add(_entity);

                    }


                    _venderlist.Add(_supplier);
                }
                scpdb.TA_VENDER.AddOrUpdate(_venderlist.ToArray());
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("更新表{0}任务ID{1}成功!", "TES_SUPPLIER", p_entity.TaskID));
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateSupplier", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        /// <summary>
        /// 更新供应商零件
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="db"></param>
        /// <param name="scpdb"></param>
        /// <param name="p_entity"></param>
        /// <returns></returns>
        public static ResultObject<bool> UpdateSupplierPart(DataCenterContext dc, ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _supplierpartlist = db.TES_SUPPLIER_PART.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _venderpartlist = new List<TA_VEND_PART>();
                decimal _packqty = 1;
                foreach (var supplierpart in _supplierpartlist)
                {
                    var _supplierpart = scpdb.TA_VEND_PART.SingleOrDefault(p => p.VendId == supplierpart.Supplier && p.PartCode == supplierpart.PartCode && p.VendPartCode == supplierpart.SupplierPart && p.Site == supplierpart.Domain );
                    if (_supplierpart == null)
                    {
                        var _pack = dc.TS_PACK.SingleOrDefault(p => p.PartCode == supplierpart.PartCode && p.Site == supplierpart.Domain && p.Site == supplierpart.Site);
                        if (_pack != null)
                        {
                        }
                        _supplierpart = new TA_VEND_PART
                        {
                            VendId = supplierpart.Supplier.ToUpper(),//供应商编号
                            PartCode = supplierpart.PartCode.ToUpper(),//对应物料号
                            VendPartCode = supplierpart.SupplierPart.ToUpper(),//供应商物料号
                            VendPackQty = _packqty,//供应商物料号
                            State = 1,//状态(0:失效 1:有效)
                            Remark = "",
                            CreateTime = supplierpart.CreateTime == null ? DateTime.Now : (DateTime)supplierpart.CreateTime,//创建日期
                            CreateUser = supplierpart.CreateUser,//创建用户
                            TransportationTime = 1,
                            IsDeleted = false,
                            GUID = new Guid()
                        };
                    }
                    _supplierpart.Site = string.IsNullOrEmpty(_supplierpart.Site) ? supplierpart.Domain : _supplierpart.Site;
                    //_supplierpart.SubSite = string.IsNullOrEmpty(_supplierpart.SubSite) ? supplierpart.Site : _supplierpart.SubSite;
                    _supplierpart.VendPartCode = supplierpart.SupplierPart?.ToUpper() ?? supplierpart.PartCode.ToUpper();
                    _supplierpart.VendPackQty = _packqty;
                    _supplierpart.TransportationTime = 1;
                    _supplierpart.UpdateTime = DateTime.Now;//更新日期
                    _supplierpart.UpdateUser = supplierpart.CreateUser;//更新用户
                    _supplierpart.Remark = supplierpart.TaskID.ToString();//任务ID
                    _venderpartlist.Add(_supplierpart);
                }
                scpdb.TA_VEND_PART.AddOrUpdate(_venderpartlist.ToArray());
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("更新表{0}任务ID{1}成功!", "TES_SUPPLIER_PART", p_entity.TaskID));
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateSupplierPart", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        /// <summary>
        /// 更新零件
        /// </summary>
        /// <param name="db"></param>
        /// <param name="scpdb"></param>
        /// <param name="p_entity"></param>
        /// <returns></returns>
        public static ResultObject<bool> UpdatePart(ExchangeCenterContext db, ScpEntities scpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _partmstrlist = db.TES_PART_MSTR.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _partlist = new List<TA_PART>();
                foreach (var part in _partmstrlist)
                {
                    var _part = scpdb.TA_PART.SingleOrDefault(p => p.PartCode == part.PartCode && p.Site == part.Domain );
                    if (_part == null)
                    {
                        _part = new TA_PART
                        {
                            PartCode = part.PartCode.ToUpper(),
                            ErpPartCode = part.PartCode.ToUpper(),
                        };
                    }
                    _part.PartDesc1 = part.Desc1;
                    _part.PartDesc2 = string.IsNullOrEmpty(part.Desc2)?string.Empty: part.Desc2;
                    if (!string.IsNullOrEmpty(part.Group))
                    {
                        _part.ProjectId = part.Group;
                    }
                    else
                    {
                        _part.ProjectId ="public";

                    }
                    _part.Unit = !string.IsNullOrEmpty(part.Um) ? part.Um.ToUpper() : "EA";

                    _part.State = part.Status;
                    if (part.InspectType != null)
                    {
                        _part.Ischeck = (part.InspectType == 0) ? true : false;
                    }

                    if (!string.IsNullOrEmpty(part.PartType))
                    {
                        if (part.PartType.Substring(0, 2) == "12")
                        {
                            _part.PartGroup = "AST";
                        }
                        else
                        {
                            _part.PartGroup = "其他";
                        }
                    }
                    _part.Qlevel = string.IsNullOrEmpty(part.Qgrade)?string.Empty: part.Qgrade;
                    _part.State = part.Status;
                    _part.Site = part.Domain;
                   // _part.SubSite = part.Site;
                    _part.Remark = part.TaskID.ToString();
                    _partlist.Add(_part);
                }

              var str=  JsonHelper.GetJson<List<TA_PART>>(_partlist);

                scpdb.TA_PART.AddOrUpdate(_partlist.ToArray());
                _ret.State = ReturnStatus.Succeed;
                _ret.MessageList.Add(string.Format("更新表{0}任务ID{1}成功!", "TES_PART_MSTR", p_entity.TaskID));
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdatePart", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> UpdateFactory(ExchangeCenterContext db, ScpEntities scpdb, AppBoxContext appscpdb, TEA_TASK_SUB p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                var _factorylist = db.TES_SITE.Where(p => p.TaskID == p_entity.TaskID).ToList();
                var _appboxfactorylist = new List<TA_FACTORY>();
                var _scpfactorylist = new List<TB_FACTORY>();
                foreach(var factory in _factorylist)
                {
                    var item1 = appscpdb.TA_FACTORY.SingleOrDefault(p => p.ErpDomain == factory.Domain && p.ErpSite == factory.Site);
                    if (item1 == null)
                    {
                        item1 = new TA_FACTORY
                        {
                            ErpDomain = factory.Domain,
                            ErpSite = factory.Site,
                            GUID = Guid.NewGuid(),
                            State = 1,
                            CreateTime = DateTime.Now,
                            CreateUser= factory.CreateUser
                        };
                    }
                    item1.FactoryId = factory.Domain;
                    item1.ZipCode = factory.Domain;
                    item1.FactoryName = factory.Desc;
                    item1.Address = "";
                    item1.Remark = factory.Remark;
                    item1.Tel = "";
                    item1.Fax = "";
                    item1.UpdateTime = DateTime.Now;
                    item1.UpdateUser = factory.CreateUser;
                    _appboxfactorylist.Add(item1);
                    var item2 = scpdb.TB_FACTORY.SingleOrDefault(p => p.ErpDomain == factory.Domain && p.ErpSite == factory.Site);
                    if (item2 == null)
                    {
                        item2 = new TB_FACTORY
                        {
                            ErpDomain = factory.Domain,
                            ErpSite = factory.Site,
                            GUID = Guid.NewGuid(),
                            State = 1,
                            CreateTime = DateTime.Now,
                            CreateUser = factory.CreateUser
                        };
                    }
                    item2.FactoryId = factory.Domain;
                    item2.ZipCode = factory.Domain;
                    item2.FactoryName = factory.Desc;
                    item2.Address = "";
                    item2.Remark = factory.Remark;
                    item2.Tel = "";
                    item2.Fax = "";
                    item2.UpdateTime = DateTime.Now;
                    item2.UpdateUser = factory.CreateUser;
                    _scpfactorylist.Add(item2);
                }
                appscpdb.TA_FACTORY.AddOrUpdate(_appboxfactorylist.ToArray());
                scpdb.TB_FACTORY.AddOrUpdate(_scpfactorylist.ToArray());
                if (appscpdb.SaveChanges() != -1)
                {
                    _ret.State = ReturnStatus.Succeed;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "UpdateFactory", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

     


        //public static ResultObject<bool> UpdateTES_PURCHASE_PRICE(List<long> p_list, string domain, string site, string name, bool flag,int ConfirmState)
        //{
          
        //    ResultObject<bool> _ret = new ResultObject<bool>();
        //    if (ConfirmState!=(int)PriceState.FConfirm)
        //    {
        //        _ret.State = ReturnStatus.Succeed;
        //        _ret.Result = true;
        //        return _ret;
        //    }
        //    try
        //    {
        //        ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
        //        ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
        //        List<TES_PURCHASE_PRICE> _teslist = new List<TES_PURCHASE_PRICE>();
        //        var _ls = scpdb.V_TB_PRICE.Where(p => p_list.Contains(p.UID)).ToList();
               
        //        foreach (var _price in _ls)
        //        {
        //            Guid _taskguid = Guid.NewGuid();
        //            TES_PURCHASE_PRICE _item = new TES_PURCHASE_PRICE();
        //            var apiitem = db.TES_PURCHASE_PRICE.Where(p => p.SupplierCode == _price.VendId && p.PartCode == _price.PartCode && p.Domain == _price.Site && p.Site == _price.SubSite && p.Start == _price.StartTime && p.ExpireDate == _price.EndTime).ToList();

        //            if (apiitem.Count <= 0)
        //            {
        //                _item.CommandType = "A";//命令类型
        //                _item.DataID = Guid.NewGuid();//DataID
        //            }
        //            else
        //            {
        //                var uid = apiitem.Select(p => p.UID).Max();
        //                var old_item = db.TES_PURCHASE_PRICE.FirstOrDefault(t => t.UID == uid);
        //                _item.CommandType = "U";//命令类型
        //                _item.DataID = old_item.GUID;
        //            }
        //            _item.PartCode = _price.PartCode;//零件编号
        //            _item.Domain = _price.Site;//域
        //            _item.Site = _price.SubSite;//地点
        //            _item.Start = Convert.ToDateTime(_price.StartTime);//开始时间
        //            _item.ExpireDate = Convert.ToDateTime(_price.EndTime);//结束时间
        //            _item.CreateUser = "scp";//_price.CreateUser;//创建人
        //            _item.CreateTime = DateTime.Now;//_price.CreateTime;//创建时间
        //            _item.GUID = Guid.NewGuid();//GUID
        //            _item.PriceList = (_price.VendId + _price.SubSite.Substring(1, 1) + _price.SubSite.Substring(3, 1)).Trim(); //价目表代码
        //            _item.Desc = "";//说明
        //            _item.ProductLine = "";//产品类
        //            _item.Currency = _price.Curr;//货币      



        //            var _first = scpdb.TA_PART.Where(itm => itm.PartCode == _price.PartCode).FirstOrDefault();
        //            if (_first != null)
        //            {
        //                _item.Um = _first.Unit;
        //            }
        //            else
        //            {

        //                _item.Um = _price.Unit;//单位
        //            }

        //            _item.AmountType = "P";//金额类型
        //            _item.Amount = _price.Amt+_price.SharingPrice;//金额(零件单价—+分摊单价)
        //            _item.TaskID = _taskguid;//任务编号
        //            _item.Remark = _price.Remarks;//备注
        //            _item.SupplierCode = _price.VendId;//供应商
        //            _item.VendAmount = _price.Amt;//供应商金额
        //            _teslist.Add(_item);
        //           var ret = CREATE_TEA_TASK_SUB(db, false,
        //        new TEA_TASK_SUB()
        //        {
        //            DataCount = _teslist.Count,
        //            TaskID = _taskguid,
        //            TableName = "TES_PURCHASE_PRICE",
        //            Site = _price.SubSite,
        //            Domain = _price.Site,
        //            CreateTime = DateTime.Now,
        //            CreateUser = name,
        //            Creator = name,
        //        });
        //        }
        //        db.TES_PURCHASE_PRICE.AddOrUpdate(_teslist.ToArray());

        //        if (db.SaveChanges() != -1)
        //        {
        //            _ret.State = ReturnStatus.Succeed;
        //            _ret.Result = true;
        //        }
        //        else
        //        {
        //            _ret.State = ReturnStatus.Failed;
        //            _ret.Result = false;
        //            _ret.Message = "数据更新失败!";
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _ret.State = ReturnStatus.Failed;
        //        _ret.Result = false;
        //        _ret.Message =e.InnerException.Message;
        //    }            
        //    return _ret;
        //}
        //public static ResultObject<bool> WritePo(List<SCP_PO_EXPORT_IMPORT_MODEL> p_order_list, string site, string p_creator, DateTime p_time, BillModType p_modtype, string subsite, string p_chineseName, string p_buyerPhone)
        //{
        //    ResultObject<bool> _ret = new ResultObject<bool>();
        //    using (var scope =
        //    new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
        //    {
        //        IsolationLevel = System.Transactions.IsolationLevel.Serializable,
        //        Timeout = new TimeSpan(0, 20, 0)
        //    }))
        //    {
        //        try
        //        {
        //            ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
        //            ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
        //            var OrderList = p_order_list.GroupBy(p => p.订单编号).ToList();
        //            string   _polist = "";
        //            int _num = 1;
        //            OrderList.ForEach((p) =>
        //            {
        //                Guid taskid = Guid.NewGuid();
        //                var list = p.ToList();
        //                if (list.Count > 0)
        //                {
        //                    #region 日程单
        //                    if (p_modtype == BillModType.Contract)
        //                    {
        //                        var _entity = list.FirstOrDefault();
        //                        var _po = scpdb.TB_PO.SingleOrDefault(t => t.PoBillNum == _entity.订单编号/* && t.State == state*/ && t.Site == site && t.SubSite == subsite && t.VendId == _entity.供应商编号.ToUpper());                                
        //                        TED_PO_MSTR _po_mstr = new TED_PO_MSTR();
        //                        _po_mstr.GUID = Guid.NewGuid();
        //                        _po_mstr.PurchaseOrder = _entity.订单编号.Trim().ToUpper();
        //                        _po_mstr.Supplier = _entity.供应商编号.Trim().ToUpper();
        //                        _po_mstr.Contact = p_chineseName;// _entity.联系人;
        //                        _po_mstr.ShipTo = subsite.Trim().ToUpper();//发往
        //                        _po_mstr.OrderDate = string.IsNullOrEmpty(_entity.订单创建时间) ? DateTime.Now : DateTime.Parse(_entity.订单创建时间);
        //                        _po_mstr.DueDate = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now : DateTime.Parse(_entity.要求到货日期);
        //                        _po_mstr.StartDate = string.IsNullOrEmpty(_entity.订单开始时间) ? DateTime.Now : DateTime.Parse(_entity.订单开始时间);//订单日期
        //                        _po_mstr.EndDate = string.IsNullOrEmpty(_entity.订单截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.订单截至日期);
        //                        _po_mstr.MadeIn = "";
        //                        _po_mstr.Confirm = true;
        //                        _po_mstr.Buyer = p_chineseName;//_entity.采购员;
        //                        _po_mstr.BuyerPhone = p_buyerPhone;// _entity.采购员电话;
        //                        _po_mstr.Status = (int)PoState.Open;
        //                        _po_mstr.ScheduledOrder = true;
        //                        _po_mstr.CreateUser = p_creator;
        //                        _po_mstr.CreateTime = p_time;
        //                        _po_mstr.Remark = _entity.备注; ;
        //                        _po_mstr.TaskID = taskid;
        //                        _po_mstr.Domain = site.Trim().ToUpper();
        //                        _po_mstr.ModeType = ((int)p_modtype).ToString();
        //                        _po_mstr.Site = subsite.Trim().ToUpper();
        //                        _po_mstr.DataID = Guid.NewGuid();
        //                        _po_mstr.Pricelist = _entity.供应商编号.ToUpper().Trim() + subsite.Trim().Substring(1, 1) + subsite.Substring(3, 1).Trim();
        //                        _po_mstr.Taxclass = _entity.税率;
        //                        if (_po != null)
        //                        {
        //                            _po_mstr.CommandType = "U";
        //                        }
        //                        else
        //                        {
        //                            _po = new TB_PO { GUID = Guid.NewGuid(), PoBillNum = _entity.订单编号.ToUpper(), State = (int)PoState.Open, Site = site, SubSite = subsite, VendId = _entity.供应商编号.Trim().ToUpper() };
        //                            _po_mstr.CommandType = "A";
        //                        }
        //                        db.TED_PO_MSTR.Add(_po_mstr);

        //                        _po.ErpBillNum = _entity.订单编号.Trim().ToUpper();;
        //                        _po.ModType = (int)p_modtype;
        //                        _po.Contacter = p_chineseName;// _entity.联系人;
        //                        _po.Buyer = p_chineseName;// _entity.联系人;
        //                        _po.Site = site.Trim().ToUpper();
        //                        _po.BuyerPhone = p_buyerPhone;
        //                        _po.Remark = _entity.备注;
        //                        _po.IsDeleted = false;
        //                        _po.CreateTime = DateTime.Now;
        //                        _po.CreateUser = p_creator;
        //                        _po.BeginTime = string.IsNullOrEmpty(_entity.订单创建时间) ? DateTime.Now : DateTime.Parse(_entity.订单创建时间);
        //                        _po.EndTime = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.要求到货日期);
        //                        _po.Pricelist = _entity.供应商编号.Trim().ToUpper() + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                        _po.Taxclass = _entity.税率;
        //                        scpdb.TB_PO.AddOrUpdate(_po);

        //                        list.ForEach((itm) =>
        //                        {

        //                            int _poline = Int32.Parse(itm.行号);
        //                            var _PO_Detail = scpdb.TB_PO_DETAIL.FirstOrDefault(t => t.PartCode == itm.零件号 && t.PoLine == _poline && t.PoBillNum == itm.订单编号 /*&& t.State == state*/ && t.Site == site && t.SubSite == subsite);
        //                            TED_PO_DET _PO_Detail_Det = new TED_PO_DET();
        //                            _PO_Detail_Det.GUID = Guid.NewGuid();
        //                            _PO_Detail_Det.PurchaseOrder = itm.订单编号.Trim().ToUpper();
        //                            _PO_Detail_Det.Line = Int32.Parse(itm.行号);
        //                            _PO_Detail_Det.Currency = "CNY";
        //                            _PO_Detail_Det.PoType = itm.订单类型;
        //                            _PO_Detail_Det.PartCode = itm.零件号.Trim().ToUpper();

        //                            _PO_Detail_Det.Qty = decimal.Parse(itm.数量);
        //                            _PO_Detail_Det.QtyOpen = 0;
        //                            _PO_Detail_Det.PackQty = 1;
        //                            _PO_Detail_Det.Currency = itm.币种;
        //                            _PO_Detail_Det.Price = string.IsNullOrEmpty(itm.单价) ? 0 : decimal.Parse(itm.单价);
        //                            var _part = scpdb.TA_PART.FirstOrDefault(part => part.PartCode == itm.零件号.Trim().ToUpper());
        //                            if (_part == null)
        //                            {
        //                                _PO_Detail_Det.PoUm = itm.单位;
        //                                _PO_Detail_Det.LocUm = itm.单位;
        //                            }
        //                            else
        //                            {
        //                                _PO_Detail_Det.PoUm = _part.Unit;
        //                                _PO_Detail_Det.LocUm =_part.Unit;
        //                            }
        //                            _PO_Detail_Det.Conv = 1;
        //                            _PO_Detail_Det.DueDate = string.IsNullOrEmpty(itm.要求到货日期) ? DateTime.Now : DateTime.Parse(itm.要求到货日期);
        //                            _PO_Detail_Det.Status = (int)PoState.Open;
        //                            _PO_Detail_Det.CreateTime = DateTime.Parse(itm.订单创建时间);
        //                            _PO_Detail_Det.StartDate = string.IsNullOrEmpty(itm.零件开始时间) ? p_time : DateTime.Parse(itm.零件开始时间);
        //                            _PO_Detail_Det.EndDate = string.IsNullOrEmpty(itm.零件截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(itm.零件截至日期);
        //                            _PO_Detail_Det.CreateUser = p_creator;
        //                            _PO_Detail_Det.TaskID = taskid;
        //                            if (_PO_Detail != null)
        //                            {
        //                                _PO_Detail_Det.CommandType = "U";
        //                            }
        //                            else
        //                            {
        //                                _PO_Detail = new TB_PO_DETAIL { GUID = Guid.NewGuid(), PartCode = itm.零件号.Trim().ToUpper(), PoLine = _poline, PoBillNum = itm.订单编号.Trim().ToUpper(), State = (int)PoState.Open, Site = site, SubSite = subsite };
        //                                _PO_Detail_Det.CommandType = "A";
        //                            }
        //                            _PO_Detail_Det.DataID = Guid.NewGuid();
        //                            _PO_Detail_Det.Domain = site.Trim().ToUpper();
        //                            _PO_Detail_Det.Site = subsite.Trim().ToUpper();
        //                            _PO_Detail_Det.Workorderlot = itm.加工单号;
        //                            _PO_Detail_Det.PoType = itm.订单类型; 
        //                            _PO_Detail_Det.Operation = string.IsNullOrEmpty(itm.工序) ? 0 : int.Parse(itm.工序);
        //                            _PO_Detail_Det.Location = itm.库位;
        //                            _PO_Detail_Det.Firmdays = string.IsNullOrEmpty(itm.固定天数) ? 7 : int.Parse(itm.固定天数);
        //                            _PO_Detail_Det.Scheduledays = string.IsNullOrEmpty(itm.日程天数) ? 7 : int.Parse(itm.日程天数);
        //                            _PO_Detail_Det.Scheduleweeks = string.IsNullOrEmpty(itm.日程周数) ? 2 : int.Parse(itm.日程周数);
        //                            _PO_Detail_Det.Schedulemonth = string.IsNullOrEmpty(itm.日程月数) ? 1 : int.Parse(itm.日程月数);
        //                            _PO_Detail_Det.Supplieritem = itm.供应商零件;
        //                            _PO_Detail_Det.Dliverypatterncode = itm.发货样式;
        //                            _PO_Detail_Det.Deliverytimecode = itm.发货时间样式;
        //                            _PO_Detail_Det.Transportdays = string.IsNullOrEmpty(itm.运输周期) ? 0 : int.Parse(itm.运输周期);
        //                            _PO_Detail_Det.Pricelist = _entity.供应商编号.Trim().ToUpper() + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                            db.TED_POD_DET.Add(_PO_Detail_Det);
        //                            _PO_Detail.Currency = "CNY";
        //                            _PO_Detail.PoUnit = itm.单位;
        //                            _PO_Detail.CreateTime = DateTime.Now;
        //                            _PO_Detail.CreateUser = p_creator;
        //                            _PO_Detail.BeginTime = string.IsNullOrEmpty(itm.订单创建时间) ? DateTime.Now : DateTime.Parse(itm.订单创建时间);
        //                            _PO_Detail.EndTime = string.IsNullOrEmpty(itm.要求到货日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(itm.要求到货日期);
        //                            _PO_Detail.PlanQty = decimal.Parse(itm.数量);
        //                            _PO_Detail.IsDeleted = false;
        //                            _PO_Detail.LocUnit = itm.单位;
        //                            _PO_Detail.PoUnit = itm.单位;
        //                            _PO_Detail.UnConv = 1;
        //                            _PO_Detail.Remark = itm.备注;
        //                            _PO_Detail.Price = string.IsNullOrEmpty(itm.单价) ? 0 : decimal.Parse(itm.单价);
        //                            _PO_Detail.Workorderlot = string.IsNullOrEmpty(itm.加工单号) ? 0 : int.Parse(itm.加工单号);
        //                            _PO_Detail.PoType =itm.订单类型;
        //                            _PO_Detail.Operation = string.IsNullOrEmpty(itm.工序) ? 0 : int.Parse(itm.工序);
        //                            _PO_Detail.Location = itm.库位;
        //                            _PO_Detail.Firmdays = string.IsNullOrEmpty(itm.固定天数) ? 7 : int.Parse(itm.固定天数);
        //                            _PO_Detail.Scheduledays = string.IsNullOrEmpty(itm.日程天数) ? 7 : int.Parse(itm.日程天数);
        //                            _PO_Detail.Scheduleweeks = string.IsNullOrEmpty(itm.日程周数) ? 2 : int.Parse(itm.日程周数);
        //                            _PO_Detail.Schedulemonth = string.IsNullOrEmpty(itm.日程月数) ? 1 : int.Parse(itm.日程月数);
        //                            _PO_Detail.Supplieritem = itm.供应商零件;
        //                            _PO_Detail.Dliverypatterncode = itm.发货样式;
        //                            _PO_Detail.Deliverytimecode = itm.发货时间样式;
        //                            _PO_Detail.Transportdays = string.IsNullOrEmpty(itm.运输周期) ? 0 : int.Parse(itm.运输周期);
        //                            scpdb.TB_PO_DETAIL.AddOrUpdate(_PO_Detail);
        //                        });
        //                        _polist = _polist + _po.PoBillNum + ",";
        //                    }
        //                    #endregion
        //                    #region 离散单 (离散单只增加不修改)
        //                    if (p_modtype == BillModType.Non_Contract)
        //                    {
        //                        var _entity = list.FirstOrDefault();
        //                        TB_PO _po = new TB_PO();
        //                        _po.GUID = Guid.NewGuid();
        //                        _po.PoBillNum = SCP_BILLCODE_CONTROLLER.MakePoNum(_num);
        //                        _po.State = (int)PoState.Open;
        //                        _po.Site = site.Trim().ToUpper();
        //                        _po.SubSite = subsite.Trim().ToUpper();
        //                        _po.VendId = _entity.供应商编号.Trim().ToUpper();
        //                        _po.ErpBillNum = _po.PoBillNum;
        //                        _po.ModType = (int)p_modtype;
        //                        _po.Contacter = p_chineseName;// _entity.联系人;
        //                        _po.Buyer = p_chineseName;// _entity.联系人;
        //                        _po.BuyerPhone = p_buyerPhone;
        //                        _po.Site = site.Trim().ToUpper();
        //                        _po.Remark = _entity.备注;
        //                        _po.IsDeleted = false;
        //                        _po.CreateTime = DateTime.Now;
        //                        _po.CreateUser = p_creator;
        //                        _po.BeginTime = string.IsNullOrEmpty(_entity.订单创建时间) ? DateTime.Now : DateTime.Parse(_entity.订单创建时间);
        //                        _po.EndTime = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.要求到货日期);
        //                        _po.Pricelist = _entity.供应商编号.ToUpper() + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                        _po.Taxclass = _entity.税率;
        //                        scpdb.TB_PO.AddOrUpdate(_po);
        //                        TB_ASK _ask = new TB_ASK();
        //                        _ask.AskBillNum = SCP_BILLCODE_CONTROLLER.MakeASKCode_BJBQ(_num);
        //                        _ask.GUID = Guid.NewGuid();
        //                        _ask.PoBillNum = _po.PoBillNum;
        //                        _ask.VendId = _entity.供应商编号.Trim().ToUpper();
        //                        _ask.IsDeleted = false;
        //                        _ask.CreateTime = DateTime.Now;
        //                        _ask.CreateUser = p_creator;
        //                        _ask.Site = site.Trim().ToUpper();
        //                        _ask.ReceivedPort = "";//交货口
        //                        _ask.State = (int)AskState.New;
        //                        _ask.Remark = _entity.备注;
        //                        _ask.ModType = (int)p_modtype;
        //                        _ask.ErpBillNum = _po.PoBillNum;
        //                        _ask.BeginTime = p_time;
        //                        _ask.EndTime = DateTime.Parse(_entity.要求到货日期);
        //                        _ask.Buyer = p_chineseName;
        //                        _ask.BuyerPhone = p_buyerPhone;
        //                        _ask.SubSite = subsite;
        //                        scpdb.TB_ASK.Add(_ask);
        //                        TED_PO_MSTR _po_mstr = new TED_PO_MSTR();
        //                        _po_mstr.GUID = Guid.NewGuid();
                          
        //                        _po_mstr.PurchaseOrder = _po.PoBillNum;
        //                        _po_mstr.Supplier = _entity.供应商编号.Trim().ToUpper();
        //                        _po_mstr.Contact = p_chineseName;// _entity.联系人;
        //                        _po_mstr.ShipTo = subsite.Trim().ToUpper();//发往
        //                        _po_mstr.OrderDate = string.IsNullOrEmpty(_entity.订单创建时间) ? DateTime.Now : DateTime.Parse(_entity.订单创建时间);
        //                        _po_mstr.DueDate = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now : DateTime.Parse(_entity.要求到货日期);
        //                        _po_mstr.StartDate = string.IsNullOrEmpty(_entity.订单开始时间) ? DateTime.Now : DateTime.Parse(_entity.订单开始时间);//订单日期
        //                        _po_mstr.EndDate = string.IsNullOrEmpty(_entity.订单截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.订单截至日期);
        //                        _po_mstr.MadeIn = "";
        //                        _po_mstr.Confirm = true;
        //                        _po_mstr.Buyer = p_chineseName;// _entity.采购员;
        //                        _po_mstr.BuyerPhone = p_buyerPhone;// _entity.采购员电话;
        //                        _po_mstr.Status = (int)PoState.Open;
        //                        _po_mstr.ScheduledOrder = false;
        //                        _po_mstr.CreateUser = p_creator;
        //                        _po_mstr.CreateTime = p_time;
        //                        _po_mstr.Remark = _entity.备注; ;
        //                        _po_mstr.TaskID = taskid;
        //                        _po_mstr.CommandType = "A";
        //                        _po_mstr.Domain = site.Trim().ToUpper();
        //                        _po_mstr.ModeType = ((int)p_modtype).ToString();
        //                        _po_mstr.Site = subsite.Trim().ToUpper();
        //                        _po_mstr.DataID = Guid.NewGuid();
        //                        _po_mstr.Pricelist = _entity.供应商编号.ToUpper() + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                        _po_mstr.Taxclass = _entity.税率;
        //                        db.TED_PO_MSTR.Add(_po_mstr);
        //                        int _number = 1;
        //                        list.ForEach((itm) =>
        //                        {
        //                            TB_PO_DETAIL _PO_Detail = new TB_PO_DETAIL();
        //                            _PO_Detail.GUID = Guid.NewGuid();
        //                            _PO_Detail.PartCode = itm.零件号.Trim().ToUpper();
        //                            _PO_Detail.PoLine = _number;
        //                            _PO_Detail.PoBillNum = _po.PoBillNum;
        //                            _PO_Detail.State = (int)PoState.Open;
        //                            _PO_Detail.Site = site.Trim().ToUpper();
        //                            _PO_Detail.SubSite = subsite.Trim().ToUpper();
        //                            _PO_Detail.Currency = "CNY";
        //                            _PO_Detail.PoUnit = itm.单位;
        //                            _PO_Detail.Remark = itm.备注;
        //                            _PO_Detail.CreateTime = DateTime.Now;
        //                            _PO_Detail.CreateUser = p_creator;
        //                            _PO_Detail.BeginTime = string.IsNullOrEmpty(itm.订单创建时间) ? DateTime.Now : DateTime.Parse(itm.订单创建时间);
        //                            _PO_Detail.EndTime = string.IsNullOrEmpty(itm.要求到货日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(itm.要求到货日期);
        //                            _PO_Detail.PlanQty = decimal.Parse(itm.数量);
        //                            _PO_Detail.IsDeleted = false;
        //                            _PO_Detail.LocUnit = itm.单位;
        //                            _PO_Detail.PoUnit = itm.单位;
        //                            _PO_Detail.UnConv = 1;
        //                            _PO_Detail.Price = string.IsNullOrEmpty(itm.单价) ? 0 : decimal.Parse(itm.单价);
        //                            _PO_Detail.Workorderlot = string.IsNullOrEmpty(itm.加工单号) ? 0 : int.Parse(itm.加工单号);
        //                            _PO_Detail.PoType = itm.订单类型;
        //                            _PO_Detail.Operation = string.IsNullOrEmpty(itm.工序) ? 0 : int.Parse(itm.工序);
        //                            _PO_Detail.Location = itm.库位;
        //                            _PO_Detail.Firmdays = string.IsNullOrEmpty(itm.固定天数) ? 7 : int.Parse(itm.固定天数);
        //                            _PO_Detail.Scheduledays = string.IsNullOrEmpty(itm.日程天数) ? 7 : int.Parse(itm.日程天数);
        //                            _PO_Detail.Scheduleweeks = string.IsNullOrEmpty(itm.日程周数) ? 2 : int.Parse(itm.日程周数);
        //                            _PO_Detail.Schedulemonth = string.IsNullOrEmpty(itm.日程月数) ? 1 : int.Parse(itm.日程月数);
        //                            _PO_Detail.Supplieritem = itm.供应商零件;
        //                            _PO_Detail.Dliverypatterncode = itm.发货样式;
        //                            _PO_Detail.Deliverytimecode = itm.发货时间样式;
        //                            _PO_Detail.Transportdays = string.IsNullOrEmpty(itm.运输周期) ? 0 : int.Parse(itm.运输周期);
        //                            _PO_Detail.TempQty = decimal.Parse(itm.数量);
        //                            TB_ASK_DETAIL _tDetail = new TB_ASK_DETAIL();
        //                            _tDetail.Remark = itm.备注;
        //                            _tDetail.PoBillNum = _po.PoBillNum;
        //                            _tDetail.AskBillNum = _ask.AskBillNum;
        //                            _tDetail.PoLine = _number;
        //                            _tDetail.PoUnit = itm.单位;
        //                            _tDetail.CreateTime = DateTime.Now;
        //                            _tDetail.CreateUser = p_creator;
        //                            _tDetail.PartCode = itm.零件号.ToUpper();
        //                            _tDetail.ReceivedPort = "";
        //                            _tDetail.BeginTime = p_time;
        //                            _tDetail.EndTime = Convert.ToDateTime(itm.要求到货日期);
        //                            _tDetail.TempQty = 0;
        //                            _tDetail.AskQty = Decimal.Parse(itm.数量);
        //                            _tDetail.IsDeleted = false;
        //                            _tDetail.LocUnit = itm.单位;
        //                            _tDetail.UnConv = 1;
        //                            _tDetail.State = (int)PoState.Open;
        //                            _tDetail.SubSite = subsite.Trim().ToUpper();
        //                            _tDetail.Site = site.Trim().ToUpper();
        //                            _tDetail.Price = Decimal.Parse(itm.单价);
        //                            _tDetail.GUID = Guid.NewGuid();
        //                            _tDetail.Currency = itm.币种;
        //                            scpdb.TB_ASK_DETAIL.Add(_tDetail);
        //                            scpdb.TB_PO_DETAIL.AddOrUpdate(_PO_Detail);
        //                            TED_PO_DET _PO_Detail_Det = new TED_PO_DET();
        //                            _PO_Detail_Det.GUID = Guid.NewGuid();
        //                            _PO_Detail_Det.PurchaseOrder = _po.PoBillNum;
        //                            _PO_Detail_Det.Line = _number;
        //                            _PO_Detail_Det.Currency = "CNY";
        //                            _PO_Detail_Det.PoType = itm.订单类型;
        //                            _PO_Detail_Det.PartCode = itm.零件号.Trim().ToUpper();
        //                            _PO_Detail_Det.Qty = decimal.Parse(itm.数量);
        //                            _PO_Detail_Det.QtyOpen = 0;
        //                            _PO_Detail_Det.PackQty = 1;
        //                            _PO_Detail_Det.Currency = itm.币种;
        //                            _PO_Detail_Det.Price = string.IsNullOrEmpty(itm.单价) ? 0 : decimal.Parse(itm.单价);
        //                            _PO_Detail_Det.PoUm = itm.单位;
        //                            _PO_Detail_Det.LocUm = itm.单位;
        //                            _PO_Detail_Det.Conv = 1;
        //                            _PO_Detail_Det.DueDate = string.IsNullOrEmpty(itm.要求到货日期) ? DateTime.Now : DateTime.Parse(itm.要求到货日期);
        //                            _PO_Detail_Det.Status = (int)PoState.Open;
        //                            _PO_Detail_Det.CreateTime = DateTime.Parse(itm.订单创建时间);
        //                            _PO_Detail_Det.StartDate = string.IsNullOrEmpty(itm.零件开始时间) ? p_time : DateTime.Parse(itm.零件开始时间);
        //                            _PO_Detail_Det.EndDate = string.IsNullOrEmpty(itm.零件截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(itm.零件截至日期);
        //                            _PO_Detail_Det.CreateUser = p_creator;
        //                            _PO_Detail_Det.TaskID = taskid;
        //                            _PO_Detail_Det.CommandType = "A";
        //                            _PO_Detail_Det.DataID = Guid.NewGuid();
        //                            _PO_Detail_Det.Domain = site.Trim().ToUpper();
        //                            _PO_Detail_Det.Site = subsite.Trim().ToUpper();
        //                            _PO_Detail_Det.Workorderlot = itm.加工单号;
        //                            _PO_Detail_Det.PoType = itm.订单类型;
        //                            _PO_Detail_Det.Operation = string.IsNullOrEmpty(itm.工序) ? 0 : int.Parse(itm.工序);
        //                            _PO_Detail_Det.Location = itm.库位;
        //                            _PO_Detail_Det.Firmdays = string.IsNullOrEmpty(itm.固定天数) ? 7 : int.Parse(itm.固定天数);
        //                            _PO_Detail_Det.Scheduledays = string.IsNullOrEmpty(itm.日程天数) ? 7 : int.Parse(itm.日程天数);
        //                            _PO_Detail_Det.Scheduleweeks = string.IsNullOrEmpty(itm.日程周数) ? 2 : int.Parse(itm.日程周数);
        //                            _PO_Detail_Det.Schedulemonth = string.IsNullOrEmpty(itm.日程月数) ? 1 : int.Parse(itm.日程月数);
        //                            _PO_Detail_Det.Supplieritem = itm.供应商零件;
        //                            _PO_Detail_Det.Dliverypatterncode = itm.发货样式;
        //                            _PO_Detail_Det.Deliverytimecode = itm.发货时间样式;
        //                            _PO_Detail_Det.Transportdays = string.IsNullOrEmpty(itm.运输周期) ? 0 : int.Parse(itm.运输周期);
        //                            _PO_Detail_Det.Pricelist = _entity.供应商编号.ToUpper() + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                            db.TED_POD_DET.Add(_PO_Detail_Det);
        //                            _number++;
        //                        });
        //                        _polist = _polist + _po.PoBillNum + ",";
        //                    }
        //                    #endregion
        //                }
        //                var ret = CREATE_TEA_TASK_SUB(db, true, new TEA_TASK_SUB()
        //                {
        //                    DataCount = 1,
        //                    TaskID = taskid,
        //                    TableName = "TED_PO_MSTR",
        //                    Site = subsite.Trim().ToUpper(),
        //                    Domain = site.Trim().ToUpper(),
        //                    CreateTime = p_time,
        //                    CreateUser = p_creator,
        //                    Creator = "SCP",
        //                });
        //                _num++;
        //                Thread.Sleep(10);
        //            }
        //            );
        //            EntitiesFactory.SaveDb(scpdb);
        //            EntitiesFactory.SaveDb(db);
        //            scope.Complete();
        //            _ret.State = ReturnStatus.Succeed;
        //            _ret.Result = true;
        //            _ret.Message= _polist;

        //        }
        //        catch (Exception e)
        //        {
        //            _ret.State = ReturnStatus.Failed;
        //            LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "InsterPo", e.Message);
        //            _ret.Result = false;
        //            _ret.Message = e.InnerException.Message;
        //            scope.Dispose();

        //        }
        //    }
        //    return _ret;
        //}
        //public static ResultObject<bool> InsterPo(List<SCP_PO_EXPORT_IMPORT_MODEL> p_order_list, string site, string p_creator, DateTime p_time, BillModType p_modtype, string subsite)
        //{
        //    ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
        //    ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
        //    ResultObject<bool> _ret = new ResultObject<bool>();

        //    try
        //    {
        //        var OrderList = p_order_list.GroupBy(p => p.订单编号).ToList();
        //        OrderList.ForEach((p) =>
        //        {
        //            Guid taskid = Guid.NewGuid();
        //            var list = p.ToList();
        //            if (list.Count > 0)
        //            {
        //                var _entity = list.FirstOrDefault();
        //                // int state = (int)PoState.Open;
        //                var update_po = scpdb.TB_PO.FirstOrDefault(t => t.PoBillNum == _entity.订单编号/* && t.State == state*/ && t.Site == site && t.SubSite == subsite && t.VendId == _entity.供应商编号.ToUpper());

        //                TED_PO_MSTR _po = new TED_PO_MSTR();
        //                _po.GUID = Guid.NewGuid();
        //                _po.PurchaseOrder = _entity.订单编号;
        //                _po.Supplier = _entity.供应商编号.ToUpper();
        //                _po.Contact = _entity.联系人;
        //                _po.ShipTo = subsite.Trim().ToUpper();//发往
        //                _po.OrderDate = string.IsNullOrEmpty(_entity.订单创建时间) ? DateTime.Now : DateTime.Parse(_entity.订单创建时间);
        //                _po.DueDate = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now : DateTime.Parse(_entity.要求到货日期);
        //                _po.StartDate = string.IsNullOrEmpty(_entity.订单开始时间) ? DateTime.Now : DateTime.Parse(_entity.订单开始时间);//订单日期
        //                _po.EndDate = string.IsNullOrEmpty(_entity.订单截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.订单截至日期);
        //                _po.MadeIn = "";
        //                _po.Confirm = true;
        //                _po.Buyer = _entity.采购员;
        //                _po.BuyerPhone = _entity.采购员电话;
        //                _po.Status = (int)PoState.Open;
        //                if (p_modtype == BillModType.Contract)
        //                {
        //                    _po.ScheduledOrder = true;
        //                }
        //                else
        //                {
        //                    _po.ScheduledOrder = false;
        //                }
        //                _po.CreateUser = p_creator;
        //                _po.CreateTime = p_time;
        //                _po.Remark = _entity.备注; ;
        //                _po.TaskID = taskid;
        //                if (update_po != null)
        //                {
        //                    _po.CommandType = "U";
        //                }
        //                else
        //                {
        //                    _po.CommandType = "A";
        //                }
        //                _po.Domain = site.Trim().ToUpper();
        //                _po.ModeType = ((int)p_modtype).ToString();
        //                _po.Site = subsite.Trim().ToUpper();
        //                _po.DataID = Guid.NewGuid();
        //                _po.Pricelist = _entity.供应商编号 + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                _po.Taxclass = _entity.税率;
        //                db.TED_PO_MSTR.Add(_po);
        //                list.ForEach((itm) =>
        //                {
        //                    int _poline = Int32.Parse(itm.行号);
        //                    var update_po_detail = scpdb.TB_PO_DETAIL.FirstOrDefault(t => t.PartCode == itm.零件号 && t.PoLine == _poline && t.PoBillNum == itm.订单编号 /*&& t.State == state*/ && t.Site == site && t.SubSite == subsite);
        //                    TED_PO_DET _PO_Detail = new TED_PO_DET();
        //                    _PO_Detail.GUID = Guid.NewGuid();
        //                    _PO_Detail.PurchaseOrder = itm.订单编号;
        //                    _PO_Detail.Line = Int32.Parse(itm.行号);
        //                    _PO_Detail.Currency = "CNY";
        //                    _PO_Detail.PoType = itm.订单类型;
        //                    _PO_Detail.PartCode = itm.零件号.ToUpper();
        //                    _PO_Detail.Qty = decimal.Parse(itm.数量);
        //                    _PO_Detail.QtyOpen = 0;
        //                    _PO_Detail.PackQty = 1;
        //                    _PO_Detail.Currency = itm.币种;
        //                    _PO_Detail.Price = string.IsNullOrEmpty(itm.单价) ? 0 : decimal.Parse(itm.单价);
        //                    _PO_Detail.PoUm = itm.单位;
        //                    _PO_Detail.LocUm = itm.单位;
        //                    _PO_Detail.Conv = 1;
        //                    _PO_Detail.DueDate = string.IsNullOrEmpty(_entity.要求到货日期) ? DateTime.Now : DateTime.Parse(_entity.要求到货日期);
        //                    _PO_Detail.Status = (int)PoState.Open;
        //                    _PO_Detail.CreateTime = DateTime.Parse(itm.订单创建时间);
        //                    _PO_Detail.StartDate = string.IsNullOrEmpty(_entity.零件开始时间) ? p_time : DateTime.Parse(_entity.零件开始时间);
        //                    _PO_Detail.EndDate = string.IsNullOrEmpty(_entity.零件截至日期) ? DateTime.Now.AddYears(30) : DateTime.Parse(_entity.零件截至日期);
        //                    _PO_Detail.CreateUser = p_creator;
        //                    _PO_Detail.TaskID = taskid;
        //                    if (update_po_detail != null)
        //                    {
        //                        _PO_Detail.CommandType = "U";
        //                    }
        //                    else
        //                    {
        //                        _PO_Detail.CommandType = "A";
        //                    }
        //                    _PO_Detail.DataID = Guid.NewGuid();
        //                    _PO_Detail.Domain = site.Trim().ToUpper();
        //                    _PO_Detail.Site = subsite.Trim().ToUpper();
        //                    _PO_Detail.Workorderlot = itm.加工单号;
        //                    _PO_Detail.PoType = itm.订单类型;
        //                    _PO_Detail.Operation = string.IsNullOrEmpty(itm.工序) ? 0 : int.Parse(itm.工序);
        //                    _PO_Detail.Location = itm.库位;
        //                    _PO_Detail.Firmdays = string.IsNullOrEmpty(itm.固定天数) ? 7 : int.Parse(itm.固定天数);
        //                    _PO_Detail.Scheduledays = string.IsNullOrEmpty(itm.日程天数) ? 7 : int.Parse(itm.日程天数);
        //                    _PO_Detail.Scheduleweeks = string.IsNullOrEmpty(itm.日程周数) ? 2 : int.Parse(itm.日程周数);
        //                    _PO_Detail.Schedulemonth = string.IsNullOrEmpty(itm.日程月数) ? 1 : int.Parse(itm.日程月数);
        //                    _PO_Detail.Supplieritem = itm.供应商零件;
        //                    _PO_Detail.Dliverypatterncode = itm.发货样式;
        //                    _PO_Detail.Deliverytimecode = itm.发货时间样式;
        //                    _PO_Detail.Transportdays = string.IsNullOrEmpty(itm.运输周期) ? 0 : int.Parse(itm.运输周期);
        //                    _PO_Detail.Pricelist = _entity.供应商编号 + subsite.Substring(1, 1) + subsite.Substring(3, 1);
        //                    db.TED_POD_DET.Add(_PO_Detail);
        //                });

        //            }
        //            var ret = CREATE_TEA_TASK_SUB(db, true ,new TEA_TASK_SUB()
        //            {
        //                DataCount = 1,
        //                TaskID = taskid,
        //                TableName = "TED_PO_MSTR",
        //                Site = subsite.Trim().ToUpper(),
        //                Domain = site.Trim().ToUpper(),
        //                CreateTime = p_time,
        //                CreateUser = p_creator,
        //                Creator = "SCP",
        //            });
        //        });

        //        if (db.SaveChanges() != -1)
        //        {
        //            _ret.State = ReturnStatus.Succeed;
        //            _ret.Result = true;
        //        }
        //        else
        //        {
        //            _ret.State = ReturnStatus.Failed;
        //            _ret.Result = false;
        //            _ret.Message = "数据更新失败!";
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _ret.State = ReturnStatus.Failed;
        //        LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "InsterPo", e.Message);
        //        _ret.Result = false;
        //        _ret.Message = e.InnerException.Message;
        //        //throw e;
        //    }
        //    return _ret;
        //}

        //public static ResultObject<bool> UpdatePo(List<string> p_po_list, string site, string p_creator, DateTime p_time,  string subsite)
        //{
        //    ScpEntities scpdb = EntitiesFactory.CreateScpInstance();
        //    ExchangeCenterContext db = EntitiesFactory.CreateExchangeCenterInstance();
        //    ResultObject<bool> _ret = new ResultObject<bool>();
        //    try
        //    {
        //        foreach(var _num in p_po_list)
        //        {
        //            Guid taskid = Guid.NewGuid();
        //            TED_PO_MSTR item = new TED_PO_MSTR();
                 
        //            var _mstr = scpdb.TB_PO.FirstOrDefault(t => t.PoBillNum == _num && t.State == (int)PoState.Open);
        //            if (_mstr!= null)
        //            {
        //               // var uid = oldpolist.Select(p => p.UID).Max();
        //              //  var  _mstr = db.TED_PO_MSTR.FirstOrDefault(t => t.UID == uid);

        //                var oldpodetaillist = scpdb.TB_PO_DETAIL.Where(q => q.PoBillNum == _num && q.State == (int)PoState.Open).ToList() ;
        //                item.CommandType = "U";
        //                item.GUID = Guid.NewGuid();
        //                item.DataID = _mstr.GUID;
        //                item.Status = (int)PoState.Close;
        //                item.TaskID = taskid;

        //                item.PurchaseOrder = _mstr.PoBillNum;
        //                item.Supplier = _mstr.VendId;
        //                item.Contact = _mstr.Buyer;
        //                item.ShipTo = _mstr.SubSite;//发往
        //                item.OrderDate = _mstr.CreateTime;//订单日期
        //                item.DueDate = Convert.ToDateTime(_mstr.EndTime);
        //                item.StartDate = _mstr.CreateTime;//订单日期
        //                item.EndDate =Convert.ToDateTime( _mstr.EndTime);
        //                item.MadeIn = "";
        //                item.Confirm = true;
        //                item.Buyer = _mstr.Buyer;
        //                item.BuyerPhone = _mstr.BuyerPhone;
        //                item.ScheduledOrder = _mstr.ModType==1?true:false;
        //                item.CreateUser = _mstr.CreateUser;
        //                item.CreateTime = _mstr.CreateTime;
        //                item.Remark = "订单关闭" ;
        //                item.Domain = _mstr.Site;
        //                item.ModeType = _mstr.ModType.ToString();
        //                item.Site = _mstr.SubSite;
        //                item.Pricelist = _mstr.Pricelist;
        //                item.Taxclass = _mstr.Taxclass;
        //                db.TED_PO_MSTR.Add(item);
        //                if (oldpodetaillist.Count > 0)
        //                {
        //                    foreach (var po_detail in oldpodetaillist)
        //                    {
        //                        TED_PO_DET _PO_Detail = new TED_PO_DET();
        //                        _PO_Detail.GUID = Guid.NewGuid();
        //                        _PO_Detail.PurchaseOrder = po_detail.PoBillNum;
        //                        _PO_Detail.Line = po_detail.PoLine;
        //                        _PO_Detail.Currency = po_detail.Currency;
        //                        _PO_Detail.PoType = po_detail.PoType;
        //                        _PO_Detail.PartCode = po_detail.PartCode.ToUpper();
        //                        _PO_Detail.Qty = po_detail.PlanQty;
        //                        _PO_Detail.QtyOpen = po_detail.ShippedQty;
        //                        _PO_Detail.PackQty = po_detail.PackQty;
        //                        _PO_Detail.Currency = po_detail.Currency;
        //                        _PO_Detail.Price = po_detail.Price;
        //                        _PO_Detail.PoUm = po_detail.PoUnit;
        //                        _PO_Detail.LocUm = po_detail.PoUnit;
        //                        _PO_Detail.Conv = 1;
        //                        _PO_Detail.Status = (int)PoState.Close;
        //                        _PO_Detail.CreateTime = po_detail.CreateTime;
        //                        _PO_Detail.StartDate = Convert.ToDateTime(po_detail.BeginTime);
        //                        _PO_Detail.EndDate = Convert.ToDateTime(po_detail.EndTime);
        //                        _PO_Detail.CreateUser = po_detail.CreateUser;
        //                        _PO_Detail.TaskID = taskid;
        //                        _PO_Detail.CommandType = "U";
        //                        _PO_Detail.DataID = po_detail.GUID;
        //                        _PO_Detail.Domain = po_detail.Site;
        //                        _PO_Detail.Site = po_detail.SubSite;
        //                        _PO_Detail.Workorderlot = po_detail.Workorderlot.ToString();
        //                        _PO_Detail.PoType = po_detail.PoType;
        //                        _PO_Detail.Operation = po_detail.Operation;
        //                        _PO_Detail.Location = po_detail.Location;
        //                        _PO_Detail.Firmdays = po_detail.Firmdays;
        //                        _PO_Detail.Scheduledays = po_detail.Scheduledays;
        //                        _PO_Detail.Scheduleweeks = po_detail.Scheduleweeks;
        //                        _PO_Detail.Schedulemonth = po_detail.Schedulemonth;
        //                        _PO_Detail.Supplieritem = po_detail.Supplieritem;
        //                        _PO_Detail.Dliverypatterncode = po_detail.Dliverypatterncode;
        //                        _PO_Detail.Deliverytimecode = po_detail.Deliverytimecode;
        //                        _PO_Detail.Transportdays = po_detail.Transportdays;
        //                        db.TED_POD_DET.Add(_PO_Detail);
        //                    }
        //                }
        //                var ret = CREATE_TEA_TASK_SUB(db, true, new TEA_TASK_SUB()
        //                {
        //                    DataCount = 1,
        //                    TaskID = taskid,
        //                    TableName = "TED_PO_MSTR",
        //                    Site = subsite,
        //                    Domain = site,
        //                    CreateTime = p_time,
        //                    CreateUser = p_creator,
        //                    Creator = "SCP",
        //                });
        //            }

        //        }               
        //    }
        //    catch (Exception e)
        //    {
        //        _ret.State = ReturnStatus.Failed;
        //        LogHelper.Writlog(LogHelper.LogType.Error, typeof(TEA_TASK_SUB), "InsterPo", e.Message);
        //        _ret.Result = false;
        //        _ret.ErrorList.Add(e);
        //        throw e;
        //    }
        //    if (db.SaveChanges() != -1)
        //    {
        //        _ret.State = ReturnStatus.Succeed;
        //        _ret.Result = true;
        //    }
        //    else
        //    {
        //        _ret.State = ReturnStatus.Failed;
        //        _ret.Result = false;
        //        _ret.Message = "数据更新失败!";
        //    }
        //    return _ret;
        //}
    }

}