using ICS.WCF.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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 UFIDA.ISV.AppRovedAPBill;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.U9.Cust.CreateApBillBySrcDoc
{
    public class CustCreateApBySrcDocSrv
    {
        string MessageLogName = "创建应付单（有来源单据）";

        public ReturnNEWModel Create(object JsonData)
        {

            ReturnNEWModel result = new ReturnNEWModel();
            try
            {
                if (JsonData == null)
                {
                    throw new Exception("参数为空！");
                }

                StringBuilder beginstrlog = new StringBuilder();
                beginstrlog.AppendLine("传入参数：" + JsonData);
                Appconfig.WriteLogFile(beginstrlog.ToString(), MessageLogName);

                List<CreateAPBillModel> lstmodel = JsonConvert.DeserializeObject<List<CreateAPBillModel>>(JsonData.ToString());
                string VenderCode = "";
                foreach (CreateAPBillModel model in lstmodel)
                {
                    if (VenderCode == "")
                    {
                        VenderCode = model.cVenCode;
                    }
                    else
                    {
                        if (VenderCode != model.cVenCode)
                        {
                            throw new Exception("传入数据中包含了不同的供应商，请选择相同供应商的收货单来创建应付单!");
                        }
                    }
                }
                //上下文信息
                object context;
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, lstmodel[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("组织编码不存在！");
                }


                string UserID = "";
                string UserName = "";
                string sqlUser = "select ID,Name from Base_User where Code ='" + lstmodel[0].MUSER + "' and Effective_IsEffective = 1";
                DataTable dtUser = DBhlper.Query(sqlUser, Appconfig.GetU9ConnStr());
                if (dtUser != null && dtUser.Rows.Count > 0)
                {
                    UserID = dtUser.Rows[0]["ID"].ToString();
                    UserName = dtUser.Rows[0]["Name"].ToString();
                }
                else
                {
                    throw new Exception("创建用户在U9中不存在，用户编码：" + lstmodel[0].MUSER);
                }

                context = CreateContextObj(OrgID, UserID, lstmodel[0].MUSER, UserName);

                string SupplierCode = "";
                long AC = 0;

                string sqlDoc = "select Supplier_Code,AC from PM_Receivement  where  DocNo ='" + lstmodel[0].details[0].ReturnDocID + "' and Org ='" + OrgID + "'";
                DataTable dtDoc = DBhlper.Query(sqlDoc, Appconfig.GetU9ConnStr());
                if (dtDoc != null && dtDoc.Rows.Count > 0)
                {
                    SupplierCode = dtDoc.Rows[0]["Supplier_Code"].ToString();
                    AC = long.Parse(dtDoc.Rows[0]["AC"].ToString());
                }
                else
                {
                    throw new Exception("来源单据不存在");
                }

                MessageBase[] outMessages;


                UFIDAU9APForAPIIAPAccrueAPISVClient client = new UFIDAU9APForAPIIAPAccrueAPISVClient();
                UFIDAU9CBOFIDTOsAccrueAPIDTOData data = new UFIDAU9CBOFIDTOsAccrueAPIDTOData();
                data.m_accrueDate = Convert.ToDateTime(lstmodel[0].dVouDate);
                data.m_invoiceDate = Convert.ToDateTime(lstmodel[0].dPBVDate);
                data.m_invoiceNum = lstmodel[0].cPBVCode;
                data.m_cusOrSuppCode = SupplierCode;
                data.m_cusOrSuppSiteCode = SupplierCode;
                data.m_fIOrg = long.Parse(OrgID);
                data.m_srcOrg = long.Parse(OrgID);
                data.m_aPMergConfigDTO = new UFIDAU9CBOFI_SCMDTOsAPMergeAccrueCfgDTOData();
                data.m_aRMergConfigDTO = new UFIDAU9CBOFI_SCMDTOsARMergeAccrueCfgDTOData();
                data.m_isMerge = true;
                data.m_currency = AC;


                List<UFIDAU9CBOFIDTOsAccrueDetailAPIDTOData> list = new List<UFIDAU9CBOFIDTOsAccrueDetailAPIDTOData>();

                long ID = 0;
                long TaxScheduleID = 0;

                foreach (CreateAPBillModel model in lstmodel)
                {
                    foreach (CreateAPBillLineModel item in model.details)
                    {
                        bool RMA = true;
                        decimal TaxPrice = 0;
                        decimal NoTaxPrice = 0;
                        decimal TaxMoney = 0;
                        decimal NoTaxMoney = 0;
                        decimal TotalMoney = 0;
                        string sql = @" select b.ReceivementType,c.TaxSchedule,c.ID,c.FinallyPriceTC AS TaxPrice,c.EvaluationPriceCU AS NoTaxPrice 
									    ,c.TotalTaxAC AS TaxMoney,C.TotalNetMnyAC AS NoTaxMoney
									    ,c.TotalMnyAC AS TotalMoney
									    from PM_Receivement a
                                        left join PM_RcvDocType b on a.RcvDocType = b.id
                                        left join PM_RcvLine c on a.id = c.Receivement
                                        where c.ID ='" + item.ReturnDocLineID + "'";
                        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            ID = long.Parse(dt.Rows[0]["ID"].ToString());
                            TaxPrice = Convert.ToDecimal(dt.Rows[0]["TaxPrice"].ToString());
                            NoTaxPrice = Convert.ToDecimal(dt.Rows[0]["NoTaxPrice"].ToString());
                            TaxMoney = Convert.ToDecimal(dt.Rows[0]["TaxMoney"].ToString());
                            NoTaxMoney = Convert.ToDecimal(dt.Rows[0]["NoTaxMoney"].ToString());
                            TaxPrice = Convert.ToDecimal(dt.Rows[0]["TaxPrice"].ToString());
                            TotalMoney = Convert.ToDecimal(dt.Rows[0]["TotalMoney"].ToString());
                            if (dt.Rows[0]["ReceivementType"].ToString() == "0")
                            {
                                RMA = false;
                            }
                        }
                        else
                        {
                            throw new Exception("来源单行不存在！");
                        }

                        UFIDAU9CBOFIDTOsAccrueDetailAPIDTOData detail = new UFIDAU9CBOFIDTOsAccrueDetailAPIDTOData();
                        detail.m_lineID = ID;
                        detail.m_amount = Math.Abs(Convert.ToDecimal(item.iPBVQuantity));
                        detail.m_taxScedule = TaxScheduleID;
                        detail.m_taxPrice = Math.Abs(TaxPrice);
                        detail.m_noTaxPrice = Math.Abs(NoTaxPrice);
                        detail.m_taxMoney = Math.Abs(TaxMoney);
                        detail.m_noTaxMoney = Math.Abs(NoTaxMoney);
                        detail.m_totalMoney = Math.Abs(TotalMoney);
                        detail.m_isRMA = RMA;



                        list.Add(detail);

                    }
                }
                if (list.Count > 0)
                {
                    data.m_accrueDetailDTOs = list.ToArray();

                }
                else
                {
                    throw new Exception("来源单据立账信息为空");
                }

                long[] rtnMes = client.Do(out outMessages, context, data);

                if (rtnMes.Length > 0)
                {
                    for (int i = 0; i < rtnMes.Length; i++)
                    {

                        string sql = "select  DocNo from AP_APBillHead where ID ='" + rtnMes[i] + "'";
                        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            string DocNo = dt.Rows[0]["DocNo"].ToString();
                            //CustApprovedAPBill Approve = new CustApprovedAPBill();
                            //ApproveAPRtnModel res = Approve.CustApprovedAP(new ApproveAPModel
                            //{
                            //    DocNo = DocNo,
                            //    OrgCode = lstmodel[0].WorkPoint
                            //});

                            //if (res.IsSuccess)
                            //{
                                result.IsSuccess = true;
                                result.MESSAGE = "创建应付单成功";
                                result.DocNo += DocNo + " ";
                            //}
                            //else
                            //{
                            //    result.IsSuccess = false;
                            //    result.MESSAGE = "创建单据成功，审核失败，异常：" + res.Message;
                            //    result.DocNo = DocNo;
                            //}
                        }
                        else
                        {
                            throw new Exception("单据ID不存在，ID:" + rtnMes[i]);
                        }
                    }
                }
                else
                {
                    result.IsSuccess = false;
                    result.MESSAGE = "创建单据失败";
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.MESSAGE = GetExceptionMessage(ex);
            }
            string RtnJson = JsonConvert.SerializeObject(result);
            Appconfig.WriteLogFile("返回结果：" + RtnJson, MessageLogName);
            return result;
        }
        private static ThreadContext CreateContextObj(string OrgID, string UserID, string UserCode, string UserName)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UserID);
            ns.Add("UserCode", UserCode);
            ns.Add("UserName", UserName);
            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;
        }


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


        public class CreateAPBillModel
        {
            public string WorkPoint { get; set; }
            public string cPBVBillType { get; set; }//发票类型 
            public string cPBVCode { get; set; }//采购发票号
            public string dPBVDate { get; set; }//开票日期 
            public string cVenCode { get; set; }//供应商编码 
            public string iPBVTaxRate { get; set; }//表头税率 
            public string cPBVMaker { get; set; }//制单人 
            public string cContactCode { get; set; }//供方联系人编码 
            public string MUSER { get; set; }//业务员编码 
            public string SubjectCode { get; set; }//采购类型编码 
            public string dVouDate { get; set; }//单据日期 
            public string cVenBank { get; set; }//供方银行名称  
            public string cVenAccount { get; set; }//供方银行账号  
            public string VenPayCond { get; set; }//付款条件编码 
            public string DepCode { get; set; }//部门编码 
            public string cContactName { get; set; }//供方联系人  
            public List<CreateAPBillLineModel> details;
        }

        public class CreateFile
        {
            public string EntityID;
            public string EntityType;
            public string FlowID;
            public File[] files;

        }
        public class File
        {
            public string Type;
            public string FileName;
            public int FileSize;
            public string FileContent;
        }
        public class CreateAPBillLineModel
        {
            public string WorkPoint { get; set; }
            public string cInvCode { get; set; }//物料代码  
            public string iPBVQuantity { get; set; }//数量  
            public string ReturnDocID { get; set; }//入库主表ID  
            public string ReturnDocLineID { get; set; }//入库单子表ID  
            public string Year { get; set; }//年月  
            public string Month { get; set; }//月  

            public string LogId { get; set; }
        }



        public class DescFlexField
        {
            public string PrivateDescSeg1 { get; set; }
            public string PubDescSeg1 { get; set; }
        }
        public class APBill
        {
            public DescFlexField DescFlexField { get; set; }
            public string OtherID { get; set; }
            public string Memo { get; set; }
            public string AccrueDate { get; set; }
            public string CusOrSuppCode { get; set; }
            public string CusOrSuppSiteCode { get; set; }
            public string FIOrg_Code { get; set; }
            public long SrcOrg { get; set; }
            public bool IsMerge { get; set; }
            public List<APAccrueDetailDTORDatas> APAccrueDetailDTORDatas { get; set; }
            public string Currency_Code { get; set; }
            public APMergConfigDTORData APMergConfigDTORData { get; set; }
            public APQryConfigureParaDTO APQryConfigureParaDTO { get; set; }

            //public bool IsIncludeRelCust { get; set; }
            //public string InvoiceNum { get; set; }
            //public string InvoiceDate { get; set; }
        }
        public class APMergConfigDTORData
        {
            public bool IsMaturity { get; set; }
            public bool IsDept { get; set; }
            public bool IsTransactor { get; set; }
            public bool IsAccrueTerm { get; set; }
            public bool IsPayTerm { get; set; }
            public bool IsProject { get; set; }
            public bool IsTask { get; set; }
            public bool IsMnyBugetSpec { get; set; }
            public bool IsBizBugetSpec { get; set; }
            public bool IsMemo { get; set; }
            public bool IsSrcOrg { get; set; }
            public bool IsTaxPrice { get; set; }
            public bool IsNonTaxPrice { get; set; }
        }
        public class APAccrueDetailDTORDatas
        {
            public DescFlexField DescFlexField { get; set; }
            public long LineID { get; set; }
            public decimal Amount { get; set; }
            public decimal TaxPrice { get; set; }
            public decimal NoTaxPrice { get; set; }
            public decimal TaxMoney { get; set; }
            public decimal NoTaxMoney { get; set; }
            public decimal TotalMoney { get; set; }
            public string TaxScedule_Code { get; set; }
            public bool IsRMA { get; set; }

        }
        public class APQryConfigureParaDTO
        {
            public bool IsOrg { get; set; }
            public bool IsAccrueBy { get; set; }
            public bool IsSrcBusinessType { get; set; }
            public bool IsAccrueDate { get; set; }
            public bool IsAC { get; set; }
            public bool IsAccrueSupp { get; set; }
            public bool IsAccrueSuppSite { get; set; }
            public bool IsPaySuppSite { get; set; }
            public bool IsDept { get; set; }
            public bool IsTransactor { get; set; }
            public bool IsAccrueTerm { get; set; }
            public bool IsPayTerm { get; set; }
            public bool IsTaxSchedule { get; set; }
            public bool IsProject { get; set; }
            public bool IsTask { get; set; }
            public bool IsSrcOrg { get; set; }
            public bool IsBizOrg { get; set; }
            public bool IsSettleOrg { get; set; }
            public bool IsSrcDocNo { get; set; }
            public bool IsRowCount { get; set; }
        }

        public class ReturnNEWModel
        {
            public bool IsSuccess { get; set; }
            public string MESSAGE { get; set; }
            public string DocNo { get; set; }
        }


    }
}
