using ICS.WCF.Base;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace ICS.CreateShipBySrc
{
    public class CreateShipByPlan
    {
        private static string ERPConStr = Appconfig.GetU9ConnStr();
        private static string ORGCode = ConfigurationManager.AppSettings["orgCode"].ToString();
        private static string UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
        private static string MessageLogName = "根据出货计划创建出货单";



        #region CreateAndApprove  pull式
        public CreateShipRetModel CreateAndApprove(string ListJson)
        {
            MessageLogName = "根据出货计划创建审核出货单";
            CreateShipRetModel res1 = new CreateShipRetModel();
            res1.IsSuccess = false;
            res1.Message = "";
            res1.DocNo = "";
            try
            {
                StringBuilder strHead = new StringBuilder();
                strHead.AppendLine("接口传入参数：" + ListJson);
                Appconfig.WriteLogFile(strHead.ToString(), MessageLogName);
                if (string.IsNullOrEmpty(ListJson))
                {
                    throw new Exception("传入参数为空");
                }
                ShipPlanModel Item = new ShipPlanModel();
                Item = JsonConvert.DeserializeObject<ShipPlanModel>(ListJson);
                if (Item == null)
                {
                    throw new Exception("传入内容为空");
                }
                if (!string.IsNullOrEmpty(Item.ORGCode))
                {
                    ORGCode = Item.ORGCode;
                }
                string ORGID = IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(ORGID))
                {
                    throw new Exception("组织不存在：" + ORGCode);
                }

                string UserID = "";
                string UserName = "";
                if (!string.IsNullOrEmpty(Item.CreatedByCode))
                {
                   DataTable DT_User= GetUser(Item.CreatedByCode );
                    if (DT_User != null && DT_User.Rows.Count > 0)
                    {
                        UserID = DT_User.Rows[0]["ID"].ToString();
                        UserName = DT_User.Rows[0]["NAME"].ToString();
                    }
                }


                List<ShipPlanModel> ItemList = new List<ShipPlanModel>();
                ItemList.Add(Item);
                DataTable dt_ShipPlan = GetShipPlan(ItemList, ORGID);

                if (dt_ShipPlan == null|| dt_ShipPlan.Rows.Count==0)
                {
                    throw new Exception("未抓取到对应出货计划：" + Item.ShipPlanDocNo);
                }

                //string DocTypeID = GetShipTypeID(Item.DocTypeCode, ORGID);
                //if (string.IsNullOrEmpty(DocTypeID))
                //{
                //    throw new Exception("未抓取到对应出货类型数据：" + Item.DocTypeCode);
                //}
                //modify on 20230731 不根据传过来的参数定义，直接根据U9推式生单的配置单据类型创建出货单 单据类型
                string ShipTypeCode = GetShipTypeByPushToDocTypeRule(dt_ShipPlan.Rows[0]["DocumentType"].ToString(), ORGID);

                if (string.IsNullOrEmpty(ShipTypeCode))
                {
                    throw new Exception("未抓取到出货计划(" + dt_ShipPlan.Rows[0]["DocumentType"].ToString() + ")对应出货单的单据类型类型(推式生单配置中)。");
                }

                    string DocTypeID = GetShipTypeID(ShipTypeCode, ORGID);
                if (string.IsNullOrEmpty(DocTypeID))
                {
                    throw new Exception("未抓取到对应出货类型数据：" + Item.DocTypeCode);
                }

                DataTable WH_dt = GetWH(ORGID);
                if (WH_dt == null)
                {
                    throw new Exception("未抓取到仓库数据");
                }
                DataTable dt_Bin = GetBin(ORGID);
                if (dt_Bin == null)
                {
                    throw new Exception("未抓取到库位数据");
                }
                object con = CreateContextObj(ORGID, UserID, Item.CreatedByCode,UserName);//上下文
                UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
                UFIDAU9ISVSMISMPullSrcDocSVClient client = new UFIDAU9ISVSMISMPullSrcDocSVClient();
                long shipDocTypeID = Convert.ToInt64(DocTypeID);//出货单单据类型
                List<UFIDAU9ISVSMSrcDocInfoDTOData> srcDocInfoDTOList = new List<UFIDAU9ISVSMSrcDocInfoDTOData>();
                List<string> LineNoWHList = Item.DetailList.Select(a => a.ShipPlanLineNo+"|" +a.WHCode).Distinct().ToList();

                //Modify on 20230815 :不支持一行出货计划 对应 多个批次 
                //多个批次需要多个行，会报错：已添加了具有相同键的项
                foreach (string LineNoLot  in LineNoWHList)
                {
                    string LineNo = LineNoLot.Split('|')[0]; 
                    string WHCode = LineNoLot.Split('|')[1];
                    List<ShipPlanDetailModel> mmS = Item.DetailList.FindAll(a => a.ShipPlanLineNo == LineNo && a.WHCode == WHCode);
                    decimal ShipQtyALL = 0;

                    DataRow[] drs_wh = WH_dt.Select("Code='" + WHCode + "'");
                    if (drs_wh == null || drs_wh.Length == 0)
                    {
                        throw new Exception("未抓取到对应仓库数据：" + WHCode);
                    }

                    foreach (ShipPlanDetailModel itemmm in mmS)
                    {
                        ShipQtyALL += itemmm.ShipQty;

                        DataRow[] drs_bin = dt_Bin.Select("BinCode='" + itemmm.BinCode + "' and WHCode='" + WHCode + "'");
                        DataRow[] drs_bin_rr = dt_Bin.Select("BinCode='" + itemmm.BinCode + "' ");
                        if (drs_bin == null || drs_bin.Length == 0)
                        {
                            if (drs_bin_rr != null && drs_bin_rr.Length > 0)
                            {
                                throw new Exception("当前库位：" + itemmm.BinCode + "和仓库:" + WHCode + "不对应");
                            }
                            else
                            {
                                throw new Exception("未抓取到当前库位数据：" + itemmm.BinCode);
                            }

                        }
                        
                    }
                    
                    DataRow[] drs = dt_ShipPlan.Select("DocNo='" + Item.ShipPlanDocNo + "' and DocLineNo='" + LineNo + "'");
                    if (drs == null || drs.Length == 0)
                    {
                        throw new Exception("未抓取到对应出货计划行数据：单号" + Item.ShipPlanDocNo + "行号：" + LineNo);
                    }
                    UFIDAU9ISVSMSrcDocInfoDTOData vDTO = new UFIDAU9ISVSMSrcDocInfoDTOData();

                    
                    vDTO.m_wH = Convert.ToInt64(drs_wh[0]["ID"].ToString());
                    vDTO.m_srcDocType = 2;//出货计划
                    vDTO.m_srcDocLineID = Convert.ToInt64(drs[0]["LineID"].ToString());//来源：出货计划行
                    vDTO.m_sOIsConsign = false;//???
                    vDTO.m_curShipQty1 = ShipQtyALL;
                    vDTO.m_curShipQty2 = 0;
                
                    List<UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData> location_list = new List<UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData>();
                    UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData location = new UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData();
                  
                    //UFIDAU9CBOPubControllerCommonArchiveDataDTOData loc = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    //loc.m_iD = Convert.ToInt64(drs_bin[0]["BinID"].ToString());
                    //loc.m_code = mm.BinCode;
                    //loc.m_name = drs_bin[0]["BinName"].ToString();
                    //location.m_srcDocInfoDTO = new www.ufida.org.EntityData.UFIDAU9ISVSMSrcDocInfoDTOData();
                    //location.m_srcDocInfoDTO.m_srcDocLineID= Convert.ToInt64(drs[0]["LineID"].ToString());

                    //location.m_locationCode = mm.BinCode;
                    //location.m_locationName= drs_bin[0]["BinName"].ToString();
                    //location.m_locationNo = 10;
                    //location.m_location = loc;
                    //location.m_locationQtyInvAmount = mm.ShipQty;
                    //location.m_locationQtyTUAmount = mm.ShipQty;

                    //location_list.Add(location);
                    // vDTO.m_locations = location_list.ToArray(); 不加库位信息
                    vDTO.m_lotCode = mmS[0].Lotno;

                    srcDocInfoDTOList.Add(vDTO);
                }
                long[] retIDList = client.Do(out returnMsg, con, shipDocTypeID, Item.shipDate, srcDocInfoDTOList.ToArray());
                if (retIDList != null && retIDList.Count() > 0)
                {
                    String DocNo = GetShipDocNo(retIDList);//查创建的出货单单号  
                    res1.DocNo = DocNo;
                    res1.Message += "创建出货单成功,单号：" + res1.DocNo + ";";
                    Appconfig.WriteLogFile("创建出货单成功,单号：" + res1.DocNo + ";", MessageLogName);

                    //更新物流号
                    if (!string.IsNullOrEmpty(Item.WuLiu))
                    {
                        UpdateShipDescFlexField(retIDList[0], Item.WuLiu);
                    }

                    #region 更新库位信息
                    DataTable dt_NoBin = GetShipNoBin(retIDList[0].ToString(), ORGID);
                    //WH.CODE WHCode,line.LotInfo_LotCode,
                    // cast(Line.SrcDocLineNo as NVARCHAR) + '|' + line.LotInfo_LotCode + '|' + WH.CODE WeiStr
                    if (dt_NoBin != null && dt_NoBin.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt_NoBin.Rows)
                        {
                            List<ShipPlanDetailModel> mml = Item.DetailList.FindAll(a => a.ShipPlanLineNo + "|" + a.WHCode == dr["WeiStr"].ToString());

                            if (mml != null && mml.Count > 0 && dr["SrcDocNo"].ToString() == Item.ShipPlanDocNo)
                            {

                                ICS.CreateShipBinLine.CreateBinModel mm_c = new CreateShipBinLine.CreateBinModel();
                                mm_c.DocNo = DocNo;
                                mm_c.DocLineNo = dr["DocLineNo"].ToString();
                                mm_c.DocLineID = Convert.ToInt64(dr["LineID"].ToString());
                                mm_c.ORGCode = ORGCode;
                                List<CreateShipBinLine.CreateBinDDModel> BINList = new List<CreateShipBinLine.CreateBinDDModel>();

                                //modify on 20230811 修改防止库位传过来有一摸一样的两笔数据
                                List<string> ListBimData = mml.Select(a => a.BinCode + "$" + a.WHCode).Distinct().ToList();

                                foreach (string BINStr in ListBimData)
                                {
                                    string Bin = BINStr.Split('$')[0];
                                    string WHCode = BINStr.Split('$')[1];
                                    List<ShipPlanDetailModel> binss = mml.Where(a => a.BinCode == Bin && a.WHCode == WHCode).ToList();
                                    decimal QtyZ = 0;
                                    foreach (ShipPlanDetailModel mm in binss)
                                    {
                                        QtyZ += mm.ShipQty;
                                    }
                                    CreateShipBinLine.CreateBinDDModel mmm = new CreateShipBinLine.CreateBinDDModel();

                                    mmm.Qty = QtyZ;
                                    mmm.BinCode = Bin;
                                    DataRow[] drs_bin_rr = dt_Bin.Select("BinCode='" + Bin + "' and WHCode='" + WHCode + "'"); 
                                    mmm.BinID = Convert.ToInt64(drs_bin_rr[0]["BinID"].ToString());
                                    BINList.Add(mmm);
                                }

                                //foreach (ShipPlanDetailModel mm in mml)
                                //{
                                //    CreateShipBinLine.CreateBinDDModel mmm = new CreateShipBinLine.CreateBinDDModel();

                                //    mmm.Qty = mm.ShipQty;
                                //    mmm.BinCode = mm.BinCode;
                                //    DataRow[] drs_bin_rr = dt_Bin.Select("BinCode='" + mm.BinCode + "' and WHCode='" + mm.WHCode + "'");
                                //   // DataRow[] drs_bin_rr = dt_Bin.Select("BinCode='" + mm.BinCode + "' ");
                                //    mmm.BinID = Convert.ToInt64(drs_bin_rr[0]["BinID"].ToString());
                                //    BINList.Add(mmm);
                                //}
                                mm_c.BinList = BINList;
                                DataTable dtll = GetShipLineSysVersion(retIDList[0].ToString());
                                DataRow drsss = dtll.Select("LineID='" + mm_c.DocLineID + "'")[0];
                                mm_c.DocLineSysVersion = drsss["SysVersion"].ToString();
                                ICS.CreateShipBinLine.CreateBin cc_c = new CreateShipBinLine.CreateBin();
                                string cc_json = JsonConvert.SerializeObject(mm_c);
                                Appconfig.WriteLogFile(cc_json.ToString(), MessageLogName);
                                ICS.CreateShipBinLine.CreateBinReturnModel cc_ret = cc_c.Create(cc_json); 
                                string cc_jsonret = JsonConvert.SerializeObject(cc_ret);
                                Appconfig.WriteLogFile(cc_jsonret.ToString(), MessageLogName);
                                res1.Message += Environment.NewLine + cc_ret.Message;

                            }
                        }
                    }
                    #endregion

                    #region  审核单据

                    string ListJson_Approve = "";
                    ICS.ApproveShip.AppShipData appm = new ICS.ApproveShip.AppShipData();
                    appm.DocNo = res1.DocNo;
                    appm.ApprovedBy = "admin";
                    appm.ORGCode = ORGCode;
                    ICS.ApproveShip.ApproveShip cc = new ICS.ApproveShip.ApproveShip();
                    ListJson_Approve = JsonConvert.SerializeObject(appm);
                    Appconfig.WriteLogFile(ListJson_Approve.ToString(), MessageLogName);
                    ApproveShip.AppShipReturnModel AppRetModel = cc.Approve(ListJson_Approve.ToString());
                    if (AppRetModel.IsSuccess)
                    {
                        res1.Message += Environment.NewLine + "审核出货单成功；";
                        res1.IsSuccess = true;
                        Appconfig.WriteLogFile("审核出货单成功", MessageLogName);
                    }
                    else
                    {
                        res1.Message += Environment.NewLine + "审核出货单失败：" + AppRetModel.Message;
                        Appconfig.WriteLogFile("审核出货单失败" + AppRetModel.Message, MessageLogName);

                        #region 审核出货单失败，删除出货单

                        string ListJson_delete = "";
                        ICS.DeleteShip.DeletShipData delm = new ICS.DeleteShip.DeletShipData();
                        delm.DocNo = res1.DocNo;
                        delm.ORGCode = ORGCode;
                        ICS.DeleteShip.CustDelete cc_del = new ICS.DeleteShip.CustDelete();
                        ListJson_delete = JsonConvert.SerializeObject(delm);
                        Appconfig.WriteLogFile(ListJson_delete.ToString(), "出货单删除");
                        DeleteShip.DeleteShipReturnModel delRetModel = cc_del.Delete(ListJson_delete.ToString());
                        if (delRetModel.IsSuccess)
                        {
                            res1.Message += Environment.NewLine + "出货单删除成功；";
                            Appconfig.WriteLogFile("出货单删除成功", MessageLogName);
                        }
                        else
                        {
                            res1.Message += Environment.NewLine + "删除出货单失败：" + delRetModel.Message;
                            Appconfig.WriteLogFile("删除出货单失败:"+ delRetModel, MessageLogName);
                        }

                        #endregion

                    }

                    #endregion


                }
                else
                {
                    throw new Exception("创建出货单无返回数据。");
                }


            }
            catch (Exception ex)
            {
                res1.IsSuccess = false;
                res1.Message += GetExceptionMessage(ex);
                Appconfig.WriteLogFile(res1.Message, MessageLogName);
                Appconfig.WriteLogFile(ex.ToString(), MessageLogName);
            }


            StringBuilder strHead2 = new StringBuilder();
            strHead2.AppendLine("***************接口传出参数：");
            strHead2.AppendLine("IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message + "DocNO:" + res1.DocNo);
            strHead2.AppendLine("***************接口传出参数End");
            Appconfig.WriteLogFile(strHead2.ToString(), MessageLogName);
            return res1;

        }

        #endregion

        #region CreateAndApprove 直接创建
        //public CreateShipRetModel CreateAndApproveold(string ListJson)
        //{
        //    MessageLogName = "根据出货计划创建审核出货单";
        //    CreateShipRetModel res1 = new CreateShipRetModel();
        //    res1.IsSuccess = false;
        //    res1.Message = "";
        //    res1.DocNo = "";
        //    try
        //    {
        //        StringBuilder strHead = new StringBuilder();
        //        strHead.AppendLine("接口传入参数：" + ListJson);
        //        Appconfig.WriteLogFile(strHead.ToString(), MessageLogName);
        //        if (string.IsNullOrEmpty(ListJson))
        //        {
        //            throw new Exception("传入参数为空");
        //        }
        //        ShipPlanModel Item = new ShipPlanModel();
        //        Item = JsonConvert.DeserializeObject<ShipPlanModel>(ListJson);
        //        if (Item == null)
        //        {
        //            throw new Exception("传入内容为空");
        //        }
        //        if (!string.IsNullOrEmpty(Item.ORGCode))
        //        {
        //            ORGCode = Item.ORGCode;
        //        }
        //        string ORGID = IsExistsCode(ORGCode, "Base_Organization");

        //        if (string.IsNullOrEmpty(ORGID))
        //        {
        //            throw new Exception("组织不存在：" + ORGCode);
        //        }


        //        List<ShipPlanModel> ItemList = new List<ShipPlanModel>();
        //        ItemList.Add(Item);
        //        DataTable dt_ShipPlan = GetShipPlan(ItemList, ORGID);

        //        if (dt_ShipPlan == null)
        //        {
        //            throw new Exception("未抓取到对应出货计划：" + Item.ShipPlanDocNo);
        //        }

        //        string DocTypeID = GetShipTypeID(Item.DocTypeCode, ORGID);
        //        if (string.IsNullOrEmpty(DocTypeID))
        //        {
        //            throw new Exception("未抓取到对应出货类型数据：" + Item.DocTypeCode);
        //        }

        //        DataTable WH_dt = GetWH(ORGID);
        //        if (WH_dt == null)
        //        {
        //            throw new Exception("未抓取到仓库数据");
        //        }
        //        DataTable dt_Bin = GetBin(ORGID);
        //        if (dt_Bin == null)
        //        {
        //            throw new Exception("未抓取到库位数据");
        //        }
        //        object con = CreateContextObj(ORGID);//上下文
        //        UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
        //        UFIDAU9ISVSMICreateShipSVClient client = new UFIDAU9ISVSMICreateShipSVClient();
        //        long shipDocTypeID = Convert.ToInt64(DocTypeID);//出货单单据类型

        //        List<UFIDAU9ISVSMShipDTOForIndustryChainData> dtoShipList = new List<UFIDAU9ISVSMShipDTOForIndustryChainData>();
        //        UFIDAU9ISVSMShipDTOForIndustryChainData dtoShip = new UFIDAU9ISVSMShipDTOForIndustryChainData();
        //        DataRow[] drs_shipplan = dt_ShipPlan.Select("DocNo='" + Item.ShipPlanDocNo + "' ");
        //        if (drs_shipplan == null || drs_shipplan.Length == 0)
        //        {
        //            throw new Exception("未抓取到对应出货计划单数据：单号" + Item.ShipPlanDocNo);
        //        }
        //        dtoShip.m_documentType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        dtoShip.m_documentType.m_iD = shipDocTypeID;

        //        //价格含税
        //        dtoShip.m_isPriceIncludeTax = true;

        //        //
        //        dtoShip.m_srcDocType = 2; ///来源单据类型 出货计划：2

        //        //创建人  
        //        dtoShip.m_createdBy = "admin";

        //        //预收
        //        dtoShip.m_isARFlag = false;
        //        dtoShip.m_isNoCreditCheck = true;


        //        //客户
        //        dtoShip.m_orderBy = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        dtoShip.m_orderBy.m_code = drs_shipplan[0]["OrderBy_Code"].ToString();   ///客户编码

        //        //业务员
        //        if (!string.IsNullOrEmpty(drs_shipplan[0]["Planer"].ToString()))
        //        {
        //            dtoShip.m_seller = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //            dtoShip.m_seller.m_iD = Convert.ToInt64(drs_shipplan[0]["Planer"].ToString());
        //        }
        //        //部门
        //        if (!string.IsNullOrEmpty(drs_shipplan[0]["Dept"].ToString()))
        //        {
        //            dtoShip.m_saleDept = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //            dtoShip.m_saleDept.m_iD = Convert.ToInt64(drs_shipplan[0]["Dept"].ToString());
        //        }
        //        ////出货确认日
        //        dtoShip.m_shipConfirmDate = Item.shipDate;
        //        dtoShip.m_demandCode = -1;

        //        ////制单日期
        //        dtoShip.m_businessDate = DateTime.Now;


        //        dtoShip.m_shipMode = -1;



        //        List<UFIDAU9ISVSMShipLineDTOForIndustryChainData> dtoShipLines = new List<UFIDAU9ISVSMShipLineDTOForIndustryChainData>();


        //        foreach (ShipPlanDetailModel mm in Item.DetailList)
        //        {
        //            DataRow[] drs = dt_ShipPlan.Select("DocNo='" + Item.ShipPlanDocNo + "' and DocLineNo='" + mm.ShipPlanLineNo + "'");
        //            if (drs == null || drs.Length == 0)
        //            {
        //                throw new Exception("未抓取到对应出货计划行数据：单号" + Item.ShipPlanDocNo + "行号：" + mm.ShipPlanLineNo);
        //            }

        //            DataRow[] drs_wh = WH_dt.Select("Code='" + mm.WHCode + "'");
        //            if (drs_wh == null || drs_wh.Length == 0)
        //            {
        //                throw new Exception("未抓取到对应仓库数据：" + mm.WHCode);
        //            }


        //            UFIDAU9ISVSMShipLineDTOForIndustryChainData vDTO = new UFIDAU9ISVSMShipLineDTOForIndustryChainData();

        //            vDTO.m_demandCode = -1;
        //            //vDTO.m_srcDocType = 2;
        //            //料品
        //            vDTO.m_itemInfo = new www.ufida.org.EntityData.UFIDAU9CBOSCMItemItemInfoData();
        //            vDTO.m_itemInfo.m_itemCode = drs[0]["ItemInfo_ItemCode"].ToString(); ///料号编码;
        //            vDTO.m_itemInfo.m_itemGrade = -1;
        //            vDTO.m_itemInfo.m_itemPotency = -1;
        //            vDTO.m_storageType = 4;

        //            //价格含税
        //            //vDTO.m_isPriceIncludeTax = true;

        //            vDTO.m_isAssociatedChild = false;

        //            vDTO.m_goodsManagementType = -1; ///实物管理方式
        //            vDTO.m_configResult = -1;       ///选配结果
        //            vDTO.m_seibanAlterable = -1;
        //            vDTO.m_innerSupersedeEnum = -1;   ///内部代工
        //            vDTO.m_shipTogetherFlag = -1;        ///成套收发货标志      

        //            //立账条件 立账依据
        //            vDTO.m_confirmAccording = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //            vDTO.m_confirmAccording.m_code = "SD02";


        //            ///是否可修改
        //            vDTO.m_isModifyShipperOrg = false;
        //            vDTO.m_isModifyOperateOrg = false;
        //            vDTO.m_chargeBasis = -1;

        //            vDTO.m_srcDocType = 2;
        //            vDTO.m_srcDocNo = Item.ShipPlanDocNo;
        //            vDTO.m_srcDocLineNo = Convert.ToInt32(mm.ShipPlanLineNo);
        //            vDTO.m_srcDocKey = Convert.ToInt64(drs[0]["ID"].ToString());
        //            vDTO.m_srcDocLineKey = Convert.ToInt64(drs[0]["LineID"].ToString());
        //            vDTO.m_srcDocOwnedOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //            vDTO.m_srcDocOwnedOrg.m_iD = Convert.ToInt64(ORGID);

        //            ///开票
        //            vDTO.m_isMakeOutInvoice = true;

        //            //发货数量
        //            vDTO.m_shipQtyInvAmount = mm.ShipQty;
        //            vDTO.m_shipQtyTUAmount = mm.ShipQty;

        //            //免费品原因
        //            vDTO.m_donationType = -1;
        //            vDTO.m_donationReason = -1;
        //            //拒收原因
        //            vDTO.m_rejectReason = -1;
        //            //存储地点
        //            vDTO.m_wH = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //            vDTO.m_wH.m_iD = Convert.ToInt64(drs_wh[0]["ID"].ToString());
        //            vDTO.m_wH.m_code = mm.WHCode;
        //            vDTO.m_orderPriceTC = Convert.ToDecimal(drs[0]["TaxPriceTC"].ToString());
        //            vDTO.m_finallyPriceTC = Convert.ToDecimal(drs[0]["TaxPriceTC"].ToString());
        //            vDTO.m_totalMoneyTC = Convert.ToDecimal(drs[0]["TaxPriceTC"].ToString()) * mm.ShipQty;
        //            vDTO.m_totalNetMoneyTC = Convert.ToDecimal(drs[0]["NoTaxPriceTC"].ToString()) * mm.ShipQty;
                 
        //            if (!string.IsNullOrEmpty(drs[0]["TaxSchedule"].ToString()))
        //            {
        //                vDTO.m_taxSchedule = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                vDTO.m_taxSchedule.m_iD = Convert.ToInt64(drs[0]["TaxSchedule"].ToString());
        //                vDTO.m_isPriceIncludeTax = true;
        //            }
        //            vDTO.m_taxRate = Convert.ToDecimal(drs[0]["TaxRate"].ToString());


        //            if (!string.IsNullOrEmpty(drs[0]["ProjectCode"].ToString()))
        //            {
        //                vDTO.m_project = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //                vDTO.m_project.m_code = drs[0]["ProjectCode"].ToString();
        //            }

        //            // vDTO.m_saleCostAmount = vDTO.m_shipQtyInvAmount;
        //            vDTO.m_shipQtyCostAmount = vDTO.m_shipQtyInvAmount;
        //            vDTO.m_tUCUConvRatio = 1;

        //            DataRow[] drs_bin = dt_Bin.Select("BinCode='" + mm.BinCode + "' and WHCode='" + mm.WHCode + "'");
        //            DataRow[] drs_bin_rr = dt_Bin.Select("BinCode='" + mm.BinCode + "' ");
        //            if (drs_bin == null || drs_bin.Length == 0)
        //            {
        //                if (drs_bin_rr != null && drs_bin_rr.Length > 0)
        //                {
        //                    throw new Exception("当前库位：" + mm.BinCode + "和仓库:" + mm.WHCode + "不对应");
        //                }
        //                else
        //                {
        //                    throw new Exception("未抓取到当前库位数据：" + mm.BinCode);
        //                }

        //            }
        //            List<www.ufida.org.EntityData.UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData> smLineLocs = new List<www.ufida.org.EntityData.UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData>();
        //            www.ufida.org.EntityData.UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData loc = new www.ufida.org.EntityData.UFIDAU9ISVSMShipLineLocationDTOForIndustryChainData();
        //            loc.m_location = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();

        //            loc.m_location.m_iD = Convert.ToInt64(drs_bin[0]["BinID"].ToString());
        //            loc.m_location.m_code = mm.BinCode;

        //            loc.m_locationQtyInvAmount = mm.ShipQty;
        //            loc.m_locationQtyTUAmount = mm.ShipQty;
        //            smLineLocs.Add(loc);
        //            vDTO.m_shipLineLocations = smLineLocs.ToArray();
        //            vDTO.m_lotInfo = new www.ufida.org.EntityData.UFIDAU9CBOSCMPropertyTypesLotInfoData();
        //            vDTO.m_lotInfo.m_lotCode= mm.Lotno;
                  


        //            dtoShipLines.Add(vDTO);
        //        }
        //        dtoShip.m_shipLines = dtoShipLines.ToArray();
        //        dtoShipList.Add(dtoShip);
        //        UFIDAU9ISVSMDocKeyDTOData[] retIDList = client.Do(out returnMsg, con, dtoShipList.ToArray(), false);
        //        if (retIDList != null && retIDList.Count() > 0)
        //        {
        //            String DocNo = "";
        //            foreach (UFIDAU9ISVSMDocKeyDTOData rrr in retIDList)
        //            {
        //                DocNo += rrr.m_docNO + ",";
        //            }
        //            DocNo = DocNo.TrimEnd(',');
        //            res1.DocNo = DocNo;
        //            res1.Message += "创建出货单成功,单号：" + res1.DocNo + ";";

        //            #region  审核单据

        //            string ListJson_Approve = "";
        //            ICS.ApproveShip.AppShipData appm = new ICS.ApproveShip.AppShipData();
        //            appm.DocNo = res1.DocNo;
        //            appm.ApprovedBy = "admin";
        //            appm.ORGCode = ORGCode;
        //            ICS.ApproveShip.ApproveShip cc = new ICS.ApproveShip.ApproveShip();
        //            ListJson_Approve = JsonConvert.SerializeObject(appm);
        //            Appconfig.WriteLogFile(ListJson_Approve.ToString(), "出货单审核");
        //            ApproveShip.AppShipReturnModel AppRetModel = cc.Approve(ListJson_Approve.ToString());
        //            if (AppRetModel.IsSuccess)
        //            {
        //                res1.Message += "审核出货单成功；";
        //                res1.IsSuccess = true;
        //            }
        //            else
        //            {
        //                res1.Message += "审核出货单失败：" + AppRetModel.Message;

        //                #region 审核出货单失败，删除出货单

        //                string ListJson_delete = "";
        //                ICS.DeleteShip.DeletShipData delm = new ICS.DeleteShip.DeletShipData();
        //                delm.DocNo = res1.DocNo;
        //                delm.ORGCode = ORGCode;
        //                ICS.DeleteShip.CustDelete cc_del = new ICS.DeleteShip.CustDelete();
        //                ListJson_delete = JsonConvert.SerializeObject(delm);
        //                Appconfig.WriteLogFile(ListJson_delete.ToString(), "出货单删除");
        //                DeleteShip.DeleteShipReturnModel delRetModel = cc_del.Delete(ListJson_delete.ToString());
        //                if (delRetModel.IsSuccess)
        //                {
        //                    res1.Message += "出货单删除成功；";
        //                }
        //                else
        //                {
        //                    res1.Message += "删除出货单失败：" + delRetModel.Message;
        //                }

        //                #endregion

        //            }

        //            #endregion


        //        }
        //        else
        //        {
        //            string Err = "";
        //            if (returnMsg != null && returnMsg.Length > 0)
        //            {
        //                foreach (UFSoft.UBF.Exceptions.MessageBase mmss in returnMsg)
        //                {
        //                    Err += mmss.localMessage;
        //                }
        //            }
        //            throw new Exception("创建出货单无返回数据:" + Err);
        //        }


        //    }
        //    catch (Exception ex)
        //    {
        //        res1.IsSuccess = false;
        //        res1.Message = GetExceptionMessage(ex);
        //        Appconfig.WriteLogFile(res1.Message, MessageLogName);
        //        Appconfig.WriteLogFile(ex.ToString(), MessageLogName);
        //    }


        //    StringBuilder strHead2 = new StringBuilder();
        //    strHead2.AppendLine("***************接口传出参数：");
        //    strHead2.AppendLine("IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message + "DocNO:" + res1.DocNo);
        //    strHead2.AppendLine("***************接口传出参数End");
        //    Appconfig.WriteLogFile(strHead2.ToString(), MessageLogName);
        //    return res1;

        //}

        #endregion

        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private static string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

            System.TimeoutException timeoutEx = ex as System.TimeoutException;
            if (timeoutEx != null)
            {
                faultMessage = "访问服务超时，请修改配置信息！";
            }
            else
            {
                FaultException<ServiceException> faultEx = ex as FaultException<ServiceException>;
                if (faultEx == null)
                {
                    faultMessage = ex.Message;
                }
                else
                {
                    ServiceException serviceEx = faultEx.Detail;
                    if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message)
                        && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase))
                    {
                        // 错误信息在faultEx.Message中，请提取，
                        // 格式为"Fault:料品不能为空，请录入\n 在....."
                        int startIndex = serviceEx.Message.IndexOf(":");
                        int endIndex = serviceEx.Message.IndexOf("\n");
                        if (endIndex == -1)
                            endIndex = serviceEx.Message.Length;
                        if (endIndex > 0 && endIndex > startIndex + 1)
                        {
                            faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
                        }
                        else
                        {
                            faultMessage = serviceEx.Message;
                        }
                    }
                }
            }
            return faultMessage;
        }
        #endregion

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID,string UserID,string UserCode,string UserName)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            if (!string.IsNullOrEmpty(UserID))
            {
                ns.Add("UserID", UserID);
                ns.Add("UserCode", UserCode);
                ns.Add("UserName", UserName);
            }
            else
            {
                ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
                ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
                ns.Add("UserName", ConfigurationManager.AppSettings["userCode"].ToString());
            }
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion

        private string IsExistsCode(string Code, string TableName)
        {
            string sql = @"    select  id from  " + TableName + @"  where code='" + Code + @"' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            return "";
        }

        private static DataTable GetUser(string Code )
        {
            string sql = @"   select  cc.ID,cc.CODE,CC.NAME from Base_User cc WHERE cc.CODE='"+ Code + @"'  ";
            DataTable dt = DBhlper.Query(sql, ERPConStr); 
            return dt;
        }

        private string GetShipDocNo(long[] IDList )
        {
            string Str = string.Join(",", IDList);
            Str = Str.Replace(",","','");
            string sql = @"    SELECT docno  from sm_ship where id in ('"+ Str + @"') ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                string Docno = "";
                foreach (DataRow dr in dt.Rows)
                {
                    Docno += dr["docno"].ToString() + ",";
                }
                Docno = Docno.TrimEnd(',');
                return Docno;
            }
            return "";
        }


        private void UpdateShipDescFlexField(long  ID  ,string DescFlexField1)
        {
           
            string sql = @"   update sm_ship 
                set DescFlexField_PrivateDescSeg1='"+ ReSetString(DescFlexField1) + @"' 
                where id  ='"+ ID + @"'";
            DBhlper.EXecute(sql, ERPConStr);
           
        }



        private DataTable GetShipPlan(List<ShipPlanModel>  List,string ORGID)
        {
            string[] DocNoList = List.Select(a=>a.ShipPlanDocNo).ToArray();
            string Str = string.Join(",", DocNoList);
            Str = Str.Replace(",", "','");
            string sql = @"     SELECT DOC.DocNo,Doc.ID,LINE.ID LineID ,line.doclineno DocLineNo ,doc.DocumentType,
line.OrderBy_Code,doc.Planer,ops.Dept,
	 line.ItemInfo_ItemCode,line.TotalMoneyTC,line.TaxPriceTC,line.NetMoneyTC,line.TaxRate,cus.TaxSchedule,
pro.code ProjectCode,line.NoTaxPriceTC
                                from SM_ShipPlan DOC
	                            LEFT JOIN SM_ShipPlanLine LINE ON DOC.ID=LINE.ShipPlan
								left join CBO_Operators ops on ops.id=doc.Planer
								left join CBO_Customer cus on cus.id=line.OrderBy_customer
								left join CBO_Project pro on pro.id=line.Project
                            where DOC.docno in ('" + Str + @"') and DOC.org='" + ORGID + @"' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                
                return dt;
            }
            return null;
        }


        


        private string GetShipTypeID(string DocTypeCode, string ORGID)
        {
             
            string sql = @"   select  ID from SM_ShipDocType where code='"+ DocTypeCode + "' and org='"+ ORGID + "' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {

                return dt.Rows[0][0].ToString();
            }
            return "";
        }

        private string GetShipTypeByPushToDocTypeRule(string SHIPPlanDocTypeID, string ORGID)
        {

            string sql = @"  SELECT TT.TargetDocTypeCode 出货单据类型编码,   stt.code 出货计划单据类型编码 
                        FROM Base_PushToDocTypeRuleLine TT 
                        LEFT JOIN Base_PushToDocTypeRule RR ON TT.PushToDocTypeRule=RR.ID
                        left join SM_ShipPlanDocType stt on stt.id=TT.EntityFieldValue3 
                         WHERE 1=1 
                         and RR.TargetOrg='" + ORGID + @"'
                          AND stt.id='" + SHIPPlanDocTypeID + @"'
                         and stt.id is not null ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {

                return dt.Rows[0]["出货单据类型编码"].ToString();
            }
            return "";
        }

        private DataTable GetWH(  string ORGID)
        {

            string sql = @"   	select  ID ,Code from CBO_Wh where   org='"+ ORGID + "' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            { 
                return dt ;
            }
            return null;
        }


        private DataTable GetBin(string ORGID)
        {

            string sql = @"   		
                select  bin.ID BinID ,bin.code BinCode,WH.ID WHID,wh.code WHCode ,BINt.Name BinName
		          from CBO_Bin bin
                left join CBO_Bin_Trl BINt on bin.id=BINt.id and BINt.sysmlflag='zh-CN'
	               left join cbo_wh wh on wh.id=bin.Warehouse
	               where bin.org='" + ORGID + "' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt;
            }
            return null;
        }

        private DataTable GetShipNoBin(string DocNoID, string ORGID)
        {
           
            string sql = @"  
                select doc.DocNo,Line.ID LineID,Line.DocLineNo DocLineNo,Line.ShipQtyTUAmount,
                Line.SrcDocNo,Line.SrcDocLineNo,Line.SysVersion,WH.CODE WHCode,line.LotInfo_LotCode ,
cast(Line.SrcDocLineNo as NVARCHAR) + '|'   + WH.CODE WeiStr
                    from sm_ship doc
	                left join SM_ShipLine Line on doc.id=line.ship
	                left join SM_ShipLineLocation subl on subl.ShipLine=line.id
					LEFT JOIN CBO_WH WH ON WH.ID=Line.WH
	                where doc.ID='" + DocNoID + @"'  
                    AND subl.id is null";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            { 
                return dt;
            }
            return null;
        }
        private DataTable GetShipLineSysVersion(string DocNoID )
        {

            string sql = @"  
                select doc.DocNo,Line.ID LineID,Line.DocLineNo DocLineNo,Line.SysVersion 
                    from sm_ship doc
	                left join SM_ShipLine Line on doc.id=line.ship 
	                where doc.ID='" + DocNoID + @"'   ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt;
            }
            return null;
        }

        private static string ReSetString(string Str)
        {
            string NewStr = Str;
            if (!string.IsNullOrEmpty(Str))
            {
                NewStr = Str.Replace("'", "''");

            }
            return NewStr;
        }



    }
}
