using HH.YiDaSyncNC.Dtos.NC;
using HH.YiDaSyncNC.Dtos.YIDA;
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;

namespace HH.YiDaSyncNC.DataSync
{
    public class YF_FPRZ_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 YF_FPRZ_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 searchKey = new
                {

                    radioField_lycrvvtk = "Y",
                    //textField_lvj2jklf = "FPRZ2024102100029",
                    selectField_lrnh633d = "预付",


                };

                var idList = _dingTalkService.GetFormCodeList(JsonConvert.SerializeObject(searchKey));

                LogHelper.WriteLog(JsonConvert.SerializeObject(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)
                {
                    string createTime = "";
                    string modifyTime = "";


                    var ydDataSource = _dingTalkService.GetFormDataById(item, out createTime, out modifyTime);

                    //var ydDataSource = _dingTalkService.GetFormDataByCode(item);//之前的有bug，表体大于50行 获取不到

                    LogHelper.WriteLog(JsonConvert.SerializeObject(ydDataSource), "发票入账数据执行");

                    string jsonData = JsonConvert.SerializeObject(ydDataSource);
                    YiDa_FPRZD thisYiDaData = JsonConvert.DeserializeObject<YiDa_FPRZD>(jsonData);

                    if (string.IsNullOrWhiteSpace(thisYiDaData.textField_lzh0m1lg))
                    {

                        LogHelper.WriteLog("供应商为空", "发票入账数据执行");
                        continue;

                    }
                    if (string.IsNullOrWhiteSpace(thisYiDaData.textField_lzh0m1lh))
                    {

                        LogHelper.WriteLog("成本组织为空", "发票入账数据执行");
                        continue;

                    }
                    if (thisYiDaData.associationFormField_lzh0m1le_id is null)
                    {

                        LogHelper.WriteLog("供应商为空", "发票入账数据执行");
                        continue;

                    }
                    var 供应商编码 = thisYiDaData.textField_lzhtchrg;
                    if (string.IsNullOrWhiteSpace(供应商编码))
                    {

                        LogHelper.WriteLog("供应商编码为空", "发票入账数据执行");
                        continue;

                    }
                    if (thisYiDaData.tableField_lsx02qv5 is null || thisYiDaData.tableField_lsx02qv5.Count == 0)
                    {

                        LogHelper.WriteLog("发票明细为空", "发票入账数据执行");
                        continue;

                    }
                    if (thisYiDaData.tableField_lrngrtgu is null || thisYiDaData.tableField_lrngrtgu.Count == 0)
                    {

                        LogHelper.WriteLog("入账明细为空", "发票入账数据执行");
                        continue;

                    }
                    if (thisYiDaData.tableField_lsx02qv5.Any(s => string.IsNullOrWhiteSpace(s.textField_lsx02qv8)))
                    {
                        LogHelper.WriteLog("发票明细-发票号为空", "发票入账数据执行");
                        continue;
                    }


                    //取值 宜搭表单的某个字段当作凭证日期 如果 支付完成时间 为null，就用 提交时间
                    DateTime 凭证日期 = DateTime.Now;
                    //thisYiDaData.dateField_lwitiobz is null
                    //    ? UnixTimeHelper.ConvertMillisecondsToDateTime(thisYiDaData.dateField_lviv4sfy)
                    //    : UnixTimeHelper.ConvertMillisecondsToDateTime((long)thisYiDaData.dateField_lwitiobz);
                    string 组织 = "";
                    if (!string.IsNullOrWhiteSpace(thisYiDaData.textField_lzh0m1lh))
                    {
                        var tempData = org_orgsDic.FirstOrDefault(f => f.name == thisYiDaData.textField_lzh0m1lh);
                        if (tempData != null)
                        {
                            组织 = tempData.code; // 组织
                        }
                    }


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


                    string 制单人 = "OA-NC";



                    string 发票拼接 = string.Join("/", thisYiDaData.tableField_lsx02qv5.Select(s => s.textField_lsx02qv8).ToList());

                    // 表头
                    var headModel = new FKGL_SyncServiceModel.DataModel.voucher_header()
                    {
                        year = 凭证日期.ToString("yyyy"),//会计年度
                        prepareddate = 凭证日期.ToString("yyyy-MM-dd"),//制单日期
                        period = 凭证日期.ToString("MM"),//会计期间
                        pk_prepared = 制单人,//凭证制单人--操作员工工号
                        no = "",//凭证号
                        pk_accountingbook = 账簿,//账簿
                        org = 组织,//组织编码
                        pk_vouchertype = "04",//凭证类别 ： 01-记账凭证 ，02-收款凭证 ，03-付款凭证 ，04-转账凭证 
                    };
                    //表体
                    var detailList = new List<FKGL_SyncServiceModel.DataModel.voucher_body>();
                    int index = 1;
                    foreach (var dataObj in thisYiDaData.tableField_lrngrtgu)
                    {
                        var 项目编码 = dataObj.radioField_ly71lpio == "项目" ? dataObj.textField_ly7257rx : "";
                        var 部门编码 = dataObj.radioField_ly71lpio == "机关" ? dataObj.textField_ly7257rx : "";

                        var assList = new List<FKGL_SyncServiceModel.DataModel.ass>();
                        if (!string.IsNullOrWhiteSpace(项目编码))
                        {
                            assList.Add(new FKGL_SyncServiceModel.DataModel.ass()
                            {
                                pk_Checktype = "0010",//0010-项目辅助核算
                                pk_Checkvalue = 项目编码,//供应商编码
                            });
                        }
                        if (!string.IsNullOrWhiteSpace(部门编码))
                        {
                            assList.Add(new FKGL_SyncServiceModel.DataModel.ass()
                            {
                                pk_Checktype = "0001",//0001-部门辅助核算
                                pk_Checkvalue = 部门编码,//供应商编码
                            });
                        }


                        //借方分录
                        detailList.Add(new FKGL_SyncServiceModel.DataModel.voucher_body()
                        {
                            detailindex = index,
                            accsubjcode = dataObj.textField_lrnh633r,//科目编码 预付账款
                            pk_accasoa = dataObj.textField_lrnh633r,//科目编码 
                            explanation = (dataObj?.textField_lvxa4v05?.Length ?? 0) > 59 ? dataObj.textField_lvxa4v05.Substring(0, 59) : $"{dataObj.textField_lvxa4v05}",//摘要 
                            verifydate = 凭证日期.ToString("yyyy-MM-dd"),
                            price = "0.00000000",
                            excrate2 = "1",
                            debitamount = dataObj.numberField_lvxa4v09.ToString(),//借方金额 
                            localdebitamount = dataObj.numberField_lvxa4v09.ToString(),//借方金额
                            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 FKGL_SyncServiceModel.DataModel.cash_flow()//现金流 
                            {

                            },
                            ass = assList,
                        });

                        index++;
                    }

                    //借方分录 应交增值税\应交税费 - 进项税
                    var sjSum = thisYiDaData.tableField_lrngrtgu.Sum(s => s.numberField_lvxa4v08);
                    if (sjSum > 0)
                    {
                        detailList.Add(new FKGL_SyncServiceModel.DataModel.voucher_body()
                        {
                            detailindex = index,
                            accsubjcode = "22210103",//科目编码 应交税费 - 进项税
                            pk_accasoa = "22210103",//科目编码 
                            explanation = $"{发票拼接}".Length > 59 ? $"{发票拼接}".Substring(0,59) : $"{发票拼接}",//摘要 
                            verifydate = 凭证日期.ToString("yyyy-MM-dd"),
                            price = "0.00000000",
                            excrate2 = "1",
                            debitamount = sjSum.ToString(),//借方金额 
                            localdebitamount = sjSum.ToString(),//借方金额
                            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 FKGL_SyncServiceModel.DataModel.cash_flow(),//现金流
                            ass = new List<FKGL_SyncServiceModel.DataModel.ass>(),//辅助核算
                        });
                        index++;
                    }

                    //贷方
                    detailList.Add(new FKGL_SyncServiceModel.DataModel.voucher_body()
                    {
                        detailindex = index,
                        accsubjcode = "1123",//科目编码 预付账款
                        pk_accasoa = "1123",//科目编码 
                        explanation = "贷方摘要",//摘要 
                        verifydate = 凭证日期.ToString("yyyy-MM-dd"),
                        price = "0.00000000",
                        excrate2 = "1",
                        creditamount = thisYiDaData.numberField_lu2habj9.ToString(),//贷方金额 
                        localcreditamount = thisYiDaData.numberField_lu2habj9.ToString(),//贷方金额 
                        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 FKGL_SyncServiceModel.DataModel.cash_flow(),//现金流 
                        ass = new List<FKGL_SyncServiceModel.DataModel.ass>()
                                {
                                    new FKGL_SyncServiceModel.DataModel.ass()
                                    {
                                        pk_Checktype ="0019",//0019-供应商辅助核算
                                        pk_Checkvalue = 供应商编码,//供应商编码
                                    }
                                },
                    });

                    XElement xElement = FKGL_SyncServiceModel.ImportXml_凭证.TemplateHeade(headModel);
                    xElement.Add(FKGL_SyncServiceModel.ImportXml_凭证.Header(headModel));//添加表头数据
                    xElement.Element("voucher").Element("voucher_head").Element("details").Add(FKGL_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)
            {

                throw;
            }
        }
    }
}
