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;

namespace ICSSoft.APIApproveRCV
{
    public class ApproveRCV
    {
        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"];

        public bool Approve(List<ICSPurchaseReceiveDoc> infos)
        {
            bool ResultFlag = false;
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            string sql = string.Empty;

            foreach (ICSPurchaseReceiveDoc Info in infos)
            {
                try
                {
                    long DocID = 0;
                    string EntityType = "";
                    Decimal RCVQty = 0;
                    //实例化代理类 
                    UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
                    //服务返回结果
                    //UFIDAU9PMPOPurchaseOrderData[] returnItems;
                    //返回异常信息,目前还没有使用此属性
                    UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                    //上下文信息
                    object context;
                    //传入 参数
                    //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
                    UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, Info.WorkPoint);
                    DataTable orgdt = DBHelper.Query(orgsql, connString);
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }
                    DataTable dt = GetData(Info.DNCode, OrgID);
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        EntityType = dt.Rows[0][1].ToString();
                        RCVQty= Convert.ToDecimal(dt.Rows[0][3].ToString());
                        decimal ACTQty = 0;
                        foreach (ICSPurchaseReceiveDocs InfoLine in Info.details)
                        {
                            ACTQty += InfoLine.Quantity;
                        }
                        if (RCVQty != ACTQty)
                        {
                            throw new Exception("实际入库数量未满足收货单数量,请整单入库!");
                        }
                    }
                    else
                    {
                        throw new Exception("传入的单据号不正确!");
                    }
                    int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                    //给上下文信息赋值
                    context = CreateContextObj(OrgID);
                    //给传入参数赋值
                    docHead.EntityType = EntityType;
                    docHead.ID = DocID;

                    //pOList = SetPoDtos(U9Info, poInfoList);
                    //服务调用
                    (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                    (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                    returnMsg = client.Do(context, acttype, docHead);
                    if (returnMsg != null)
                    {
                        if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                        {
                            throw new Exception(returnMsg[0].localMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
            }
            ResultFlag = true;
            return ResultFlag;
        }

        public bool Approve(List<ICSSalesShipmentDocNegative> infos)
        {
            bool ResultFlag = false;
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            string sql = string.Empty;

            foreach (ICSSalesShipmentDocNegative Info in infos)
            {
                try
                {
                    long DocID = 0;
                    string EntityType = "";
                    //实例化代理类 
                    UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
                    //服务返回结果
                    //UFIDAU9PMPOPurchaseOrderData[] returnItems;
                    //返回异常信息,目前还没有使用此属性
                    UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                    //上下文信息
                    object context;
                    //传入 参数
                    //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
                    UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, Info.WorkPoint);
                    DataTable orgdt = DBHelper.Query(orgsql, connString);
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }
                    DataTable dt = GetData(Info.SDNNEGCode, OrgID);
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        EntityType = dt.Rows[0][1].ToString();
                    }
                    else
                    {
                        throw new Exception("传入的单据号不正确!");
                    }
                    int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                    //给上下文信息赋值
                    context = CreateContextObj(OrgID);
                    //给传入参数赋值
                    docHead.EntityType = EntityType;
                    docHead.ID = DocID;

                    //pOList = SetPoDtos(U9Info, poInfoList);
                    //服务调用
                    (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                    (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                    returnMsg = client.Do(context, acttype, docHead);
                    if (returnMsg != null)
                    {
                        if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                        {
                            throw new Exception(returnMsg[0].localMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
            }
            ResultFlag = true;
            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

        private static DataTable GetData(string DocCode, string OrgID)
        {
            string sql = @" select  A.ID,A1.[Code] as [Receivement_RcvDocType_Code],A.Status,SUM(A3.RcvQtyCU) AS RcvQtyCU
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
							left join [PM_RcvLine] A3 ON A3.Receivement=A.ID
                            where A.DocNo='" + DocCode + "' AND A.Org='" + OrgID + @"'
                            GROUP BY A.ID,A1.[Code],A.Status";
            return DBHelper.Query(sql, connString);
        }
    }
}