using HH.YiDaSyncNC.Dtos;
using HH.YiDaSyncNC.Dtos.NC;
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
{
    class KP_TP_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_so_saleorder = ConfigurationManager.AppSettings["so_saleorder"];
        public static string _Static_PK_so_saleorder_b = ConfigurationManager.AppSettings["so_saleorder_b"];
        public static string _Static_pk_org_jt = ConfigurationManager.AppSettings["pk_org_jt"];

        public KP_TP_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 class IdCodeModel
        {
            public int sourceId { get; set; }
            public string Id { get; set; }
        }

        public class FormItem
        {
            public string title { get; set; }
        }

        public void DataSync()
        {
            DingTalkService _dingTalkService = new DingTalkService(_AppType, _SystemToken, _UserId, _FormId);

            // 宜搭全量数据Id
            var idList = _dingTalkService.GetFormIdList("{\"radioField_lycrvvtk\":\"Y\",\"selectField_lvituew9\":\"已红冲\"}");
            //var idList = _dingTalkService.GetFormIdList("{\"textField_lvdosccc\":\"KP_2024071700252\"}");

            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 bd_defdoc_kplx = _db_nc.Queryable<bd_defdoc>().Where(w => w.pk_defdoclist == "1001G1100000000016FV").ToList(); // 开票类型
            var bd_defdoc_htywlx = _db_nc.Queryable<bd_defdoc>().Where(w => w.pk_defdoclist == "1001G1100000000010PV").ToList(); // 合同业务类型
            #endregion

            #region 接口方式
            // 向NC插入数据
            foreach (var item in idList)
            {
                string createTime = "";
                string modifyTime = "";

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

                // 如果NC单据号不为空，说明正数发票及销售订单已经传入NC，此时按照此流程传输红票
                if (ydDataSource.FirstOrDefault(f => f.Key == "textField_ltxyt75m").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["textField_ltxyt75m"].ToString()))
                {

                }
                else
                {
                    continue;
                }

                var ncResData = new List<YiDaResDto>();


                #region 表头
                // 表头
                var dataSource = new KP_SyncServiceModel.DataModel();

                if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lvc9x4vo").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lvc9x4vo"].ToString()))
                    {
                        var tempData = org_orgsDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lvc9x4vo"].ToString());
                        if (tempData != null)
                        {
                            dataSource.组织 = tempData.code; // 组织
                        }
                    }
                }

                dataSource.单据日期 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                //if (!string.IsNullOrWhiteSpace(ydDataSource["dateField_lw5ud9bk"].ToString()))
                //{
                //    dataSource.单据日期 = UnixTimeHelper.ConvertMillisecondsToDateTime(Convert.ToInt64(ydDataSource["dateField_lw5ud9bk"].ToString())).ToString("yyyy-MM-dd HH:mm:ss");
                //}


                if (ydDataSource.FirstOrDefault(f => f.Key == "textField_lvdojfuj").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["textField_lvdojfuj"].ToString()))
                    {
                        var tempData = bd_customerDic.FirstOrDefault(f => f.code == ydDataSource["textField_lvdojfuj"].ToString());
                        if (tempData != null)
                        {
                            dataSource.客户 = tempData.code; // 客户
                        }
                    }
                }

                if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lvc9x4vq").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lvc9x4vq"].ToString()))
                    {
                        var tempData = bd_incomeDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lvc9x4vq"].ToString());
                        if (tempData != null)
                        {
                            dataSource.收款协议 = tempData.code; // 收款协议
                        }
                    }
                }

                if (ydDataSource.FirstOrDefault(f => f.Key == "departmentSelectField_lvc7mi3w").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["departmentSelectField_lvc7mi3w"].ToString()))
                    {
                        var tempData = org_deptDic.FirstOrDefault(f => f.name == JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(ydDataSource["departmentSelectField_lvc7mi3w"]))[0]);
                        if (tempData != null)
                        {
                            dataSource.部门 = tempData.code; // 部门
                        }
                    }
                }

                dataSource.审批人 = "OA-NC";
                dataSource.制单人 = "OA-NC";
                dataSource.创建人 = "OA-NC";

                dataSource.审批时间 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                dataSource.制单时间 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                dataSource.创建时间 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                if (ydDataSource.FirstOrDefault(f => f.Key == "textField_lvdntzul").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["textField_lvdntzul"].ToString()))
                    {
                        var tempData = bd_projectDic.FirstOrDefault(f => f.project_code == ydDataSource["textField_lvdntzul"].ToString());
                        if (tempData != null)
                        {
                            dataSource.项目 = tempData.project_code; // 项目
                        }
                    }
                }

                dataSource.发票号 = ydDataSource["textField_lwsth4o3"].ToString(); // 取重开发票号
                dataSource.客户打印名称 = ydDataSource["selectField_lvdojfui"].ToString();

                if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lvc9x4vp").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lvc9x4vp"].ToString()))
                    {
                        var tempName = ydDataSource["selectField_lvc9x4vp"].ToString();
                        if (ydDataSource["selectField_lvc9x4vp"].ToString() == "增值税专票")
                        {
                            tempName = "增值税专用发票";
                        }

                        if (ydDataSource["selectField_lvc9x4vp"].ToString() == "增值税普票")
                        {
                            tempName = "增值税普通发票";
                        }

                        var tempData = bd_defdoc_kplx.FirstOrDefault(f => f.name == tempName);
                        if (tempData != null)
                        {
                            dataSource.开票类型 = tempData.pk_defdoc; // 开票类型
                        }
                    }
                }

                dataSource.OA单据号 = ydDataSource["textField_lvdosccc"].ToString();

                if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lvc9x4vn").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lvc9x4vn"].ToString()))
                    {
                        if (ydDataSource["selectField_lvc9x4vn"].ToString().Contains("一次性") || ydDataSource["selectField_lvc9x4vn"].ToString().Contains("工程订单"))
                        {
                            dataSource.合同业务类型 = "1001G11000000000113F";
                        }
                        else
                        {
                            var tempData = bd_defdoc_htywlx.FirstOrDefault(f => f.name == ydDataSource["selectField_lvc9x4vn"].ToString());
                            if (tempData != null)
                            {
                                dataSource.合同业务类型 = tempData.pk_defdoc; // 合同业务类型
                            }
                        }
                    }
                }

                dataSource.年份 = DateTime.Now.ToString("yyyy");
                dataSource.月份 = DateTime.Now.ToString("MM");

                #endregion

                var detailList = new List<KP_SyncServiceModel.DataModel.OrderB>();

                #region 大业主开票明细
                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvc9x4vt").Value != null)
                {
                    if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvc9x4vt").Value != null)
                    {
                        var detailObjList1 = (List<object>)ydDataSource["tableField_lvc9x4vt"]; // 大业主开票明细

                        if (detailObjList1.Count() > 0 && !string.IsNullOrWhiteSpace(((Dictionary<string, object>)detailObjList1.FirstOrDefault())["textField_lvdojfup"].ToString()))
                        {

                            foreach (var objItem in detailObjList1)
                            {
                                var detailItem = new KP_SyncServiceModel.DataModel.OrderB();

                                if (!string.IsNullOrWhiteSpace(((Dictionary<string, object>)objItem)["associationFormField_lvynhq7p_id"].ToString()))
                                {
                                    var sourceStr = ((Dictionary<string, object>)objItem)["associationFormField_lvynhq7p_id"].ToString().Replace("\\", "");
                                    var a = sourceStr = sourceStr.Substring(1, sourceStr.Length - 2);
                                    var b = JsonConvert.DeserializeObject<List<FormItem>>(a);

                                    var materialData = bd_materialDic.FirstOrDefault(f => f.name == b[0].title);

                                    detailItem.物料 = materialData.code; // 物料

                                    var unitCode = bd_measdocDic.FirstOrDefault(f => f.pk_measdoc == materialData.pk_measdoc);

                                    detailItem.计量单位 = unitCode.code; // 计量单位
                                }

                                var hsdj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2v"].ToString());
                                var se = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2z"].ToString());
                                var wsdj = hsdj - se;
                                var sl = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2w"].ToString());
                                var wsje = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp30"].ToString());
                                var jshj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2y"].ToString());

                                // 含税单价
                                detailItem.含税单价 = hsdj.ToString();

                                // 无税单价
                                detailItem.无税单价 = wsdj.ToString();

                                //  含税净价
                                detailItem.含税净价 = hsdj.ToString();

                                // 无税净价
                                detailItem.无税净价 = wsdj.ToString();

                                // 税额
                                detailItem.税额 = se.ToString();

                                // 无税金额
                                detailItem.无税金额 = wsje.ToString();

                                // 数量
                                detailItem.数量 = sl.ToString();

                                // 价税合计
                                detailItem.价税合计 = jshj.ToString();

                                detailItem.换算率 = "1.00/1.00";
                                detailItem.税码 = "CN04"; // 税率码 
                                detailItem.税率 = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2x"].ToString()).ToString(); // 税率

                                detailItem.开票内容 = ((Dictionary<string, object>)objItem)["textField_lvd8pp2t"].ToString();

                                detailItem.行id = ((Dictionary<string, object>)objItem)["textField_lvdojfup"].ToString();

                                detailList.Add(detailItem);
                            }
                        }
                    }
                }
                #endregion

                #region 工程订单开票明细
                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvd8pp44").Value != null)
                {
                    var detailObjList2 = (List<object>)ydDataSource["tableField_lvd8pp44"]; // 工程订单开票明细
                    if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvd8pp44").Value != null)
                    {
                        if (detailObjList2.Count() > 0 && !string.IsNullOrWhiteSpace(((Dictionary<string, object>)detailObjList2.FirstOrDefault())["textField_lvdojfur"].ToString()))
                        {
                            dataSource.项目 = "PM99001";

                            foreach (var objItem in detailObjList2)
                            {
                                var detailItem = new KP_SyncServiceModel.DataModel.OrderB();

                                if (!string.IsNullOrWhiteSpace(((Dictionary<string, object>)objItem)["associationFormField_lvynrr6a_id"].ToString()))
                                {
                                    var sourceStr = ((Dictionary<string, object>)objItem)["associationFormField_lvynrr6a_id"].ToString().Replace("\\", "");
                                    var a = sourceStr = sourceStr.Substring(1, sourceStr.Length - 2);
                                    var b = JsonConvert.DeserializeObject<List<FormItem>>(a);

                                    var materialData = bd_materialDic.FirstOrDefault(f => f.name == b[0].title);

                                    detailItem.物料 = materialData.code; // 物料

                                    var unitCode = bd_measdocDic.FirstOrDefault(f => f.pk_measdoc == materialData.pk_measdoc);

                                    detailItem.计量单位 = unitCode.code; // 计量单位
                                }

                                var hsdj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp3y"].ToString());
                                var se = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp42"].ToString());
                                var wsdj = hsdj - se;
                                var sl = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp3z"].ToString());
                                var wsje = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp43"].ToString());
                                var jshj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp41"].ToString());

                                // 含税单价
                                detailItem.含税单价 = hsdj.ToString();

                                // 无税单价
                                detailItem.无税单价 = wsdj.ToString();

                                //  含税净价
                                detailItem.含税净价 = hsdj.ToString();

                                // 无税净价
                                detailItem.无税净价 = wsdj.ToString();

                                // 税额
                                detailItem.税额 = se.ToString();

                                // 无税金额
                                detailItem.无税金额 = wsje.ToString();

                                // 数量
                                detailItem.数量 = sl.ToString();

                                // 价税合计
                                detailItem.价税合计 = jshj.ToString();

                                detailItem.换算率 = "1.00/1.00";
                                detailItem.税码 = "CN04"; // 税率码 
                                detailItem.税率 = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp40"].ToString()).ToString(); // 税率

                                detailItem.开票内容 = ((Dictionary<string, object>)objItem)["textField_lvd8pp3w"].ToString();

                                detailItem.行id = ((Dictionary<string, object>)objItem)["textField_lvdojfur"].ToString();

                                detailList.Add(detailItem);
                            }
                        }
                    }
                }
                #endregion

                #region 小业主开票明细
                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvdnme13").Value != null)
                {
                    var detailObjList3 = (List<object>)ydDataSource["tableField_lvdnme13"]; // 小业主
                    if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvdnme13").Value != null)
                    {
                        if (detailObjList3.Count() > 0 && !string.IsNullOrWhiteSpace(((Dictionary<string, object>)detailObjList3.FirstOrDefault())["textField_lvdojfus"].ToString()))
                        {

                            foreach (var objItem in detailObjList3)
                            {
                                var detailItem = new KP_SyncServiceModel.DataModel.OrderB();

                                if (!string.IsNullOrWhiteSpace(((Dictionary<string, object>)objItem)["associationFormField_lvynrr6c_id"].ToString()))
                                {
                                    var sourceStr = ((Dictionary<string, object>)objItem)["associationFormField_lvynrr6c_id"].ToString().Replace("\\", "");
                                    var a = sourceStr = sourceStr.Substring(1, sourceStr.Length - 2);
                                    var b = JsonConvert.DeserializeObject<List<FormItem>>(a);

                                    var materialData = bd_materialDic.FirstOrDefault(f => f.name == b[0].title);

                                    detailItem.物料 = materialData.code; // 物料

                                    var unitCode = bd_measdocDic.FirstOrDefault(f => f.pk_measdoc == materialData.pk_measdoc);

                                    detailItem.计量单位 = unitCode.code; // 计量单位
                                }

                                var hsdj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme0w"].ToString());
                                var se = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme10"].ToString());
                                var wsdj = hsdj - se;
                                var sl = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme0x"].ToString());
                                var wsje = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme11"].ToString());
                                var jshj = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme0z"].ToString());

                                // 含税单价
                                detailItem.含税单价 = hsdj.ToString();

                                // 无税单价
                                detailItem.无税单价 = wsdj.ToString();

                                //  含税净价
                                detailItem.含税净价 = hsdj.ToString();

                                // 无税净价
                                detailItem.无税净价 = wsdj.ToString();

                                // 税额
                                detailItem.税额 = se.ToString();

                                // 无税金额
                                detailItem.无税金额 = wsje.ToString();

                                // 数量
                                detailItem.数量 = sl.ToString();

                                // 价税合计
                                detailItem.价税合计 = jshj.ToString();

                                detailItem.换算率 = "1.00/1.00";
                                detailItem.税码 = "CN04"; // 税率码 
                                detailItem.税率 = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme0y"].ToString()).ToString(); // 税率

                                detailItem.开票内容 = ((Dictionary<string, object>)objItem)["textField_lvdnme0u"].ToString();

                                detailItem.行id = ((Dictionary<string, object>)objItem)["textField_lvdojfus"].ToString();

                                detailList.Add(detailItem);
                            }
                        }
                    }
                }
                #endregion

                var 旧发票号 = ydDataSource["textField_lvd8pp35"].ToString();
                var 新发票号 = ydDataSource["textField_lwsth4o3"].ToString();

                foreach (var detailItem in detailList)
                {
                    // 替换明细中，开票内容字段中的发票号
                    detailItem.开票内容 = detailItem.开票内容.Replace(旧发票号, 新发票号);

                    // 将金额和数量都改为负数
                    detailItem.数量 = "-" + detailItem.数量;

                    detailItem.含税单价 = "-" + detailItem.含税单价;
                    detailItem.无税单价 = "-" + detailItem.无税单价;
                    detailItem.含税净价 = "-" + detailItem.含税净价;
                    detailItem.无税净价 = "-" + detailItem.无税净价;
                    detailItem.税额 = "-" + detailItem.税额;
                    detailItem.无税金额 = "-" + detailItem.无税金额;
                    detailItem.价税合计 = "-" + detailItem.价税合计;
                }

                dataSource.明细 = detailList;

                dataSource.数量 = dataSource.明细.Sum(s => Convert.ToDecimal(s.数量)).ToString();
                dataSource.价税合计 = dataSource.明细.Sum(s => Convert.ToDecimal(s.价税合计)).ToString();

                // 销售订单主表id
                var csaleorderid = ydDataSource["textField_ltxyt75m"].ToString();

                // -------------------------------销售订单同步完，开始同步销售发票

                var saleorderData = _db_nc.Queryable<so_saleorder>().First(f => f.csaleorderid == csaleorderid);
                var saleorderbData = _db_nc.Queryable<so_saleorder_b>().Where(f => f.csaleorderid == csaleorderid).ToList();

                dataSource.销售订单单据号 = saleorderData.vbillcode;
                dataSource.销售订单主表id = saleorderData.csaleorderid;

                foreach (var detailItem in dataSource.明细)
                {
                    detailItem.销售订单子表id = saleorderbData.FirstOrDefault(f => f.vbdef10 == detailItem.行id).csaleorderbid;
                }

                var results_销售发票 = NCImportFunc.NCImport(KP_SyncServiceModel.ImportXml_销售发票.TemplateHeade(), KP_SyncServiceModel.ImportXml_销售发票.Header(dataSource, item + "_tp"), _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 resultdescription_销售发票 = xE_销售发票.Element("sendresult").Element("resultdescription")?.Value;

                if (resultcode_销售发票 == "1")
                {
                    ncResData.Add(new YiDaResDto()
                    {
                        bSuccess = true,
                        ncNo = xE_销售发票.Element("sendresult").Element("content").Value,
                        log = "同步成功！"
                    });
                }
                else
                {
                    ncResData.Add(new YiDaResDto()
                    {
                        bSuccess = false,
                        ncNo = "",
                        log = "同步失败！原因为【" + resultdescription_销售发票 + "】！"
                    });
                }

                // -------------------------------销售发票同步完，开始同步应收  （新版）应收不同步，改为调用审核接口，让NC自动取生成应收单

                var results_销售发票审核 = HttpRequestHelper.ApporeNCCSOBill(xE_销售发票.Element("sendresult").Element("content").Value);

                LogHelper.WriteLog(JsonConvert.SerializeObject(results_销售发票审核), "results_销售发票审核");

                if (results_销售发票审核.state == 0)
                {
                    ncResData.Add(new YiDaResDto()
                    {
                        bSuccess = true,
                        ncNo = "",
                        log = "同步成功！"
                    });
                }
                else
                {
                    ncResData.Add(new YiDaResDto()
                    {
                        bSuccess = false,
                        ncNo = "",
                        log = "同步失败！原因为【" + results_销售发票审核.msg + "】！"
                    });
                }


                var finalResData = new YiDaResDto();

                if (ncResData.FirstOrDefault(f => !f.bSuccess) != null)
                {
                    finalResData.bSuccess = false;
                    finalResData.syncTime = DateTime.Now;
                    finalResData.ncNo = csaleorderid;
                    finalResData.log = string.Join(" || ", ncResData.Select(s => s.log));
                }
                else
                {
                    finalResData.bSuccess = true;
                    finalResData.syncTime = DateTime.Now;
                    finalResData.ncNo = csaleorderid;
                    finalResData.log = string.Join(" || ", ncResData.Select(s => s.log));
                }

                var ydRes = _dingTalkService.UpdateFormDataSyncDataById(finalResData, item);
            }

            #endregion
        }
    }
}
