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

namespace ICSSoft.APIModifySMShipmement
{
    public class ModifySMShipmement
    {
        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 LogName = "修改并审核标准出货单";
        /// <summary>
        /// 修改并审核标准出货单
        /// </summary>
        /// <returns></returns>
        /// 
        public string ActionModifyShipmement(List<ICSShipmentUpdateHead> infos)
        {
            ThreadContext context;
            DataSet ds = new DataSet();
            try
            {
                string DocNo = "";
                string DocLine = "";
                string _MOCode = string.Empty;
                UFIDAU9CustDocIModifyAndApproveISMShipModifyAndApproveServiceClient client = new UFIDAU9CustDocIModifyAndApproveISMShipModifyAndApproveServiceClient();
                MessageBase[] message = null;
                UFIDAU9CustDocIModifyAndApproveSMShipModifyInputHeadData InputInfo = new UFIDAU9CustDocIModifyAndApproveSMShipModifyInputHeadData();
                List<UFIDAU9CustDocIModifyAndApproveSMShipModifyInputLineData> LineInfoList = new List<UFIDAU9CustDocIModifyAndApproveSMShipModifyInputLineData>();
                UFIDAU9CustDocIModifyAndApproveSMShipModifyInputLineData InputLineInfo = new UFIDAU9CustDocIModifyAndApproveSMShipModifyInputLineData();
                string OrgID = "";
                string Updatesql = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }

                InputInfo.m_shipDocNo = infos[0].DocNo;
                InputInfo.m_org = new UFIDAU9BaseOrganizationOrganizationData();
                InputInfo.m_org.m_iD = long.Parse(OrgID);
                InputInfo.m_org.m_code = infos[0].WorkPoint;
                foreach (ICSShipmentUpdateBody lineInfo in infos[0].details)
                {
                    InputLineInfo = new UFIDAU9CustDocIModifyAndApproveSMShipModifyInputLineData();
                    if (DocNo == "")
                    {
                        DocNo = infos[0].DocNo;
                        DocLine = lineInfo.Sequence;
                    }
                    else
                    {
                        if (DocNo == infos[0].DocNo && DocLine == lineInfo.Sequence)
                        {
                            InputLineInfo.m_isNeedSplit = true;
                        }
                        else
                        {
                            InputLineInfo.m_isNeedSplit = false;
                            DocNo = infos[0].DocNo;
                            DocLine = lineInfo.Sequence;
                        }
                    }
                    InputLineInfo.m_shipLineNo = int.Parse(lineInfo.Sequence);
                    InputLineInfo.m_shipInvCode = lineInfo.InvCode;
                    InputLineInfo.m_shipQty = lineInfo.Quantity;
                    if (lineInfo.BatchCode != "")
                    {
                        //获取批号
                        string lotsql = @"  select ID from Lot_LotMaster
                                    WHERE LotCode='{0}' AND ItemCode='{1}'";
                        lotsql = string.Format(lotsql, lineInfo.BatchCode, lineInfo.InvCode);
                        DataTable lotdt = DBhlper.Query(lotsql, connString);
                        if (lotdt.Rows.Count == 0)
                        {
                            throw new Exception("传入料号：" + lineInfo.InvCode + "对应出库批号:" + lineInfo.BatchCode + "在U9不存在!");
                        }
                        else
                        {
                            InputLineInfo.m_batchID = long.Parse(lotdt.Rows[0]["ID"].ToString());
                            InputLineInfo.m_batchCode = lineInfo.BatchCode;
                        }
                    }
                    else
                    {
                        InputLineInfo.m_batchID = 0;
                        InputLineInfo.m_batchCode = "";
                    }
                    LineInfoList.Add(InputLineInfo);
                }
                InputInfo.m_shipLineInfo = LineInfoList.ToArray();
                context = CreateContextObj(OrgID);
                //服务返回结果
                UFIDAU9CustDocIModifyAndApproveSMShipModifyReturnModelData result;
                //返回异常信息，目前还没有使用此属性
                MessageBase[] returnMsg;
                result = client.Do(context, InputInfo, out returnMsg);
                if (result.m_isSuccess == true)
                {
                    #region 查询
                    string sql = "";
                    sql = @" select top 1 a.ID as ID, a.ID as IDs,a.DocNo as SSDCode,c.Code as CusCode,
                             d.Name as CusName,'' as WHCode,'' as WHName,
                             a.CreatedBy as CreateUser ,a.CreatedOn as CreateDateTime ,a.ApproveMan as Checker ,
                             a.ApproveDate as CheckDateTime 
                             from SM_Ship a 
                             left join SM_ShipLine b on b.Ship=a.ID
                             left join CBO_Customer  c on c.ID=a.OrderBy_Customer
                             left join CBO_Customer_Trl d on d.ID=c.ID
                             WHERE 1=1 and a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_shipDocNo, OrgID);
                    DataTable dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);

