using HH.YiDaSyncNC.Dtos.NC;
using HH.YiDaSyncNC.Dtos;
using HH.YiDaSyncNC.Helper;
using HH.YiDaSyncNC.Models;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using HH.YiDaSyncNC.Dtos.YIDA;

namespace HH.YiDaSyncNC.DataSync
{
    public class HKD_GL_SyncService
    {
        public string _AppType;
        public string _SystemToken;
        public string _UserId;
        public string _FormId;
        public SqlSugarClient _db;
        public SqlSugarClient _db_nc;
        public string _NCApiUrl;

        public static string _Static_PK_bd_project = ConfigurationManager.AppSettings["bd_project"];
        public static string _Static_pk_org_jt = ConfigurationManager.AppSettings["pk_org_jt"];
        public HKD_GL_SyncService(string AppType, string SystemToken, string UserId, string FormId, SqlSugarClient db, SqlSugarClient db_nc, string NCApiUrl)
        {
            _AppType = AppType;
            _SystemToken = SystemToken;
            _UserId = UserId;
            _FormId = FormId;
            _db = db;
            _db_nc = db_nc;
            _NCApiUrl = NCApiUrl;
        }

        public void DataSync()
        {
            try
            {

                DingTalkService _dingTalkService = new DingTalkService(_AppType, _SystemToken, _UserId, _FormId);


                var idList = _dingTalkService.GetFormCodeList("");
                LogHelper.WriteLog(JsonConvert.SerializeObject(idList.Count), "idList");

                #region 获取NC中选项数据的Id
                var bd_customerDic = _db_nc.Queryable<bd_customer>().ToList();
                var bd_incomeDic = _db_nc.Queryable<bd_income>().ToList();
                var org_orgsDic = _db_nc.Queryable<org_orgs>().ToList();
                var bd_projectDic = _db_nc.Queryable<bd_project>().ToList();
                var bd_materialDic = _db_nc.Queryable<bd_material>().ToList();
                var bd_measdocDic = _db_nc.Queryable<bd_measdoc>().ToList();
                var org_deptDic = _db_nc.Queryable<org_dept>().ToList();
                var bd_psndocDic = _db_nc.Queryable<bd_psndoc>().ToList();
                var sm_userDic = _db_nc.Queryable<sm_user>().ToList();
                var org_accountingbookDic = _db_nc.Queryable<org_accountingbook>().ToList();
                #endregion

                foreach (var item in idList)
                {
                    try
                    {
                        var ydDataSource = _dingTalkService.GetFormDataByCode(item);
                        string jsonData = JsonConvert.SerializeObject(ydDataSource);

                        // 如果NC单据号为空，说明没有传入过NC，此时需要走此逻辑去传输
                        if (ydDataSource.FirstOrDefault(f => f.Key == "textField_ltxyt75m").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["textField_ltxyt75m"].ToString()))
                        {
                            continue;
                        }


                        YiDa_ZZHX thisYiDaData = JsonConvert.DeserializeObject<YiDa_ZZHX>(jsonData);

                        DateTime 凭证日期 = DateTime.Now;

                        string 组织 = "";
                        if (!string.IsNullOrWhiteSpace(thisYiDaData.textField_lw0ef16v))
                        {
                            var tempData = org_orgsDic.FirstOrDefault(f => f.name == thisYiDaData.textField_lw0ef16v);
                            if (tempData != null)
                            {
                                组织 = tempData.code; // 组织
                            }
                        }


                        string 账簿 = "";
                        if (!string.IsNullOrWhiteSpace(thisYiDaData.textField_lw0ef16v))
                        {
                            var tempData = org_accountingbookDic.FirstOrDefault(f => f.name == thisYiDaData.textField_lw0ef16v + "-蓝云账簿");
                            if (tempData != null)
                            {
                                账簿 = tempData.code; // 账簿
                            }
                        }


                        string 人员编码 = "";//测试
                        if (thisYiDaData.employeeField_lviv4sfw != null && thisYiDaData.employeeField_lviv4sfw.Count > 0)
                        {
                            var firstName = thisYiDaData.employeeField_lviv4sfw.FirstOrDefault();
                            var tempData = bd_psndocDic.FirstOrDefault(f => firstName.Contains(f.name));
                            if (tempData != null)
                            {
                                人员编码 = tempData.code; // 账簿
                            }
                        }



                        string 制单人 = "OA-NC";

                        // 表头
                        var headModel = new HKD_GL_SyncServiceModel.DataModel.voucher_header()
                        {
                            year = 凭证日期.ToString("yyyy"),//会计年度
                            prepareddate = 凭证日期.ToString("yyyy-MM-dd"),//制单日期
                            period = 凭证日期.ToString("MM"),//会计期间
                            pk_prepared = 制单人,//凭证制单人--操作员工工号
                            no = "",//凭证号
                            pk_accountingbook = 账簿,//账簿
                            org = 组织,//组织编码
                            pk_vouchertype = "02",//凭证类别 ： 01-记账凭证 ，02-收款凭证 ，03-付款凭证 ，04-转账凭证 要确定
                        };
                        //表体
                        var detailList = new List<HKD_GL_SyncServiceModel.DataModel.voucher_body>();


                        //贷方
                        detailList.Add(new HKD_GL_SyncServiceModel.DataModel.voucher_body()
                        {
                            detailindex = 1,
                            accsubjcode = "122105",//科目编码 其他应收款-人员借款 
                            pk_accasoa = "122105",//科目编码  
                            explanation = "贷方摘要",//摘要  1
                            verifydate = 凭证日期.ToString("yyyy-MM-dd"),
                            price = "0.00000000",
                            excrate2 = "1",
                            creditamount = thisYiDaData.numberField_lvuc0gtq.ToString(),//贷方金额  1
                            localcreditamount = thisYiDaData.numberField_lvuc0gtq.ToString(),//贷方金额  1
                            debitquantity = "0.00000000",
                            debitamount = "0.00000000",
                            groupdebitamount = "0.00000000",
                            globaldebitamount = "0.00000000",
                            localdebitamount = "0.00000000",
                            creditquantity = "0.00000000",
                            groupcreditamount = "0.00000000",
                            globalcreditamount = "0.00000000",
                            billtype = "",
                            bankaccount = "",
                            checkstyle = "",
                            checkno = "",
                            checkdate = "",
                            bill_id = "",
                            bill_date = "",
                            pk_currtype = "CNY",
                            cash_flow = new HKD_GL_SyncServiceModel.DataModel.cash_flow()//现金流 
                            {
                                m_pk_currtype = "CNY",
                                pk_cashflow = "1113",//现金流编码 
                                money = thisYiDaData.numberField_lvuc0gtq.ToString(),//金额  1
                                moneymain = thisYiDaData.numberField_lvuc0gtq.ToString(),//金额  1
                                moneygroup = "",
                                moneyglobal = "",
                                pk_innercorp = "",
                            },
                            ass = new List<HKD_GL_SyncServiceModel.DataModel.ass>()//
                                {
                                    new HKD_GL_SyncServiceModel.DataModel.ass()
                                    {
                                        pk_Checktype ="0001",//0019-部门
                                        pk_Checkvalue = thisYiDaData.textField_lyzc1mpt,//部门编码 1
                                    },
                                     new HKD_GL_SyncServiceModel.DataModel.ass()
                                    {
                                        pk_Checktype ="0002",//0019-人员
                                        pk_Checkvalue = 人员编码,//人员编码 1
                                    }
                                },
                        });

                        //借方
                        detailList.Add(
                            new HKD_GL_SyncServiceModel.DataModel.voucher_body()
                            {
                                detailindex = 2,
                                accsubjcode = thisYiDaData.textField_lyocuyp3,//科目编码  1
                                pk_accasoa = thisYiDaData.textField_lyocuyp3,//科目编码 1
                                explanation = "借方摘要",//摘要 
                                verifydate = 凭证日期.ToString("yyyy-MM-dd"),
                                price = "0.00000000",
                                excrate2 = "1",
                                debitamount = thisYiDaData.numberField_lvuc0gtq.ToString(),//借方金额  1
                                localdebitamount = thisYiDaData.numberField_lvuc0gtq.ToString(),//借方金额 1
                                debitquantity = "0.00000000",
                                groupdebitamount = "0.00000000",
                                globaldebitamount = "0.00000000",
                                creditquantity = "0.00000000",
                                creditamount = "0.00000000",
                                groupcreditamount = "0.00000000",
                                globalcreditamount = "0.00000000",
                                localcreditamount = "0.00000000",
                                billtype = "",
                                bankaccount = "",
                                checkstyle = "",
                                checkno = "",
                                checkdate = "",
                                bill_id = "",
                                bill_date = "",
                                pk_currtype = "CNY",
                                cash_flow = new HKD_GL_SyncServiceModel.DataModel.cash_flow()
                                {
                                },
                                ass = new List<HKD_GL_SyncServiceModel.DataModel.ass>()//辅助核算 
                                {
                                    new HKD_GL_SyncServiceModel.DataModel.ass()
                                    {
                                        pk_Checktype ="0011",//0011-银行账户辅助核算 
                                        pk_Checkvalue =  thisYiDaData.textField_lsx02qvj.Replace(" ",""),//银行账户  1
                                    }
                                },
                            }
                        );

                        XElement xElement = HKD_GL_SyncServiceModel.ImportXml_凭证.TemplateHeade(headModel);
                        xElement.Add(HKD_GL_SyncServiceModel.ImportXml_凭证.Header(headModel));//添加表头数据
                        xElement.Element("voucher").Element("voucher_head").Element("details").Add(HKD_GL_SyncServiceModel.ImportXml_凭证.Bodydebit(detailList));
                        //生成凭证
                        var results_凭证 = NCImportFunc.NCImport2(xElement, _NCApiUrl + "?account=LY01&groupcode=0");

                        LogHelper.WriteLog(JsonConvert.SerializeObject(results_凭证), "results_凭证");


                        XElement xE = XElement.Parse(results_凭证);

                        string resultcode = xE.Element("sendresult").Element("resultcode").Value;

                        string content = xE.Element("sendresult").Element("content")?.Value;

                        string resultdescription = xE.Element("sendresult").Element("resultdescription")?.Value;
                        var ncResData = new YiDaResDto();
                        if (resultcode == "1")
                        {
                            ncResData = (new YiDaResDto()
                            {
                                bSuccess = true,
                                syncTime = DateTime.Now,
                                ncNo = resultdescription,//xE.Element("sendresult").Element("content").Value,
                                log = "同步成功！"
                            });
                        }
                        else
                        {
                            ncResData = (new YiDaResDto()
                            {
                                bSuccess = false,
                                syncTime = DateTime.Now,
                                ncNo = "",
                                log = "同步失败！原因为【" + resultdescription + "】！"
                            });
                        }
                        //更新同步标识
                        var ydRes = _dingTalkService.UpdateFormDataSyncDataById(ncResData, item);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(JsonConvert.SerializeObject(ex.ToString()), "HKD循环内错误");
                    }
                    
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(JsonConvert.SerializeObject(ex.ToString()), "HKD");
                throw;
            }
        }
    }
}
