using ICSSoft.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Entity;
using UFSoft.UBF.Util.Context;
using System.ServiceModel;
using www.ufida.org.EntityData;
using UFSoft.UBF.Exceptions1;

namespace ICSSoft.APIApproveIssue
{
    public class ApproveIssue
    {
        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"];
        /// <summary>
        /// 审核领料单(外部通过API调用)
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public bool Approve(List<ICSRdrecord11> infos)
        {
            bool ResultFlag = false;
            ThreadContext context;
            try
            {
                StringBuilder strHead = new StringBuilder();
                string _MOCode = string.Empty;
                UFIDAU9ISVMOIApproveIssueDoc4ExternalSrvClient client = new UFIDAU9ISVMOIApproveIssueDoc4ExternalSrvClient();
                MessageBase[] message = null;
                List<UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData> LLlist = new List<UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData>();
                UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData LL = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData();
                UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData[] resultList = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData[] { };
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBHelper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                foreach (ICSRdrecord11 info in infos)
                {
                    string checksql = @"select * from MO_IssueDoc
                                        where DocNo='" + info.IssueCode + "' AND Org='" + OrgID + "'";
                    checksql = string.Format(checksql);
                    DataTable dtcheck = DBHelper.Query(checksql, connString);
                    if (dtcheck.Rows.Count == 0)
                    {
                        throw new Exception("领料单号:'" + info.IssueCode + "'不存在!!");
                    }
                    else
                    {
                        LL = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData();
                        LL.m_docNo = info.IssueCode;
                        LL.m_operateType = true;
                        LLlist.Add(LL);
                    }
                }
                context = CreateContextObj(OrgID);
                resultList = client.Do(out message, context, LLlist.ToArray(), false, false);
                if (resultList != null && resultList.Count() > 0)
                {
                    foreach (var item in resultList)
                    {
                        if (item.m_isSucceed == false)
                        {
                            throw new Exception(item.m_errorMsg);
                        }
                    }
                    ResultFlag = true;
                }
                else
                {
                    ResultFlag = true;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            return ResultFlag;
        }
        /// <summary>
        /// 审核领料单(接口内部调用,如:创建退料单后调用审核单据)
        /// </summary>
        /// <param name="DocNOList"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public bool Approve(List<string> DocNOList,string OrgCode)
        {
            bool ResultFlag = false;
            ThreadContext context;
            try
            {
                StringBuilder strHead = new StringBuilder();
                string _MOCode = string.Empty;
                UFIDAU9ISVMOIApproveIssueDoc4ExternalSrvClient client = new UFIDAU9ISVMOIApproveIssueDoc4ExternalSrvClient();
                MessageBase[] message = null;
                List<UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData> LLlist = new List<UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData>();
                UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData LL = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData();
                UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData[] resultList = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData[] { };
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                orgsql = string.Format(orgsql, OrgCode);
                DataTable orgdt = DBHelper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                foreach (string DocNO in DocNOList)
                {
                    string checksql = @"select * from MO_IssueDoc
                                        where DocNo='" + DocNO + "' AND Org='" + OrgID + "'";
                    checksql = string.Format(checksql);
                    DataTable dtcheck = DBHelper.Query(checksql, connString);
                    if (dtcheck.Rows.Count == 0)
                    {
                        throw new Exception("领料单号:'" + DocNO + "'不存在!!");
                    }
                    else
                    {
                        LL = new UFIDAU9ISVMOApproveIssueDoc4ExternalDTOData();
                        LL.m_docNo = DocNO;
                        LL.m_operateType = true;
                        LLlist.Add(LL);
                    }
                }
                context = CreateContextObj(OrgID);
                resultList = client.Do(out message, context, LLlist.ToArray(), false, false);
                if (resultList != null && resultList.Count() > 0)
                {
                    foreach (var item in resultList)
                    {
                        if (item.m_isSucceed == false)
                        {
                            throw new Exception(item.m_errorMsg);
                        }
                    }
                    ResultFlag = true;
                }
                else
                {
                    ResultFlag = true;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            return ResultFlag;
        }
        #region 给上下文信息赋值
        /// <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());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion
    }
}