using ICS.CreateLotMaster;
using ICS.WCF.Base;
using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace ICSSoft.DataProject
{
    /// <summary>
    /// 调拨单
    /// </summary>
    public class TransferDoc
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
        private static string CRNALL = System.Configuration.ConfigurationManager.AppSettings["TransDCRDNAME"];
        private static string ERPConStr = Appconfig.GetU9ConnStr();
        private static string LogName = "调拨申请单转调出单";
        /// <summary>
        /// 审核调拨单
        /// </summary>
        /// <param name="Bills"></param>
        /// <returns></returns>
        public bool ConfirmTrans(List<ICSTransferDoc> Bills)
        {
            bool ResultFlag = false;
            string connS = "";
            //int num = 0;
            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();

            if (Bills.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            LogInfo(Bills);
            List<string> result = Bills.Select(t => t.WorkPoint).Distinct().ToList();


            foreach (string WorkPoint in result)
            {
                try
                {
                    connS = string.Format(connString, WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    foreach (ICSTransferDoc head in Bills)
                    {
                        if (WorkPoint != head.WorkPoint)
                            continue;
                        if (!DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
                            throw new Exception("U8正在整理现存量，请稍后再试");

                        string[] ss = head.WorkPoint.Split('_');
                        ERPDB = ss[1];
                        string sql = "";
                        ICSUserInfo userInfo = new ICSUserInfo();
                        userInfo = DBHelper.GetPersonInfo(head.User, cmd);
                        string cIWhCode = string.Empty;
                        string cOWhCode = string.Empty;
                        #region 检查
                        sql = "select * from dbo.TransVouch where ID='" + head.ID + "';";
                        DataTable dtCheck = DBHelper.SQlReturnData(sql, cmd);
                        if (dtCheck != null && dtCheck.Rows.Count > 0)
                        {
                            string cHandler = dtCheck.Rows[0]["cVerifyPerson"].ToString();
                            if (!string.IsNullOrEmpty(cHandler))
                            {
                                throw new Exception("调拨单ID：" + head.ID + "不是开立状态！");
                            }
                            cIWhCode = dtCheck.Rows[0]["cIWhCode"].ToString();
                            cOWhCode = dtCheck.Rows[0]["cOWhCode"].ToString();
                            sql = string.Format("select * from Warehouse where cWhCode in ('{0}','{1}')", dtCheck.Rows[0]["cOWhCode"].ToString(), dtCheck.Rows[0]["cIWhCode"].ToString());
                            DataTable dtWh = DBHelper.SQlReturnData(sql, cmd);
                            if (dtWh != null && dtWh.Rows.Count > 1)
                            {
                            }
                            else
                            {
                                throw new Exception("调拨单中转入或者转出仓库不存在！");
                            }
                        }
                        else
                        {
                            throw new Exception("调拨单ID：" + head.ID + "在U8中不存在！");
                        }
                        #endregion

                        #region 审核
                        sql = "UPDATE dbo.TransVouch SET cVerifyPerson='" + userInfo.UserName + "' ,dVerifyDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("审核调拨单失败！异常：" + ex.Message + "；\r\n SQL:" + sql);
                            throw new Exception("程序异常，请联系开发人员！");
                        }
                        int bodyID = 0;
                        //                    foreach (ICSTransferDoc body in Bills)
                        //                    {
                        //                        //回写调出仓库待发数量
                        //                        string fOutcBatch = string.Empty;
                        //                        //bodyID = Convert.ToInt32(body);
                        //                        sql = @"UPDATE a SET fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0)
                        //                                FROM dbo.CurrentStock a
                        //                                LEFT JOIN (SELECT a.cOWhCode,a.cIWhCode,b.cInvCode,b.autoID,
                        //                            ISNULL(b.cTVBatch,'') AS cTVBatch FROM dbo.TransVouch a 
                        //                            INNER JOIN dbo.TransVouchs b ON a.cTVCode = b.cTVCode)b 
                        //                              ON a.cInvCode=b.cInvCode AND a.cBatch=b.cTVBatch and a.cWhCode=b.cOWhCode WHERE b.autoID=@bodyID";
                        //                        cmd.Parameters.Clear();
                        //                        //cmd.Parameters.Add(new SqlParameter("@Qty", dtCheck.Rows[0]["iQuantity"].ToString()));
                        //                        cmd.Parameters.Add(new SqlParameter("@bodyID",body.ID));
                        //                        cmd.CommandText = sql;
                        //                        try
                        //                        {
                        //                            cmd.ExecuteNonQuery();
                        //                        }
                        //                        catch (Exception ex)
                        //                        {
                        //                            log.Error("回写现存量表 待调拨数量！异常：" + ex.Message + "；\r\n SQL:" + sql);
                        //                            throw new Exception("程序异常，请联系开发人员！");
                        //                        }

                        ////                        #region 判断现存量是否足够
                        ////                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransOutQuantity<0)
                        ////                            BEGIN
                        ////	                            DECLARE @MSG NVARCHAR(100)
                        ////	                            SELECT @MSG='ERP待调拨出库数量不足！AutoID：'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransOutQuantity<0
                        //// 	                            RAISERROR(@MSG,16,1)
                        ////                            END";

                        ////                        cmd.CommandText = sql;
                        ////                        cmd.ExecuteNonQuery();
                        ////                        #endregion
                        //                        //回写调入仓库在途数量
                        //                        fOutcBatch = string.Empty;
                        //                        sql = @"UPDATE a SET fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)
                        //                                FROM dbo.CurrentStock a
                        //                                LEFT JOIN (SELECT a.cOWhCode,a.cIWhCode,b.cInvCode,b.autoID,
                        //                            ISNULL(b.cTVBatch,'') AS cTVBatch FROM dbo.TransVouch a 
                        //                            INNER JOIN dbo.TransVouchs b ON a.cTVCode = b.cTVCode)b 
                        //                              ON a.cInvCode=b.cInvCode AND a.cBatch=b.cTVBatch and a.cWhCode=b.cIWhCode WHERE b.autoID=@bodyID";
                        //                        cmd.Parameters.Clear();
                        //                        //cmd.Parameters.Add(new SqlParameter("@Qty", dtCheck.Rows[0]["iQuantity"].ToString()));
                        //                        cmd.Parameters.Add(new SqlParameter("@bodyID", body.ID));
                        //                        cmd.CommandText = sql;
                        //                        try
                        //                        {
                        //                            cmd.ExecuteNonQuery();
                        //                        }
                        //                        catch (Exception ex)
                        //                        {
                        //                            log.Error("回写现存量表在途数量！异常：" + ex.Message + "；\r\n SQL:" + sql);
                        //                            throw new Exception("程序异常，请联系开发人员！");
                        //                        }

                        ////                        #region 判断现存量是否足够
                        ////                        sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransInQuantity<0)
                        ////                            BEGIN
                        ////	                            DECLARE @MSG NVARCHAR(100)
                        ////	                            SELECT @MSG='ERP待调拨入库数量不足！AutoID：'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fTransInQuantity<0
                        //// 	                            RAISERROR(@MSG,16,1)
                        ////                            END";

                        ////                        cmd.CommandText = sql;
                        ////                        cmd.ExecuteNonQuery();
                        ////                        #endregion
                        //                    }
                        #endregion
                        //0305 形态转换单CartonNum
                        sql = "select * from dbo.TransVouchs where ID='" + head.ID + "';";
                        DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
                        #region 其他入库单
                        //取得out库单的默认显示模版

                        string[] dd = CRNALL.Split('~');
                        string crdname = dd[2];
                        string crdname1 = dd[3];
                        string carname = dd[4];
                        string carname1 = dd[5];
                        string surface = dd[6];
                        string cardnewcode = DBHelper.GetCardNumber(carname, cmd);
                        string cardnewcode1 = DBHelper.GetCardNumber(carname1, cmd);

                        VouchKey key08 = new VouchKey();
                        //key08 = U8Helper.GetPrimaryKey("rd", ErpName, 1, cmd);
                        //// 取得表头单据号
                        //string Code08 = U8Helper.GetRdrecord08Code(ErpName, "QR", cmd);
                        var num = dtChecks.Rows.Count;
                        Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
                        int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                        int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                        DateTime date = DateTime.Now;
                        string cRDcode08 = DBHelper.GetRDCode(crdname1, cmd);
                        string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode1, "" + date + "", "admin", cRDcode08, head.WorkPoint);

                        string DEF_ID08 = DBHelper.GetDefaultTemplate(cardnewcode1, cmd);
                        #region  其他入库单表头
                        sql = @"INSERT INTO dbo.RdRecord08
                        (ID,bRdFlag,cVouchType,cBusType,cSource,cBusCode,cWhCode,dDate,cCode,cRdCode,
                        cHandler,cMemo,bTransFlag,cMaker,dVeriDate,bpufirst,biafirst,VT_ID,bIsSTQc,bOMFirst,
                        bFromPreYear,bIsComplement,iDiscountTaxType,ireturncount,
                        iverifystate,iswfcontrolled,dnmaketime,dnverifytime,bredvouch,cSourceLs,cDepCode)

                         SELECT @ID,'1','08','调拨入库','调拨',a.cTVCode,cIWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),a.cTVCode,@cRdCode,
                        @cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
                        @VT_ID,'0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0','1',cIDepCode from dbo.TransVouch a WHERE ID='" + head.ID + "' ";

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        //cmd.Parameters.Add(new SqlParameter("@cBusCode", head.ID));

                        cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                        cmd.Parameters.Add(new SqlParameter("@cHandler", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@cMemo", ""));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID08));
                        cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode08));
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成其他入库单表头失败！调拨单ID：" + head.ID + ";异常：" + ex.Message + "；SQL：\r\n" + sql);
                            throw new Exception("程序异常，请联系开发人员！");
                        }
                        #endregion

                        #region 3.5 其他入库单表体
                        for (int i = 0; i < dtChecks.Rows.Count; i++)
                        {
                            #region 3.5.1 表体
                            sql = @"INSERT INTO dbo.rdrecords08
                        (AutoID,ID,cInvCode,iQuantity,iSOutQuantity,iSOutNum,iFlag,iTrIds,iNQuantity,iNum,
                        cMassUnit,bLPUseFree,iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,cbaccounter,cBatch,iPUnitCost,iPPrice,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
                        SELECT @AutoID,@ID,cInvCode,a.iTVQuantity,'0','0','0',a.AutoID,iTVQuantity,iTVNum,
                         '0','0','0','0','1','0','0','0',@irowno,null,cTVBatch,iTVPCost,iTVPPrice ,a.cFree1,a.cFree2,a.cFree3,a.cFree4,a.cFree5,a.cFree6,a.cFree7,a.cFree8,a.cFree9,a.cFree10
                        from TransVouchs a
                        inner join  TransVouch b on a.ID=b.ID
                       where a.autoid='" + dtChecks.Rows[i]["AutoID"].ToString() + @"';";

                            cmd.Parameters.Clear();
                            cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                            cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                            cmd.Parameters.Add(new SqlParameter("@irowno", dtChecks.Rows[i]["irowno"].ToString()));
                            cmd.CommandText = sql;
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                log.Error("生成其他出库单表体失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                                throw new Exception("程序异常，请联系开发人员！");
                            }
                            #endregion

                            //更新现存量
                            key08.cBustypeUN = "调拨入库";
                            key08.cVouchTypeUN = "08";
                            key08.TableName = "IA_ST_UnAccountVouch08";
                            key08.UpdateTodoQuantity = head.UpdateTodoQuantity;
                            //DBHelper.UpdateCurrentStockNEW(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cIWhCode, dtChecks.Rows[i]["cTVBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(), dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(), key08);

                            DBHelper.UpdateCurrentStockCCGC(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cIWhCode, dtChecks.Rows[i]["cTVBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), Convert.ToDecimal(dtChecks.Rows[i]["iTVNum"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(),
                     dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(),
                     "", key08, "", "", "", "", 0, 0, 0, 0, -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), -Convert.ToDecimal(dtChecks.Rows[i]["iTVNum"].ToString()), 0, 0, iFatherId, iChildId);
                            //DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cIWhCode, "", Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), key08);
                            iChildId--;
                        }

                        #endregion

                        #endregion

                        #region 其他出库单


                        //取得采购入库单单据 表头ID，表体DID
                        VouchKey key09 = new VouchKey();
                        //key09 = U8Helper.GetPrimaryKey("rd", ErpName, 1, cmd);
                        //// 取得表头单据号
                        //string Code09 = U8Helper.GetRdrecord09Code(ErpName, "QC", cmd);
                        var nums = dtChecks.Rows.Count;
                        Dictionary<string, int> dics = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + nums + "", head.WorkPoint);
                        int iFatherIds = Convert.ToInt32(dics["iFatherId"].ToString());
                        int iChildIds = Convert.ToInt32(dics["iChildId"].ToString());
                        DateTime dates = DateTime.Now;
                        string cRDcode09 = DBHelper.GetRDCode(crdname, cmd);
                        string iBaseCodeLens = DBHelper.GetAllRDCode(cardnewcode, "" + date + "", "admin", cRDcode09, head.WorkPoint);

                        string DEF_ID09 = DBHelper.GetDefaultTemplate(cardnewcode, cmd);
                        #region  其他出库单表头
                        sql = @"INSERT INTO dbo.RdRecord09
        (ID,bRdFlag,cVouchType,cBusType,cSource,cBusCode,cWhCode,dDate,cCode,cRdCode,
        cHandler,cMemo,bTransFlag,cMaker,dVeriDate,bpufirst,biafirst,VT_ID,bIsSTQc,bOMFirst,
        bFromPreYear,bIsComplement,iDiscountTaxType,ireturncount,
        iverifystate,iswfcontrolled,dnmaketime,dnverifytime,bredvouch,cSourceLs,cDepCode)

        SELECT @ID,'0','09','调拨出库','调拨',a.cTVCode,cOWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,@cRdCode,
        @cHandler,@cMemo,'0',@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),'0','0',
        '85','0','0','0','0','0','0','0','0',GETDATE(),GETDATE(),'0','1',cODepCode from dbo.TransVouch a WHERE ID='" + head.ID + "' ";

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));
                        //cmd.Parameters.Add(new SqlParameter("@cBusCode", dtCheck.Rows[0]["cTVCode"].ToString()));
                        //cmd.Parameters.Add(new SqlParameter("@cWhCode", cOWhCode));
                        cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLens));
                        cmd.Parameters.Add(new SqlParameter("@cHandler", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@cMemo", ""));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
                        cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID09));
                        cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode09));
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成其他出库单失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                            throw new Exception("程序异常，请联系开发人员！");
                        }
                        #endregion

                        #region 3.5 其他出库单表体
                        for (int i = 0; i < dtChecks.Rows.Count; i++)
                        {
                            #region 3.5.1 表体

                            //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                            //sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtCheck.Rows[0]["cInvCode"].ToString() + "'AND cWhCode='" + dtCheck.Rows[0]["cOWhCode"].ToString() + "'";
                            //DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
                            //if (dtItem != null && dtItem.Rows.Count > 0)
                            //{
                            //    if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cTVBatch))
                            //    {
                            //        throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                            //    }
                            //    if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < body.iQuantity)
                            //    {
                            //        throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + body.cInvCode);
                            //    }

                            //}
                            //else
                            //{
                            //    throw new Exception("物料:" + body.cInvCode + "在现存量表中不存在!");
                            //}
                            //key09.DID += 1;
                            //Rd09irowno += 1;
                            sql = @"INSERT INTO dbo.rdrecords09
                        (AutoID,ID,cInvCode,iQuantity,iSOutQuantity,iSOutNum,iFlag,iTrIds,iNQuantity,iNum,
                        cMassUnit,bLPUseFree,iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,cbaccounter,cBatch,iPUnitCost,iPPrice,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
                        SELECT @AutoID,@ID,cInvCode,a.iTVQuantity,'0','0','0',a.AutoID,iTVQuantity,iTVNum,
                         '0','0','0','0','1','0','0','0',a.irowno,null,cTVBatch,iTVPCost,iTVPPrice ,a.cFree1,a.cFree2,a.cFree3,a.cFree4,a.cFree5,a.cFree6,a.cFree7,a.cFree8,a.cFree9,a.cFree10
                         from TransVouchs a
                        inner join TransVouch b on a.ID=b.ID
                        where a.autoid='" + dtChecks.Rows[i]["AutoID"].ToString() + @"' ;";

                            cmd.Parameters.Clear();
                            cmd.Parameters.Add(new SqlParameter("@AutoID", iChildIds));
                            cmd.Parameters.Add(new SqlParameter("@ID", iFatherIds));


                            cmd.CommandText = sql;
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                log.Error("生成其他出库单表体失败！调拨单ID：" + head.ID + "；异常：" + ex.Message + "；SQL：\r\n" + sql);
                                throw new Exception("程序异常，请联系开发人员！");
                            }

                            sql = @"INSERT INTO dbo.rdrecords09sub
                                ( AutoID , ID ,iBG_Ctrl , iBGSTSum )
                                values('" + iChildIds + "','" + iFatherIds + "',0,0)";
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();
                            #endregion
                            if (head.UpdateStock)
                            {
                                //更新现存量
                                key09.cBustypeUN = "调拨出库";
                                key09.cVouchTypeUN = "09";
                                key09.TableName = "IA_ST_UnAccountVouch09";
                                //DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cOWhCode, "", -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), key09);
                                //DBHelper.UpdateCurrentStockNEW(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cOWhCode, dtChecks.Rows[i]["cTVBatch"].ToString(), -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(), dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(), key09);
                                DBHelper.UpdateCurrentStockCCGC(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), cOWhCode, dtChecks.Rows[i]["cTVBatch"].ToString(), -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), -Convert.ToDecimal(dtChecks.Rows[i]["iTVNum"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(),
                                     dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(),
                                     "", key09, "", "", "", "", 0, 0, 0, 0, 0, 0, -Convert.ToDecimal(dtChecks.Rows[i]["iTVQuantity"].ToString()), -Convert.ToDecimal(dtChecks.Rows[i]["iTVNum"].ToString()), iFatherIds, iChildIds);
                            }
                            iChildIds--;
                        }

                        #endregion

                        #endregion

                    }
                    cmd.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    cmd.Transaction.Rollback();
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }

            }
            ResultFlag = true;
            return ResultFlag;

        }


        /// <summary>
        /// 根据调拨申请单创建并审核调出单
        /// </summary>
        /// <param name="Bills"></param>
        /// <returns></returns>
        public Result CreateTransferOut(List<ICSTransferApplyDoc> Bills)
        {
            DataSet ds = new DataSet();

            if (Bills == null || Bills.Count == 0)
            {
                throw new Exception("传入数据为空");
            }

            var res = new Result();
            var datalist = new List<ICSTransferApplyDoc>();

            foreach (var item in Bills)
            {
                try
                {
                    string ORGID = "";
                    long TransOutDocType = 0;
                    string TransOutOrgCode = "";
                    string TransInOrgCode = "";

                    ORGID = Appconfig.IsExistsCode(item.WorkPoint, "Base_Organization");

                    if (string.IsNullOrEmpty(ORGID))
                    {
                        throw new Exception("组织编码：" + item.WorkPoint + "在U9中不存在。");
                    }

                    string usersql = "select ID from Base_User where Code ='" + item.User + "'";
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    if (userdt.Rows.Count == 0)
                    {
                        throw new Exception("用户编码不存在");
                    }

                    string UserID = userdt.Rows[0]["ID"].ToString();


                    #region 获取调拨申请单调入组织及调出组织
                    string docsql = @"  select B.Code AS OutOrgCode,C.Code AS InOrgCode from InvDoc_TransferApply A
                                    LEFT JOIN Base_Organization B ON B.ID=A.TransferOutOrg
                                    LEFT JOIN Base_Organization C ON C.ID=A.TransferInOrg
                                    where A.DocNo='{0}' AND A.Org='{1}'";
                    docsql = string.Format(docsql, item.TACode, ORGID);

                    DataTable docdt = DBhlper.Query(docsql, ERPConStr);
                    if (docdt.Rows.Count == 0)
                    {
                        throw new Exception("调拨申请单不存在，单号：" + item.TACode);
                    }

                    TransOutOrgCode = docdt.Rows[0]["OutOrgCode"].ToString();
                    TransInOrgCode = docdt.Rows[0]["InOrgCode"].ToString();
                    #endregion
                    #region 获取调出单单据类型
                    string sql = @" select ID,Code from InvDoc_TransOutDocType
                                where TransferType=(select TransferType from InvDoc_TransferApply
                                where DocNo='{0}' and Org='{1}')
                                AND Org='{1}'";
                    sql = string.Format(sql, item.TACode, ORGID);
                    DataTable dt = DBhlper.Query(sql, ERPConStr);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("调拨申请单：" + item.TACode + "的调拨类型未在调出单单据类型中查询到相对应的调拨类型，请确认U9配置。");
                    }

                    TransOutDocType = long.Parse(dt.Rows[0]["ID"].ToString());

                    #endregion
                    List<TransferApplyToTransferOutAPIModel> HeadList = new List<TransferApplyToTransferOutAPIModel>();
                    TransferApplyToTransferOutAPIModel Head = new TransferApplyToTransferOutAPIModel();
                    List<TransferApplyLine> LineList = new List<TransferApplyLine>();
                    TransferApplyLine Line = new TransferApplyLine();

                    foreach (ICSTransApplyLine LineInfo in item.details)
                    {
                        bool LineIsSame = false;
                        foreach (TransferApplyToTransferOutAPIModel chkInfo in HeadList)
                        {
                            if (chkInfo.TransApplyLineKey == long.Parse(LineInfo.TADetailID))
                            {
                                LineIsSame = true;
                                Line = new TransferApplyLine();
                                Line.TransOutBusDate = DateTime.Now;
                                Line.TransOutQty = LineInfo.Quantity;
                                Line.TransInWh_Code = LineInfo.INWhCode;
                                Line.TransInOrg_Code = TransInOrgCode;
                                Line.TransOutWh_Code = LineInfo.OutWhCode;
                                Line.TransInBin = 0;
                                Line.TransOutBin = 0;
                                if (!string.IsNullOrEmpty(LineInfo.BatchCode))
                                {
                                    #region 查询批号是否存在，如不存在则创建
                                    string LotID = "";
                                    string sqlLot = @"SELECT ID,InvalidTime,CreatedOn FROM Lot_LotMaster WHERE ItemCode='{0}'  AND LotCode ='{1}'";
                                    sqlLot = string.Format(sqlLot, LineInfo.InvCode, LineInfo.BatchCode);
                                    DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                                    if (dtLot.Rows.Count > 0)
                                    {
                                        if (string.IsNullOrEmpty(dtLot.Rows[0]["InvalidTime"].ToString()))
                                        {
                                            #region 因U9原因创建出的批号失效时间为空，需要更新批号并赋予失效时间
                                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                            string BatchID = dtLot.Rows[0]["ID"].ToString();
                                            string lotWHCode = "";
                                            string lotItemCode = LineInfo.InvCode;
                                            string LotCode = LineInfo.BatchCode;
                                            DateTime EffectiveDatetime = Convert.ToDateTime(dtLot.Rows[0]["CreatedOn"].ToString());
                                            LotMasterCreate.CreateRCVLotMasterSpecial(BatchID, lotWHCode, lotItemCode, LotCode, EffectiveDatetime, ORGID, ref LotID);
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                        string lotWHCode = "";
                                        string lotItemCode = LineInfo.InvCode;
                                        string LotCode = LineInfo.BatchCode;
                                        LotMasterCreate.CustCreateRCVLotMasterPN(lotWHCode, lotItemCode, LotCode, ORGID, ref LotID);
                                    }
                                    #endregion
                                }
                                Line.LotInfo_Code = LineInfo.BatchCode;
                                Line.TransOutBinCode = "";
                                Line.TransInBinCode = "";
                                Line.TransOutDocType = TransOutDocType;
                                Line.DescFlexField = new DescFlexSegments();
                                Line.DescFlexField.PrivateDescSeg30 = LineInfo.LogIds;
                                chkInfo.tptoTransoutDTOS.Add(Line);
                                break;
                            }
                        }
                        if (LineIsSame == true)
                        {
                            continue;
                        }
                        else
                        {
                            Head = new TransferApplyToTransferOutAPIModel();
                            LineList = new List<TransferApplyLine>();
                            Line = new TransferApplyLine();
                            Head.IsApproved = true;
                            Head.DocStatus = 2;
                            Head.TransApplyLineKey = long.Parse(LineInfo.TADetailID);
                            Head.OtherID = "";

                            Line.TransOutBusDate = DateTime.Now;
                            Line.TransOutQty = LineInfo.Quantity;
                            Line.TransInWh_Code = LineInfo.INWhCode;
                            Line.TransInOrg_Code = TransInOrgCode;
                            Line.TransOutWh_Code = LineInfo.OutWhCode;
                            Line.TransInBin = 0;
                            Line.TransOutBin = 0;
                            if (!string.IsNullOrEmpty(LineInfo.BatchCode))
                            {
                                #region 查询批号是否存在，如不存在则创建
                                string LotID = "";
                                string sqlLot = @"SELECT ID,InvalidTime,CreatedOn FROM Lot_LotMaster WHERE ItemCode='{0}'  AND LotCode ='{1}'";
                                sqlLot = string.Format(sqlLot, LineInfo.InvCode, LineInfo.BatchCode);
                                DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                                if (dtLot.Rows.Count > 0)
                                {
                                    if (string.IsNullOrEmpty(dtLot.Rows[0]["InvalidTime"].ToString()))
                                    {
                                        #region 因U9原因创建出的批号失效时间为空，需要更新批号并赋予失效时间
                                        CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                        string BatchID = dtLot.Rows[0]["ID"].ToString();
                                        string lotWHCode = "";
                                        string lotItemCode = LineInfo.InvCode;
                                        string LotCode = LineInfo.BatchCode;
                                        DateTime EffectiveDatetime = Convert.ToDateTime(dtLot.Rows[0]["CreatedOn"].ToString());
                                        LotMasterCreate.CreateRCVLotMasterSpecial(BatchID, lotWHCode, lotItemCode, LotCode, EffectiveDatetime, ORGID, ref LotID);
                                        #endregion
                                    }
                                }
                                else
                                {
                                    CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                                    string lotWHCode = "";
                                    string lotItemCode = LineInfo.InvCode;
                                    string LotCode = LineInfo.BatchCode;
                                    LotMasterCreate.CustCreateRCVLotMasterPN(lotWHCode, lotItemCode, LotCode, ORGID, ref LotID);
                                }
                                #endregion
                            }
                            Line.LotInfo_Code = LineInfo.BatchCode;
                            Line.TransOutBinCode = "";
                            Line.TransInBinCode = "";
                            Line.TransOutDocType = TransOutDocType;
                            Line.DescFlexField = new DescFlexSegments();
                            Line.DescFlexField.PrivateDescSeg30 = LineInfo.LogIds;

                            LineList.Add(Line);
                            Head.tptoTransoutDTOS = LineList;
                            HeadList.Add(Head);
                        }
                    }


                    string postJson = JsonConvert.SerializeObject(HeadList);

                    ApplyToTransferOutReturnValue value = new ApplyToTransferOutReturnValue();
                    value = PostJsonToTransferOut(postJson, item.User, item.WorkPoint, TransOutOrgCode, TransInOrgCode);


                    if (value.IsSuccess == false)
                    {
                        throw new Exception(value.Message);
                    }

                    foreach (ICSTransApplyLine LineInfo in item.details)
                    {
                        string sqlcheck = @"select b.DescFlexSegments_PrivateDescSeg30 from InvDoc_TransferOut a
                            left join InvDoc_TransOutLine b on a.id = b.TransferOut
                            where a.ID ='" + value.ID + "' and b.SrcDocInfo_SrcDocLine_EntityID ='" + LineInfo.TADetailID + "'";
                        DataTable dtcheck = DBhlper.Query(sqlcheck, ERPConStr);
                        if (dtcheck.Rows.Count > 0)
                        {
                            var linelist = new List<ICSTransApplyLine>();
                            foreach (DataRow dr in dtcheck.Rows)
                            {
                                linelist.Add(new ICSTransApplyLine
                                {
                                    TADetailID = LineInfo.TADetailID,
                                    LogIds = dr["DescFlexSegments_PrivateDescSeg30"].ToString()
                                });
                            }

                            datalist.Add(new ICSTransferApplyDoc
                            {
                                TACode = item.TACode,
                                IsSuccess = true,
                                Message = "创建成功",
                                details = linelist
                            });
                        }
                    }



                    #region 查询

                    //sql = @" select DISTINCT a.ID as ID,a.ID as IDs,a.DocNo as TransCode,'' FromDepCode,'' FromDepName,'' FromWHCode,'' FromWHName
                    //        ,'' ToDepCode,'' ToDepName,'' ToWHCode,'' ToWHName
                    //        ,b.SrcDocInfo_SrcDocNo as TACode ,a.CreatedBy as CreateUser ,a.CreatedOn as CreateDateTime
                    //        ,a.ApprovedBy as Checker ,a.ApprovedOn as CheckDateTime 
                    //        from InvDoc_TransferOut a 
                    //        LEFT JOIN InvDoc_TransOutLine b on b.TransferOut=a.ID
                    //        WHERE A.ID IN ({0})";
                    //sql = string.Format(sql, value.ID);
                    //dt = DBhlper.Query(sql, ERPConStr);
                    //ds.Tables.Add(dt);

                    //sql = @" select DISTINCT a.ID as IDs, b.ID as DetailID,b.DocLineNo as Sequence  ,b.ItemInfo_ItemCode as InvCode ,
                    //        b.StoreUOMQty as Quantity ,0 as Amount,b.SrcDocInfo_SrcDocLine_EntityID as TADetailID
                    //        ,d.Code FromDepCode,dd.Name FromDepName,e.Code FromWHCode,ee.Name FromWHName
                    //        ,f.Code ToDepCode,ff.Name ToDepName,g.Code ToWHCode,gg.Name ToWHName
                    //        ,isnull(c.Code,'') ProjectCode,isnull(b.LotInfo_LotCode,'') BatchCode,'' version ,'' brand,
                    //        '' as cFree1,
                    //        '' as cFree2,
                    //        '' as cFree3,
                    //        '' as cFree4,
                    //        '' as cFree5,
                    //        '' as cFree6,
                    //        '' as cFree7,
                    //        '' as cFree8,
                    //        '' as cFree9,
                    //        '' as cFree10,
                    //        '' LogId
                    //        from InvDoc_TransferOut a 
                    //        left join InvDoc_TransOutLine b on b.TransferOut=a.ID
                    //        left join InvDoc_TransOutSubLine bb on bb.TransOutLine=b.ID
                    //        left join CBO_Project c on c.ID=b.Project
                    //        left join CBO_Department d on d.ID=b.TransOutDept
                    //        left join CBO_Department_Trl dd on dd.ID=d.ID
                    //        left join CBO_Wh e on e.ID=b.TransOutWh
                    //        left join CBO_Wh_Trl ee on ee.ID=e.ID
                    //        left join CBO_Department f on f.ID=bb.TransInDept
                    //        left join CBO_Department_Trl ff on ff.ID=f.ID
                    //        left join CBO_Wh g on g.ID=bb.TransInWh
                    //        left join CBO_Wh_Trl gg on gg.ID=g.ID
                    //        WHERE A.ID IN ({0})";
                    //sql = string.Format(sql, value.ID);
                    //dt = DBhlper.Query(sql, ERPConStr);
                    //ds.Tables.Add(dt);

                    #endregion
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSTransApplyLine>();
                    foreach (var d in item.details)
                    {
                        linelist.Add(new ICSTransApplyLine
                        {
                            TADetailID = d.TADetailID,
                            LogIds = d.LogIds
                        });
                    }

                    datalist.Add(new ICSTransferApplyDoc
                    {
                        TACode = item.TACode,
                        IsSuccess = false,
                        Message = "创建失败：" + ex.Message,
                        details = linelist
                    });
                }
            }

            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;

            //string szJson = "";

            //szJson = JSON.DataSetToJson(ds, "details", "IDs");
            //return szJson;

        }

        public static ApplyToTransferOutReturnValue PostJsonToTransferOut(string DataJson, string CreateByCode, string ORGCode, string TransOutOrgCode, string TransInOrgCode)
        {
            ApplyToTransferOutReturnValue valueRet = new ApplyToTransferOutReturnValue();
            try
            {
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/TransferOut/CreateTransOutBySrcTransferApply";
                    CreateUrl = string.Format(CreateUrl, U9IP);

                    Appconfig.WriteLogFile("调拨申请转调出单传入Json：" + DataJson, LogName);

                    string resultCreateSoFile = PostData.APT(CreateUrl, DataJson, TokenCode);

                    Appconfig.WriteLogFile("调拨申请转调出单返回Json：" + resultCreateSoFile, LogName);


                    bool IsSucess = false;
                    List<TransferOutDocInfo> DocInfoList = new List<TransferOutDocInfo>();

                    TransferApplyToTransferOutApiReturnModel RetModel = JsonConvert.DeserializeObject<TransferApplyToTransferOutApiReturnModel>(resultCreateSoFile);
                    if (RetModel.Success == true &&
                        RetModel.Data != null && RetModel.Data.Count > 0)
                    {
                        var IsTrues = RetModel.Data.Where(a => a.IsSucess == false).ToList();
                        if (IsTrues != null && IsTrues.Count() > 0)
                        {
                            #region 部分成功则先删除已生成的调入单，弃审成功的调出单，并一起删除
                            //var SuccessOutDoc = RetModel.Data.Where(a => a.IsSucess == true);
                            //if (SuccessOutDoc.Count() > 0)
                            //{
                            //    List<TransferOutApproveModel> UnApproveDelOutDocList = new List<TransferOutApproveModel>();
                            //    foreach (DataItem successData in SuccessOutDoc)
                            //    {
                            //        TransferOutApproveModel UnApproveDelOutDoc = new TransferOutApproveModel();
                            //        UnApproveDelOutDoc.ID = successData.ID;
                            //        UnApproveDelOutDoc.Code = successData.Code;
                            //        UnApproveDelOutDocList.Add(UnApproveDelOutDoc);
                            //        sqlID += successData.ID.ToString() + ",";
                            //        DocList += successData.Code.ToString() + ",";
                            //    }
                            //    sqlID = sqlID.TrimEnd(',');
                            //    DocList = DocList.TrimEnd(',');
                            //    #region 先查询出已生成的调入单并删除
                            //    List<TransferOutApproveModel> delInDocList = new List<TransferOutApproveModel>();
                            //    string linesql = @" select DISTINCT A.DocNo,A.ID from InvDoc_TransferIn A
                            //                        LEFT JOIN InvDoc_TransInLine B ON B.TransferIn=A.ID
                            //                        WHERE B.SrcDocInfo_SrcDoc_EntityID IN ({0})";
                            //    linesql = string.Format(linesql, sqlID);
                            //    DataTable linedt = DBhlper.Query(linesql, Appconfig.GetU9ConnStr());
                            //    if (linedt.Rows.Count > 0)
                            //    {
                            //        foreach (DataRow dr in linedt.Rows)
                            //        {
                            //            TransferOutApproveModel delInDoc = new TransferOutApproveModel();
                            //            delInDoc.ID = long.Parse(dr["ID"].ToString());
                            //            delInDoc.Code = dr["DocNo"].ToString();
                            //            delInDocList.Add(delInDoc);
                            //        }
                            //        string postDelJson = JsonConvert.SerializeObject(delInDocList);

                            //        TokenCode = GetToken(CreateByCode, ORGCode);

                            //        string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                            //        DelUrl = string.Format(DelUrl, U9IP);
                            //        Appconfig.WriteLogFile("删除调用接口Json：" + postDelJson, LogName);
                            //        string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                            //        Appconfig.WriteLogFile("删除调入单返回Json：" + resultDelFile, LogName);

                            //        JObject objuu4 = JObject.Parse(resultDelFile);


                            //        if (objuu4["Success"] != null && objuu4["Data"] != null && objuu4["Success"].ToString().ToUpper() == "TRUE")
                            //        {
                            //            TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                            //            if (RetModel4.Success == true &&
                            //                RetModel4.Data != null && RetModel4.Data.Count > 0)
                            //            {
                            //                var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false);
                            //                if (IsTrues4 != null && IsTrues4.Count() > 0)
                            //                {
                            //                    Message += RetModel4.Data[0].ErrorMsg;
                            //                }
                            //                else
                            //                {
                            //                    Message += "部分生成的调入单删除成功：";
                            //                }
                            //            }
                            //        }
                            //        else
                            //        {
                            //            Message += "部分生成的调入单删除失败：";
                            //            if (objuu4["Message"] != null && !string.IsNullOrEmpty(objuu4["Message"].ToString()))
                            //            {
                            //                Message += objuu4["Message"].ToString();
                            //            }
                            //            if (objuu4["ResMsg"] != null && !string.IsNullOrEmpty(objuu4["ResMsg"].ToString()))
                            //            {
                            //                Message += objuu4["ResMsg"].ToString();
                            //            }
                            //        }
                            //    }
                            //    #endregion

                            //    #region 弃审并删除调出单
                            //    string postunapproveJson = JsonConvert.SerializeObject(UnApproveDelOutDocList);

                            //    TokenCode = GetToken(CreateByCode, ORGCode);

                            //    string UapproveUrl = "http://{0}/u9c/webapi/TransferOut/UnApprove";
                            //    UapproveUrl = string.Format(UapproveUrl, U9IP);
                            //    Appconfig.WriteLogFile("弃审调用接口Json：" + postunapproveJson, LogName);
                            //    string resultUnapproveFile = PostData.APT(UapproveUrl, postunapproveJson, TokenCode);

                            //    Appconfig.WriteLogFile("弃审调出单返回Json：" + resultUnapproveFile, LogName);

                            //    JObject objuu5 = JObject.Parse(resultUnapproveFile);


                            //    if (objuu5["Success"] != null && objuu5["Data"] != null && objuu5["Success"].ToString().ToUpper() == "TRUE")
                            //    {
                            //        TransferOutApproveReturnModel RetModel5 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultUnapproveFile);
                            //        if (RetModel5.Success == true &&
                            //            RetModel5.Data != null && RetModel5.Data.Count > 0)
                            //        {
                            //            var IsTrues5 = RetModel5.Data.Where(a => a.IsSucess == false);
                            //            if (IsTrues5 != null && IsTrues5.Count() > 0)
                            //            {
                            //                Message += RetModel5.Data[0].ErrorMsg;
                            //            }
                            //            else
                            //            {
                            //                string submitJson = JsonConvert.SerializeObject(UnApproveDelOutDocList);

                            //                TokenCode = GetToken(CreateByCode, ORGCode);

                            //                string submitUrl = "http://{0}/u9c/webapi/TransferOut/Delete";
                            //                submitUrl = string.Format(submitUrl, U9IP);
                            //                Appconfig.WriteLogFile("删除调出单调用接口Json：" + submitJson, LogName);
                            //                string resultsubmitFile = PostData.APT(submitUrl, submitJson, TokenCode);

                            //                Appconfig.WriteLogFile("删除调出单返回Json：" + resultsubmitFile, LogName);

                            //                JObject objuu6 = JObject.Parse(resultsubmitFile);


                            //                if (objuu6["Success"] != null && objuu6["Data"] != null && objuu6["Success"].ToString().ToUpper() == "TRUE")
                            //                {
                            //                    TransferOutApproveReturnModel RetModel6 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultsubmitFile);
                            //                    if (RetModel6.Success == true &&
                            //                        RetModel6.Data != null && RetModel6.Data.Count > 0)
                            //                    {
                            //                        var IsTrues6 = RetModel6.Data.Where(a => a.IsSucess == false);
                            //                        if (IsTrues6 != null && IsTrues6.Count() > 0)
                            //                        {
                            //                            Message += RetModel6.Data[0].ErrorMsg;
                            //                        }
                            //                        else
                            //                        {
                            //                            Message += "删除调出单：" + DocList + "成功";
                            //                        }
                            //                    }
                            //                }
                            //                else
                            //                {
                            //                    Message += "删除调出单：" + DocList + "失败：";
                            //                    if (objuu5["Message"] != null && !string.IsNullOrEmpty(objuu5["Message"].ToString()))
                            //                    {
                            //                        Message += objuu5["Message"].ToString();
                            //                    }
                            //                    if (objuu5["ResMsg"] != null && !string.IsNullOrEmpty(objuu5["ResMsg"].ToString()))
                            //                    {
                            //                        Message += objuu5["ResMsg"].ToString();
                            //                    }
                            //                }
                            //            }
                            //        }
                            //    }
                            //    else
                            //    {
                            //        Message += "弃审调出单：" + DocList + "失败：";
                            //        if (objuu5["Message"] != null && !string.IsNullOrEmpty(objuu5["Message"].ToString()))
                            //        {
                            //            Message += objuu5["Message"].ToString();
                            //        }
                            //        if (objuu5["ResMsg"] != null && !string.IsNullOrEmpty(objuu5["ResMsg"].ToString()))
                            //        {
                            //            Message += objuu5["ResMsg"].ToString();
                            //        }
                            //    }
                            //    #endregion
                            //}
                            #endregion

                            throw new Exception("创建失败：" + RetModel.Data[0].ErrorMsg);

                        }
                        else
                        {
                            try
                            {
                                DocInfoList.Add(new TransferOutDocInfo
                                {
                                    ID = RetModel.Data[0].ID,
                                    DocNo = RetModel.Data[0].Code
                                });


                                #region 查询生成的调入单
                                string linesql = @" select DISTINCT A.DocNo,A.ID from InvDoc_TransferIn A
                                                    LEFT JOIN InvDoc_TransInLine B ON B.TransferIn=A.ID
                                                    WHERE B.SrcDocInfo_SrcDoc_EntityID =" + RetModel.Data[0].ID;
                                DataTable linedt = DBhlper.Query(linesql, Appconfig.GetU9ConnStr());
                                if (linedt.Rows.Count == 0)
                                {
                                    throw new Exception("调出单审核后调入单查询失败，请确认是否配置审核后自动生成调入单");
                                }
                                else
                                {
                                    string TransInDocList = "";
                                    List<TransferOutApproveModel> ListDoc = new List<TransferOutApproveModel>();
                                    foreach (DataRow dr in linedt.Rows)
                                    {
                                        TransInDocList += dr["DocNo"].ToString() + ",";
                                        TransferOutApproveModel subm = new TransferOutApproveModel();
                                        subm.OtherID = "";
                                        subm.ID = long.Parse(dr["ID"].ToString());
                                        subm.Code = dr["DocNo"].ToString();
                                        ListDoc.Add(subm);
                                    }
                                    TransInDocList = TransInDocList.TrimEnd(',');
                                    string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                    string SubmitUrl = "http://{0}/u9c/webapi/TransferIn/Submit";
                                    SubmitUrl = string.Format(SubmitUrl, U9IP);

                                    Appconfig.WriteLogFile("提交调入单调用接口Json：" + postSubmitJson, LogName);
                                    string resultSubmFile = PostData.APT(SubmitUrl, postSubmitJson, TokenCode);

                                    Appconfig.WriteLogFile("提交调入单返回Json：" + resultSubmFile, LogName);


                                    TransferOutApproveReturnModel RetModel2 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultSubmFile);
                                    if (RetModel2.Success == true &&
                                        RetModel2.Data != null && RetModel2.Data.Count > 0)
                                    {
                                        var IsTrues2 = RetModel2.Data.Where(a => a.IsSucess == false);
                                        if (IsTrues2 != null && IsTrues2.Count() > 0)
                                        {
                                            #region 提交失败即删除调入单
                                            List<TransferOutApproveModel> ListDoc4 = new List<TransferOutApproveModel>();
                                            foreach (DataRow dr in linedt.Rows)
                                            {
                                                TransferOutApproveModel delm = new TransferOutApproveModel();
                                                delm.OtherID = "";
                                                delm.ID = long.Parse(dr["ID"].ToString());
                                                delm.Code = dr["DocNo"].ToString();
                                                ListDoc4.Add(delm);
                                            }
                                            string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                            TokenCode = GetToken(CreateByCode, ORGCode);

                                            string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                                            DelUrl = string.Format(DelUrl, U9IP);
                                            Appconfig.WriteLogFile("删除调入单调用接口Json：" + postDelJson, LogName);
                                            string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                            Appconfig.WriteLogFile("删除调入单返回Json：" + resultDelFile, LogName);


                                            TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                                            if (RetModel4.Success == true &&
                                                RetModel4.Data != null && RetModel4.Data.Count > 0)
                                            {
                                                var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false).ToList();
                                                if (IsTrues4 != null && IsTrues4.Count() > 0)
                                                {
                                                    throw new Exception("删除调入单失败：" + RetModel4.Data[0].ErrorMsg + "提交异常：" + RetModel2.Data[0].ErrorMsg);
                                                }
                                                else
                                                {
                                                    throw new Exception("删除调入单成功，提交异常：" + RetModel2.Data[0].ErrorMsg);
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception("删除调入单失败：" + RetModel4.ResMsg + "提交异常：" + RetModel2.Data[0].ErrorMsg);
                                            }

                                            #endregion
                                        }
                                        else
                                        {
                                            #region 审核 调入单
                                            List<TransferOutApproveModel> ListDoc3 = new List<TransferOutApproveModel>();
                                            foreach (DataRow dr in linedt.Rows)
                                            {
                                                TransferOutApproveModel Apprm = new TransferOutApproveModel();
                                                Apprm.OtherID = "";
                                                Apprm.ID = long.Parse(dr["ID"].ToString());
                                                Apprm.Code = dr["DocNo"].ToString();
                                                ListDoc3.Add(Apprm);
                                            }
                                            string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                            TokenCode = GetToken(CreateByCode, ORGCode);

                                            string ApproveUrl = "http://{0}/u9c/webapi/TransferIn/Approve";
                                            ApproveUrl = string.Format(ApproveUrl, U9IP);

                                            Appconfig.WriteLogFile("审核调入单调用接口Json：" + postApproveJson, LogName);
                                            string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);

                                            Appconfig.WriteLogFile("审核调入单返回Json：" + resultappmFile, LogName);


                                            TransferOutApproveReturnModel RetModel3 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultappmFile);
                                            if (RetModel3.Success == true &&
                                                RetModel3.Data != null && RetModel3.Data.Count > 0)
                                            {
                                                var IsTrues3 = RetModel3.Data.Where(a => a.IsSucess == false);
                                                if (IsTrues3 != null && IsTrues3.Count() > 0)
                                                {
                                                    #region 审核失败即删除调入单
                                                    List<TransferOutApproveModel> ListDoc4 = new List<TransferOutApproveModel>();
                                                    foreach (DataRow dr in linedt.Rows)
                                                    {
                                                        TransferOutApproveModel delm = new TransferOutApproveModel();
                                                        delm.OtherID = "";
                                                        delm.ID = long.Parse(dr["ID"].ToString());
                                                        delm.Code = dr["DocNo"].ToString();
                                                        ListDoc4.Add(delm);
                                                    }
                                                    string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                                    string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                                                    DelUrl = string.Format(DelUrl, U9IP);
                                                    Appconfig.WriteLogFile("删除调入单调用接口Json：" + postDelJson, LogName);
                                                    string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                                    Appconfig.WriteLogFile("删除调入单返回Json：" + resultDelFile, LogName);


                                                    TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                                                    if (RetModel4.Success == true &&
                                                        RetModel4.Data != null && RetModel4.Data.Count > 0)
                                                    {
                                                        var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false).ToList();
                                                        if (IsTrues4 != null && IsTrues4.Count() > 0)
                                                        {
                                                            throw new Exception("删除调入单失败：" + RetModel4.Data[0].ErrorMsg + "审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                        }
                                                        else
                                                        {
                                                            throw new Exception("删除调入单成功，审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("删除调入单失败：" + RetModel4.ResMsg + "审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                    }

                                                    #endregion
                                                }
                                                else
                                                {
                                                    IsSucess = true;
                                                    valueRet.IsSuccess = true;
                                                    valueRet.ID = RetModel.Data[0].ID.ToString();
                                                }
                                            }
                                            else
                                            {
                                                #region 审核失败即删除调入单
                                                List<TransferOutApproveModel> ListDoc4 = new List<TransferOutApproveModel>();
                                                foreach (DataRow dr in linedt.Rows)
                                                {
                                                    TransferOutApproveModel delm = new TransferOutApproveModel();
                                                    delm.OtherID = "";
                                                    delm.ID = long.Parse(dr["ID"].ToString());
                                                    delm.Code = dr["DocNo"].ToString();
                                                    ListDoc4.Add(delm);
                                                }
                                                string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                                TokenCode = GetToken(CreateByCode, ORGCode);

                                                string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                                                DelUrl = string.Format(DelUrl, U9IP);
                                                Appconfig.WriteLogFile("删除调入单调用接口Json：" + postDelJson, LogName);
                                                string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                                Appconfig.WriteLogFile("删除调入单返回Json：" + resultDelFile, LogName);


                                                TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                                                if (RetModel4.Success == true &&
                                                    RetModel4.Data != null && RetModel4.Data.Count > 0)
                                                {
                                                    var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false).ToList();
                                                    if (IsTrues4 != null && IsTrues4.Count() > 0)
                                                    {
                                                        throw new Exception("删除调入单失败：" + RetModel4.Data[0].ErrorMsg + "审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("删除调入单成功，审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception("删除调入单失败：" + RetModel4.ResMsg + "审核异常：" + RetModel3.Data[0].ErrorMsg);
                                                }

                                                #endregion
                                            }

                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        #region 提交失败即删除调入单
                                        List<TransferOutApproveModel> ListDoc4 = new List<TransferOutApproveModel>();
                                        foreach (DataRow dr in linedt.Rows)
                                        {
                                            TransferOutApproveModel delm = new TransferOutApproveModel();
                                            delm.OtherID = "";
                                            delm.ID = long.Parse(dr["ID"].ToString());
                                            delm.Code = dr["DocNo"].ToString();
                                            ListDoc4.Add(delm);
                                        }
                                        string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                        TokenCode = GetToken(CreateByCode, ORGCode);

                                        string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                                        DelUrl = string.Format(DelUrl, U9IP);
                                        Appconfig.WriteLogFile("删除调入单调用接口Json：" + postDelJson, LogName);
                                        string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                        Appconfig.WriteLogFile("删除调入单返回Json：" + resultDelFile, LogName);


                                        TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                                        if (RetModel4.Success == true &&
                                            RetModel4.Data != null && RetModel4.Data.Count > 0)
                                        {
                                            var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false).ToList();
                                            if (IsTrues4 != null && IsTrues4.Count() > 0)
                                            {
                                                throw new Exception("删除调入单失败：" + RetModel4.Data[0].ErrorMsg + "提交异常：" + RetModel2.Data[0].ErrorMsg);
                                            }
                                            else
                                            {
                                                throw new Exception("删除调入单成功，提交异常：" + RetModel2.Data[0].ErrorMsg);
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("删除调入单失败：" + RetModel4.ResMsg + "提交异常：" + RetModel2.Data[0].ErrorMsg);
                                        }

                                        #endregion
                                    }
                                }

                                #endregion
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    #region 失败即弃审删除调出单
                                    if (!IsSucess)
                                    {
                                        List<TransferOutApproveModel> ListDoc5 = new List<TransferOutApproveModel>();
                                        foreach (TransferOutDocInfo DocInfo in DocInfoList)
                                        {
                                            TransferOutApproveModel unapprovem = new TransferOutApproveModel();
                                            unapprovem.OtherID = "";
                                            unapprovem.ID = DocInfo.ID;
                                            unapprovem.Code = DocInfo.DocNo;
                                            ListDoc5.Add(unapprovem);
                                        }
                                        string postunapproveJson = JsonConvert.SerializeObject(ListDoc5);

                                        TokenCode = GetToken(CreateByCode, ORGCode);

                                        string UapproveUrl = "http://{0}/u9c/webapi/TransferOut/UnApprove";
                                        UapproveUrl = string.Format(UapproveUrl, U9IP);

                                        Appconfig.WriteLogFile("弃审调出单调用接口Json：" + postunapproveJson, LogName);
                                        string resultUnapproveFile = PostData.APT(UapproveUrl, postunapproveJson, TokenCode);

                                        Appconfig.WriteLogFile("弃审调出单返回Json：" + resultUnapproveFile, LogName);

                                        JObject objuu5 = JObject.Parse(resultUnapproveFile);



                                        TransferOutApproveReturnModel RetModel5 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultUnapproveFile);
                                        if (RetModel5.Success == true &&
                                            RetModel5.Data != null && RetModel5.Data.Count > 0)
                                        {
                                            var IsTrues5 = RetModel5.Data.Where(a => a.IsSucess == false).ToList();
                                            if (IsTrues5 != null && IsTrues5.Count() > 0)
                                            {
                                                throw new Exception("弃审调出单失败：" + RetModel5.Data[0].ErrorMsg);
                                            }
                                            else
                                            {
                                                List<TransferOutDeleteModel> ListDoc6 = new List<TransferOutDeleteModel>();
                                                foreach (TransferOutDocInfo DocInfo in DocInfoList)
                                                {
                                                    TransferOutDeleteModel delTransOutm = new TransferOutDeleteModel();
                                                    delTransOutm.OtherID = "";
                                                    delTransOutm.ID = DocInfo.ID;
                                                    delTransOutm.Code = DocInfo.DocNo;
                                                    delTransOutm.HoldOrReleaseReasonCode = "";
                                                    delTransOutm.CancelResean = "";
                                                    ListDoc6.Add(delTransOutm);
                                                }
                                                string submitJson = JsonConvert.SerializeObject(ListDoc6);

                                                TokenCode = GetToken(CreateByCode, ORGCode);

                                                string submitUrl = "http://{0}/u9c/webapi/TransferOut/Delete";
                                                submitUrl = string.Format(submitUrl, U9IP);
                                                Appconfig.WriteLogFile("删除调出单调用接口Json：" + submitJson, LogName);
                                                string resultsubmitFile = PostData.APT(submitUrl, submitJson, TokenCode);

                                                Appconfig.WriteLogFile("删除调出单返回Json：" + resultsubmitFile, LogName);


                                                TransferOutApproveReturnModel RetModel6 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultsubmitFile);
                                                if (RetModel6.Success == true &&
                                                    RetModel6.Data != null && RetModel6.Data.Count > 0)
                                                {
                                                    var IsTrues6 = RetModel6.Data.Where(a => a.IsSucess == false).ToList();
                                                    if (IsTrues6 != null && IsTrues6.Count() > 0)
                                                    {
                                                        throw new Exception("删除调出单失败：" + RetModel6.Data[0].ErrorMsg);
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("删除调出单成功");
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception("删除调出单失败：" + RetModel6.ResMsg);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("弃审调出单失败：" + RetModel5.ResMsg);
                                        }
                                    }

                                    #endregion
                                }
                                catch (Exception exdelete)
                                {
                                    throw new Exception(exdelete.Message + "， " + ex.Message);
                                }

                            }
                        }
                    }
                    else
                    {
                        throw new Exception("调用OpenAPI创建调出单失败:" + RetModel.ResMsg);

                    }
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                valueRet.ID = "0";
                valueRet.IsSuccess = false;
                valueRet.DocNo = "";
                valueRet.Message = ex.Message;

            }
            return valueRet;
        }

        public static string GetToken(string CreateByCode, string ORGCode)
        {
            if (ConfigurationManager.AppSettings["clientid"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientid"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientid。");
            }
            if (ConfigurationManager.AppSettings["clientsecret"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientsecret"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientsecret。");
            }
            if (ConfigurationManager.AppSettings["U9IP"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["U9IP"].ToString()))
            {
                throw new Exception("请联系管理员，未配置U9IP。");
            }
            if (ConfigurationManager.AppSettings["enterpriseID"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["enterpriseID"].ToString()))
            {
                throw new Exception("请联系管理员，未配置enterpriseID。");
            }

            string clientid = ConfigurationManager.AppSettings["clientid"].ToString();
            string clientsecret = ConfigurationManager.AppSettings["clientsecret"].ToString();
            string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
            string enterpriseID = ConfigurationManager.AppSettings["enterpriseID"].ToString();
            DateTime dateTime = DateTime.Now;
            string url = "http://{2}/u9c/webapi/OAuth2/GetAuthorizeCode?clientid={0}&clientsecret={1}";
            url = string.Format(url, clientid, clientsecret, U9IP);
            string resultuu = PostData.GetInfo("", url);

            Appconfig.WriteLogFile("授权返回Json：" + resultuu, LogName);

            JObject objuu = new JObject();
            objuu = JObject.Parse(resultuu);

            string keyCode = objuu["Data"].ToString();
            if (!string.IsNullOrWhiteSpace(keyCode))
            {
                string ToeknUrl = "http://{4}/u9c/webapi/OAuth2/Login?userCode={0}&entcode={1}&orgcode={2}&code={3}";
                ToeknUrl = string.Format(ToeknUrl, CreateByCode, enterpriseID, ORGCode, keyCode, U9IP);
                string resultToken = PostData.GetInfo("", ToeknUrl);

                Appconfig.WriteLogFile("Token返回Json：" + resultToken, LogName);

                objuu = JObject.Parse(resultToken);
                string TokenCode = objuu["Data"].ToString();
                return TokenCode;
            }
            else
            {
                throw new Exception("获取token失败");
            }


        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSTransferDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSTransferDoc head in Bills)
            {
                HeadList += "\r\n 表头调拨单号：" + head.ID + "，用户：" + head.User + "，站点：" + head.WorkPoint;
                foreach (ICSTransferDoc body in Bills)
                {
                    BodyList += "\r\n 表体主键ID： " + body.ID + "";
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo1(List<ICSTransferApplyDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSTransferApplyDoc head in Bills)
            {
                HeadList += "\r\n 表头调拨申请单号：" + head.TACode + "，用户：" + head.User + "，站点：" + head.WorkPoint;
                foreach (ICSTransApplyLine body in head.details)
                {
                    BodyList += "\r\n 调拨申请单行ID： " + body.TADetailID + "";
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }



    }

}
