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.Exceptions;

namespace ICSSoft.APIApproveShipment
{
    public class ApproveShipment
    {
        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<ICSSalesShipmentDoc> infos)
        {
            bool ResultFlag = false;
            UFIDAU9ISVSMIAuditShipSVClient client = new UFIDAU9ISVSMIAuditShipSVClient();
            //返回异常信息,目前还没有使用此属性
            MessageBase[] returnMsg;
            //上下文信息
            object context;
            try
            {
                if (infos == null || infos.Count == 0)
                {
                    throw new Exception("传入数据不能为空!");
                }
                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("传入组织编码错误!");
                }
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                UFIDAU9ISVSMDocKeyDTOData[] shipKeys = new UFIDAU9ISVSMDocKeyDTOData[] { };
                List<UFIDAU9ISVSMDocKeyDTOData> _shipKeys = new List<UFIDAU9ISVSMDocKeyDTOData>();
                UFIDAU9ISVSMDocKeyDTOData shipkey = new UFIDAU9ISVSMDocKeyDTOData();


                bool isSubmit = false;
                bool isUnApprove = false;
                bool isSubmitAndApprove = false;
                UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData[] itemBarCodes = new UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData[] { };
                foreach (ICSSalesShipmentDoc Info in infos)
                {
                    shipkey = new UFIDAU9ISVSMDocKeyDTOData();
                    shipkey.m_docNO = Info.SDNCode;
                    _shipKeys.Add(shipkey);
                }
                shipKeys = _shipKeys.ToArray();
                returnMsg = client.Do(context, shipKeys, isSubmit, isSubmitAndApprove, isUnApprove, itemBarCodes);


                if (returnMsg != null && returnMsg.Length > 0)
                {
                    foreach (var item in returnMsg)
                    {
                        throw new Exception(item.localMessage);
                    }
                }
                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;
            UFIDAU9ISVSMIAuditShipSVClient client = new UFIDAU9ISVSMIAuditShipSVClient();
            //返回异常信息,目前还没有使用此属性
            MessageBase[] returnMsg;
            //上下文信息
            object context;
            try
            {
                if (DocNOList == null || DocNOList.Count == 0)
                {
                    throw new Exception("传入数据不能为空!");
                }
                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("传入组织编码错误!");
                }
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                UFIDAU9ISVSMDocKeyDTOData[] shipKeys = new UFIDAU9ISVSMDocKeyDTOData[] { };
                List<UFIDAU9ISVSMDocKeyDTOData> _shipKeys = new List<UFIDAU9ISVSMDocKeyDTOData>();
                UFIDAU9ISVSMDocKeyDTOData shipkey = new UFIDAU9ISVSMDocKeyDTOData();


                bool isSubmit = false;
                bool isUnApprove = false;
                bool isSubmitAndApprove = false;
                UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData[] itemBarCodes = new UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData[] { };
                foreach (string DocNO in DocNOList)
                {
                    shipkey = new UFIDAU9ISVSMDocKeyDTOData();
                    shipkey.m_docNO = DocNO;
                    _shipKeys.Add(shipkey);
                }
                shipKeys = _shipKeys.ToArray();
                returnMsg = client.Do(context, shipKeys, isSubmit, isSubmitAndApprove, isUnApprove, itemBarCodes);


                if (returnMsg != null && returnMsg.Length > 0)
                {
                    foreach (var item in returnMsg)
                    {
                        throw new Exception(item.localMessage);
                    }
                }
                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
    }
}