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.Exceptions;
using ICS.CreateLotMaster;

namespace ICSSoft.APIModifyPMIssueDoc
{
    public class ModifyPMIssueDoc
    {
        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 ActionModifyPMIssueDoc(List<ICSPMIssueDocUpdateHead> infos)
        {
            ThreadContext context;
            DataSet ds = new DataSet();
            try
            {
                string DocNo = "";
                string DocLine = "";
                string _MOCode = string.Empty;
                UFIDAU9CustDocIModifyAndApproveIPMIssueDocModifyAndApproveServiceClient client = new UFIDAU9CustDocIModifyAndApproveIPMIssueDocModifyAndApproveServiceClient();
                UFSoft.UBF.Exceptions.MessageBase[] message = null;
                UFIDAU9CustDocIModifyAndApprovePMIssueModifyInputHeadData InputInfo = new UFIDAU9CustDocIModifyAndApprovePMIssueModifyInputHeadData();
                List<UFIDAU9CustDocIModifyAndApprovePMIssuedocModifyInputLineData> LineInfoList = new List<UFIDAU9CustDocIModifyAndApprovePMIssuedocModifyInputLineData>();
                UFIDAU9CustDocIModifyAndApprovePMIssuedocModifyInputLineData InputLineInfo = new UFIDAU9CustDocIModifyAndApprovePMIssuedocModifyInputLineData();
                string OrgID = "";
                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_pMIssueDocNo = 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 (ICSPMIssueDocUpdateBody lineInfo in infos[0].details)
                {
                    #region 验证出库仓库是否打开了批号管控
                    bool whIsLot = false;
                    string whsql = @"select IsLot from CBO_Wh
                                     where Code='{0}' AND Org='{1}'";
                    whsql = string.Format(whsql, lineInfo.WHCode, OrgID);
                    DataTable whdt = DBhlper.Query(whsql, connString);
                    if (whdt.Rows.Count > 0)
                    {
                        whIsLot = Convert.ToBoolean(whdt.Rows[0]["IsLot"]);
                    }
                    #endregion
                    InputLineInfo = new UFIDAU9CustDocIModifyAndApprovePMIssuedocModifyInputLineData();
                    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_pMIssueDocLineNo = int.Parse(lineInfo.Sequence);
                    InputLineInfo.m_pMIssueInvCode = lineInfo.InvCode;
                    InputLineInfo.m_pMIssueQty = lineInfo.Quantity;
                    if (lineInfo.BatchCode != "" && whIsLot == true)
                    {
                        //获取批号
                        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.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_pMIssueDocLine = LineInfoList.ToArray();
                context = CreateContextObj(OrgID);
                //服务返回结果
                UFIDAU9CustDocIModifyAndApprovePMIssueDocModifyReturnModelData result;
                //返回异常信息，目前还没有使用此属性
                UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                result = client.Do(context, InputInfo, out returnMsg);
                if (result.m_isSuccess == true)
                {
                    #region 查询
                    string sql = "";
                    sql = @" select DISTINCT a.ID as ID,a.ID as IDs,a.DocNo as SourceCode ,
                            a.DocNo as IssueCode,'' AS cDepCode,'' as cDepName,'' WHCode,'' WHName,
                            a.CreatedBy as CreateUser,a.CreatedOn as CreateDateTime,
                            a.ApproveBy as Checker,a.ApproveOn as CheckDateTime
                            from PM_IssueDoc a
                            WHERE a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_docNo, OrgID);
                    DataTable dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);

                    sql = @"select DISTINCT a.ID as IDs,b.ID as DetailID,b.LineNum as Sequence,c.Code as InvCode 
                                ,b.IssuedQty as Quantity,b.SourceDoc_SrcDocLine_EntityID as SourceDetailID,0 as Amount
                                ,d.Code as cDepCode,dd.Name as cDepName,e.Code as WHCode,ee.Name as WHName
                                ,isnull(f.Code,'') ProjectCode,isnull(g.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 PM_IssueDoc a
                                left join PM_IssueDocLine b on b.PMIssueDoc=a.ID
                                left join CBO_ItemMaster c on c.ID=b.Item
                                left join CBO_Department d on d.ID=b.IssueDept
                                left join CBO_Department_Trl dd on dd.ID=d.ID
                                left join CBO_Wh e on e.ID=b.Wh
                                left join CBO_Wh_Trl ee on ee.ID=e.ID
                                left join CBO_Project f on f.ID=b.Project
                                left join Lot_LotMaster g on g.ID=b.LotMaster
                                WHERE a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_docNo, OrgID);
                    dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);
                    #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;
        }

        /// <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; }
        }

    }


}
