using ICS.WCF.Base;
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;

namespace UFIDA.ISV.BFPMRecedeApprove
{
    public class CustApproveBFPMRecede
    {
        /// <summary>
        /// 审核领料单
        /// </summary>
        /// <returns></returns>
        /// 
        public OperationResult CustBFPMRecedeApprove(List<string> DocCodeList, string OrgID, string Status)
        {
            OperationResult result = new OperationResult();
            ThreadContext context;
            www.ufida.org.EntityData.UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] returnMsg;
            UFSoft.UBF.Exceptions.MessageBase1[] outMessages;
            try
            {
                string _MOCode = string.Empty;
                UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient client = new UFIDAU9ISVPMIssueIApprovePMIssueDoc4ExternalSrvClient();
                //MessageBase[] message = null;
                List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData> Doclist = new List<UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData>();
                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData DocNo = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData();
                UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] DocArray = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData[] { };
                if (DocCodeList != null && DocCodeList.Count != 0)
                {
                    foreach (string Code in DocCodeList)
                    {
                        if (Code=="")
                            continue;
                       string checksql = @"select * from PM_IssueDoc
                                            where DocNo='" + Code + "' AND Org='" + OrgID + "'";
                        checksql = string.Format(checksql);
                        DataTable dtcheck = DBhlper.Query(checksql, Appconfig.GetU9ConnStr());
                        if (dtcheck.Rows.Count == 0)
                        {
                            result.MESSAGE = "退料单号:'" + Code + "'不存在!";
                            result.IsSuccess = false;
                          return result;
                        }       
                        else
                        {
                            DocNo = new UFIDAU9ISVPMIssueApprovePMIssueDoc4ExternalDTOData();
                            DocNo.m_docNo = Code;
                            if (Status == "审核")
                            {
                                DocNo.m_operateType = true;
                            }
                            else
                            {
                                DocNo.m_operateType = false;
                            }
                            Doclist.Add(DocNo);
                        }
                    }
                    DocArray = Doclist.ToArray();
                }
                else
                {
                    result.MESSAGE = "传入数据不能为空!";
                    result.IsSuccess = false;
                    return result;
                }

                context = CreateContextObj(OrgID);
                returnMsg = client.Do(out outMessages, context, DocArray.ToArray());
                if (returnMsg != null && returnMsg.Count() > 0)
                {
                    StringBuilder str = new StringBuilder();
                    foreach (var item in returnMsg)
                    {
                        result.LLCode = 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)
            {
                string Message = GetExceptionMessage(ex);
                result.IsSuccess = false;
                result.MESSAGE += Message;
            }
            return result;
        }


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


        #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 OperationResult
        {
            /// <summary>
            /// 结果状态,默认值false
            /// </summary>
            public bool IsSuccess { get; set; }

            /// <summary>
            ///处理消息
            /// </summary>
            public string MESSAGE { get; set; }

            /// <summary>
            /// 输出领料订单
            /// </summary>
            public string LLCode { get; set; }
        }

    }


}
