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

namespace ICSSoft.APIDeleteCompRpt
{
    public class DeleteCompRpt
    {
        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 Delete(List<ICSManufactureReceiveDoc> infos)
        {
            bool ResultFlag = false;
            try
            {
                UFIDAU9ISVMOIDeleteCompRptSrvClient client = new UFIDAU9ISVMOIDeleteCompRptSrvClient();
                MessageBase[] returnMsg;
                object context;
                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 = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                #region 已审核的单据先弃审
                List<string> DocList = new List<string>();
                foreach (ICSManufactureReceiveDoc Info in infos)
                {
                    long DocID = 0;
                    string DocType = "";
                    DataTable dt = GetData(Info.MRCVCode, OrgID);
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        //审核完成的单据需要先弃审，后删除
                        if (dt.Rows[0][1].ToString() == "1")
                        {
                            DocList.Add(DocID.ToString());
                        }
                    }
                    else
                    {
                        throw new Exception("需要删除的单据号不正确!");
                    }
                }
                UnApproveCompRpt UnApprove = new UnApproveCompRpt();
                UnApprove.UnApprove(DocList, OrgID);
                #endregion

                UFIDAU9ISVMOCompRptKeyDTOData[] compRptKeyDTOs = new UFIDAU9ISVMOCompRptKeyDTOData[] { };
                List<UFIDAU9ISVMOCompRptKeyDTOData> compRptKeyList = new List<UFIDAU9ISVMOCompRptKeyDTOData>();

                foreach (ICSManufactureReceiveDoc Info in infos)
                {
                    UFIDAU9ISVMOCompRptKeyDTOData model = new UFIDAU9ISVMOCompRptKeyDTOData();
                    model.m_docNo = Info.MRCVCode;
                    model.m_iD = GetTypeID(Info.MRCVCode, OrgID);
                    compRptKeyList.Add(model);
                }

                compRptKeyDTOs = compRptKeyList.ToArray();

                context = CreateContextObj(OrgID);

                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                bool isfalse = false;

                isfalse = client.Do(out returnMsg, context, compRptKeyDTOs);
                if (isfalse)
                {
                    ResultFlag = true;
                }
                else
                {
                    throw new Exception("完工报告删除失败，请查看日志!");
                }
            }
            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 Delete(List<string> DocNOList, string OrgCode)
        {
            bool ResultFlag = false;
            try
            {
                UFIDAU9ISVMOIDeleteCompRptSrvClient client = new UFIDAU9ISVMOIDeleteCompRptSrvClient();
                MessageBase[] returnMsg;
                object context;
                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 = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("删除传入组织编码错误!");
                }
                List<string> DocList = new List<string>();
                List<string> CancelList = new List<string>();
                foreach (string DocNo in DocNOList)
                {
                    long DocID = 0;
                    string DocType = "";
                    DataTable dt = GetData(DocNo, OrgID);
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        //审核完成的单据需要先弃审，后删除
                        if (dt.Rows[0][1].ToString() == "1")
                        {
                            DocList.Add(DocNo.ToString());
                        }
                        //已入库的单据需要先取消入库，再弃审，最后删除
                        if (dt.Rows[0][1].ToString() == "3")
                        {
                            DocList.Add(DocNo.ToString());
                            CancelList.Add(DocNo.ToString());
                        }
                    }
                    else
                    {
                        throw new Exception("需要删除的单据号不正确!");
                    }
                }
                if (CancelList.Count > 0)
                {
                    CloseCompRpt Open = new CloseCompRpt();
                    Open.OpenCompRpt(CancelList, OrgCode);
                }
                if (DocList.Count > 0)
                {
                    UnApproveCompRpt UnApprove = new UnApproveCompRpt();
                    UnApprove.UnApprove(DocList, OrgCode);
                }

                UFIDAU9ISVMOCompRptKeyDTOData[] compRptKeyDTOs = new UFIDAU9ISVMOCompRptKeyDTOData[] { };
                List<UFIDAU9ISVMOCompRptKeyDTOData> compRptKeyList = new List<UFIDAU9ISVMOCompRptKeyDTOData>();

                foreach (string DocNo in DocNOList)
                {
                    UFIDAU9ISVMOCompRptKeyDTOData model = new UFIDAU9ISVMOCompRptKeyDTOData();
                    model.m_docNo = DocNo;
                    model.m_iD = GetTypeID(DocNo, OrgID);
                    compRptKeyList.Add(model);
                }

                compRptKeyDTOs = compRptKeyList.ToArray();

                context = CreateContextObj(OrgID);

                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                bool isfalse = false;

                isfalse = client.Do(out returnMsg, context, compRptKeyDTOs);
                if (isfalse)
                {
                    ResultFlag = true;
                }
                else
                {
                    throw new Exception("完工报告删除失败，请查看日志!");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            return ResultFlag;
        }

        private static long GetTypeID(string docTypeCode, string OrgID)
        {
            string sql = @"select ID from MO_CompleteRpt where DocNo='" + docTypeCode + "' AND Org='" + OrgID + "' ";
            DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
            if (dt.Rows.Count > 0)
            {
                return long.Parse(dt.Rows[0][0].ToString());
            }
            else
            {
                return 0;
            }
        }

        #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 ID,DocState from MO_CompleteRpt
                            where DocNo='"+ DocCode + "' AND Org='" + OrgID + "'";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }
    }
}