                    sql = @"select distinct a.ID as IDs,b.ID as DetailID,b.DocLineNo as Sequence,C.Code as InvCode ,b.ShipQtyTUAmount as Quantity ,
                            0 as Amount,D.ID as  SDNDetailID,G.Code as WHCode,H.Name as WHName
                            ,isnull(E.Code,'') ProjectCode,isnull(F.LotCode,'') cBatch,'' version ,'' brand,
                            '' as cFree1,
                            '' as cFree2,
                            '' as cFree3,
                            '' as cFree4,
                            '' as cFree5,
                            '' as cFree6,
                            '' as cFree7,
                            '' as cFree8,
                            '' as cFree9,
                            '' as cFree10,
                            '' as LogId
                            from SM_Ship a 
                            inner join SM_ShipLine b on b.Ship=a.ID
                            LEFT JOIN CBO_ItemMaster C ON C.ID=B.ItemInfo_ItemID
                            LEFT JOIN SM_SOLine D ON D.ID=B.SOLineKey
                            LEFT JOIN CBO_Project E ON E.ID=B.Project
                            LEFT JOIN Lot_LotMaster F ON F.ID=B.LotInfo_LotMaster
                            LEFT JOIN CBO_Wh G ON G.ID=B.WH
                            LEFT JOIN CBO_Wh_Trl H ON H.ID=G.ID
                            WHERE 1=1 and a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_shipDocNo, OrgID);
                    dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);
                    //审核成功后根据单据行拆分情况更新私有段3
                    foreach (DataRow dr in dt.Rows)
                    {
                        Updatesql += @" update SM_ShipLine set DescFlexField_PrivateDescSeg3=ShipQtyTUAmount
										where ID='{0}'";
                        Updatesql = string.Format(Updatesql, dr["DetailID"].ToString());
                    }
                    DBhlper.EXecute(Updatesql, connString);
                    #endregion
                }
                else
                {
                    throw new Exception(result.m_message);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            string szJson = JSON.DataSetToJson(ds, "details", "IDs");
            return szJson;
        }
        //更新发货单行私有段3（派纳逻辑---私有段3为WMS已发货数量）
        public string UpdateSMShipPrivateDescSeg(List<ICSShipmentUpdateHead> infos)
        {
            try
            {
                string OrgID = "";
                string Updatesql = "";
                string sql = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                foreach (ICSShipmentUpdateBody lineInfo in infos[0].details)
                {
                    Updatesql += @" update Line
                                    SET LINE.DescFlexField_PrivateDescSeg3 = Case When LINE.DescFlexField_PrivateDescSeg3='' 
                                    Then '{3}' else LINE.DescFlexField_PrivateDescSeg3+Convert(decimal(18,6),'{3}') END
                                    FROM SM_ShipLine Line
                                    LEFT JOIN SM_Ship Head ON Head.ID=Line.Ship
									where Head.DocNo='{0}' and Line.DocLineNo='{1}' and Head.Org='{2}'
                                  ";
                    Updatesql = string.Format(Updatesql, infos[0].DocNo, lineInfo.Sequence, OrgID, lineInfo.Quantity);
                }
                DBhlper.EXecute(Updatesql, connString);
                return "私有段修改成功";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 创建上下文
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", 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());
            ns.Add("acttype", ConfigurationManager.AppSettings["acttype"].ToString());
            thContext.nameValueHas = ns;

            return thContext;

            return thContext;
        }

        public class rtnMaterialDeliveryInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

        #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

        public class APIreturnInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }

    }


}
