using ICS.WCF.Base;
using ICSSoft.Entity;
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.Exceptions;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.ATWApproveFCTMatrialPick
{
    public class ATWFCTMatrialPick
    {
        /// <summary>
        /// 外部API接口调用，用于直接审核U9的非成套领料单
        /// </summary>
        /// <param name="Bills"></param>
        /// <returns></returns>
        public bool CustLLState(List<ICSMOIssueDocApprove> Bills)
        {
            bool IsSuccess = false;
            string MESSAGE = "";
            bool flag = false;
            string returnCode = "";
            try
            {
                UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient client = new UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient();

                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] resultList = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] { };
                List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData> modelList = new List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData>();
                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData model = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData();

                MessageBase[] messageBase = null;
                object _context;
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                      where Code='{0}' ";
                orgsql = string.Format(orgsql, Bills[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count == 0)
                {
                    throw new Exception("传入组织编码:" + Bills[0].WorkPoint + "不存在!");
                }
                else
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                _context = GetLLStateContext(OrgID);
                bool isNotNewTransaction = true;
                foreach (ICSMOIssueDocApprove DocInfo in Bills)
                {
                    if (DocInfo.ID == "")
                    {
                        throw new Exception("传入非成套领料单ID为空，无法审核!");
                    }
                    string sql = @"select DocNo from PM_IssueDoc
                                   where ID='{0}'";
                    sql = string.Format(sql, DocInfo.ID);
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("传入非成套领料单ID:" + DocInfo.ID + "无法查找到对应领料单，请确认单据是否存在!");
                    }
                    model.m_docNo = dt.Rows[0]["DocNo"].ToString();
                    model.m_operateType = true;
                    model.m_isSucceed = true;
                    modelList.Add(model);
                }

                resultList = client.Do(out messageBase, _context, modelList.ToArray());
                foreach (UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData result in resultList)
                {
                    if (result.m_isSucceed == false)
                    {
                        throw new Exception(result.m_errorMsg);
                    }
                }
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("审核委外发料单");
                str.AppendLine("错误:" + MESSAGE);
                str.AppendLine("单号:" + returnCode);
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "审核委外发料单");

                throw new Exception(ex.Message);
            }
            return true;
        }
        /// <summary>
        /// 接口内部调用，用于创建非成套领料单后的审核
        /// </summary>
        /// <param name="LLCodeList"></param>
        /// <param name="OrgID"></param>
        /// <returns></returns>
        public OperationResult CustLLState(List<string> LLCodeList, string OrgID)
        {
            OperationResult result = new OperationResult();
            bool IsSuccess = false;
            string MESSAGE = "";
            bool flag = false;
            string returnCode = "";
            try
            {
                UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient client = new UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient();

                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] resultList = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] { };
                List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData> modelList = new List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData>();
                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData model = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData();

                MessageBase[] messageBase = null;
                object _context;
                _context = GetLLStateContext(OrgID);
                bool isNotNewTransaction = true;
                if (LLCodeList.Count() == 0)
                {
                    IsSuccess = false;
                    result.Message = "发料单为空!";
                    return result;
                }
                foreach (string LLCode in LLCodeList)
                {
                    model.m_docNo = LLCode;
                    model.m_operateType = true;
                    model.m_isSucceed = true;

                    //string sqlUpdate = "UPDATE dbo.PM_IssueDoc SET BusinessCreatedOn=GETDATE() WHERE DocNo='" + LLCode + "'";
                    //DBhlper.EXecute(sqlUpdate, Appconfig.GetU9ConnStr());
                }

                modelList.Add(model);
                resultList = modelList.ToArray();

                resultList = client.Do(out messageBase, _context, resultList);
                if (resultList != null && resultList.Count() > 0)
                {
                    StringBuilder str = new StringBuilder();
                    foreach (var item in resultList)
                    {
                        result.DocNo = item.m_docNo;
                        result.Message = item.m_errorMsg;
                        result.IsSuccess = item.m_isSucceed;
                        str.AppendLine("审核委外发料单：");
                        str.AppendLine("单号：" + item.m_docNo);
                        str.AppendLine("返回错误信息：" + item.m_errorMsg);
                    }
                    Appconfig.WriteLogFile(str.ToString(), "审核委外发料单");
                }
                else
                {
                    result.Message = "审核成功";
                    result.IsSuccess = true;
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = MESSAGE = GetExceptionMessage(ex);
                result.DocNo = returnCode;

                StringBuilder str = new StringBuilder();
                str.AppendLine("审核委外发料单");
                str.AppendLine("错误:" + MESSAGE);
                str.AppendLine("单号:" + returnCode);
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "审核委外发料单");
            }
            return result;
        }


        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private ThreadContext GetLLStateContext(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());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion


        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private 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 OperationResult
        {

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

    }
}
