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.APICreateOnStoreCheckDoc
{
    public class CreateOnStoreCheckDoc
    {
        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 ActionCreateOnStoreCheckDoc(ICSCreateOnStoreCheckHead infos)
        {
            ThreadContext context;
            DataSet ds = new DataSet();
            try
            {
                string DocNo = "";
                string DocLine = "";
                string _MOCode = string.Empty;
                UFIDACustInvDocCreateOnStoreCheckICreateAndApproveOnStoreChkServiceClient client = new UFIDACustInvDocCreateOnStoreCheckICreateAndApproveOnStoreChkServiceClient();
                MessageBase[] message = null;
                UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputHeadData InputInfo = new UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputHeadData();
                List<UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputLineData> LineInfoList = new List<UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputLineData>();
                UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputLineData InputLineInfo = new UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputLineData();
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos.WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }

                InputInfo.m_invCode = infos.InvCode;
                InputInfo.m_wHCode = infos.WHCode;
                InputInfo.m_org = new UFIDAU9BaseOrganizationOrganizationData();
                InputInfo.m_org.m_iD = long.Parse(OrgID);
                InputInfo.m_org.m_code = infos.WorkPoint;
                foreach (ICSCreateOnStoreCheckBody lineInfo in infos.details)
                {
                    InputLineInfo = new UFIDACustInvDocCreateOnStoreCheckOnStoreChkInputLineData();
                    InputLineInfo.m_chkQty = lineInfo.ChkQty;
                    InputLineInfo.m_batchCode = lineInfo.BatchCode;

                    LineInfoList.Add(InputLineInfo);
                }
                InputInfo.m_onStoreChkLine = LineInfoList.ToArray();
                context = CreateContextObj(OrgID);
                //服务返回结果
                UFIDACustInvDocCreateOnStoreCheckOnStoreChkReturnModelData result;
                //返回异常信息，目前还没有使用此属性
                MessageBase[] returnMsg;
                result = client.Do(context, InputInfo, out returnMsg);
                if (result.m_isSuccess == true)
                {
                    #region 单据创建成功之后修改公有段7/公有段21/公有段35（库位7，供应商21,汇总信息35）
                    string updatesql = "";
                    foreach (ICSCreateOnStoreCheckBody lineInfo in infos.details)
                    {
                        updatesql += @" update A SET A.DescFlexSegments_PubDescSeg7='{0}',A.DescFlexSegments_PubDescSeg21='{4}',A.DescFlexSegments_PubDescSeg35='{5}'
                                        FROM InvDoc_OnStoreCheckL A
                                        LEFT JOIN InvDoc_OnStoreCheck B ON B.ID=A.OnStoreCheck
                                        WHERE B.DocNo='{1}' AND B.Org='{2}' AND A.LotInfo_LotCode='{3}'";
                        updatesql = string.Format(updatesql, lineInfo.BinCode, result.m_docNo, OrgID, lineInfo.BatchCode, lineInfo.SupplierName, lineInfo.Memo);
                    }
                    DBhlper.EXecute(updatesql, connString);
                    #endregion
                    return "在库检验申请单创建成功";
                }
                else
                {
                    throw new Exception(result.m_message);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                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; }
        }

    }


}
