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 FK_FYBX_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 FK_FYBX_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.GetFormCodeList("");

            var idList = _dingTalkService.GetFormIdList("{\"serialNumberField_lsx02quw\":\"FYBX202408010186\"}");

            LogHelper.WriteLog(JsonConvert.SerializeObject(idList.Count), "idList");

            #region 获取NC中选项数据的Id
            var bd_custclassDic = _db_nc.Queryable<bd_custclass>().ToList();
            var org_orgsDic = _db_nc.Queryable<org_orgs>().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()))
                {
                    continue;
                }

                var ncResData = new List<YiDaResDto>();

                #region 表头

                // 表头
                var dataSource = new FK_FYBX_SyncServiceModel.DataModel();

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

                    var tempData = org_orgsDic.FirstOrDefault(f => f.name == b[0].title);
                    if (tempData != null)
                    {
                        dataSource.组织 = tempData.code; // 组织
                    }
                }

                dataSource.支付人 = "OA-NC";

                if (ydDataSource.FirstOrDefault(f => f.Key == "dateField_lsx0pirp").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["dateField_lsx0pirp"].ToString()))
                {
                    dataSource.支付日期 = UnixTimeHelper.ConvertMillisecondsToDateTime(Convert.ToInt64(ydDataSource["dateField_lsx0pirp"].ToString())).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    var resData = new YiDaResDto();
                    resData.bSuccess = false;
                    resData.syncTime = DateTime.Now;
                    resData.ncNo = "";
                    resData.log = "付款银行账户为空，NC无法执行审批操作";

                    _dingTalkService.UpdateFormDataSyncDataById(resData, item);

                    continue;
                }

                dataSource.创建人 = "OA-NC";
                dataSource.制单人 = "OA-NC";
                dataSource.单据日期 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                dataSource.生效人 = "OA-NC";
                dataSource.生效日期 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                // dataSource.发票号 = ydDataSource["textField_lw7erc7d"].ToString();
                dataSource.付款银行账户 = ydDataSource["textField_lsx02qvj"].ToString().Trim().Replace(" ", "");

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

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

                // 价税合计

                #endregion

                var detailList = new List<FK_FYBX_SyncServiceModel.DataModel.Item>();

                #region 明细
                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lrngrtgu").Value != null)
                {
                    var detailObjList1 = (List<object>)ydDataSource["tableField_lrngrtgu"]; // 付款明细

                    if (detailObjList1.Count() > 0 && !string.IsNullOrWhiteSpace(((Dictionary<string, object>)detailObjList1.FirstOrDefault())["numberField_lrnh633o"].ToString()))
                    {
                        foreach (var objItem in detailObjList1)
                        {
                            var detailItem = new FK_FYBX_SyncServiceModel.DataModel.Item();

                            var hsje = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lrnh633o"].ToString());

                            decimal se = 0;

                            if (((Dictionary<string, object>)objItem).FirstOrDefault(f => f.Key == "numberField_lrnh633p").Value != null)
                            {
                                se = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lrnh633p"].ToString());
                            }

                            decimal wsje = 0;

                            if (((Dictionary<string, object>)objItem).FirstOrDefault(f => f.Key == "numberField_lrnh633q").Value != null)
                            {
                                wsje = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lrnh633q"].ToString());
                            }

                            // 含税金额
                            detailItem.价税合计 = hsje.ToString();

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

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

                            detailItem.摘要 = ((Dictionary<string, object>)objItem)["textField_lrngrtgy"].ToString();

                            detailItem.科目 = ((Dictionary<string, object>)objItem)["textField_lrnh633r"].ToString();

                            if (((Dictionary<string, object>)objItem).FirstOrDefault(f => f.Key == "textField_ly7257rx").Value != null)
                            {
                                var a = ((Dictionary<string, object>)objItem)["textField_ly7257rx"].ToString();
                                if (a.Contains("PM"))
                                    detailItem.项目 = a;
                                else
                                    detailItem.部门 = a;
                            }

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

                if (detailList.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.项目)) == null && detailList.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.部门)) == null)
                {
                    var resData = new YiDaResDto();
                    resData.bSuccess = false;
                    resData.syncTime = DateTime.Now;
                    resData.ncNo = "";
                    resData.log = "明细行中项目或部门ID为空";

                    _dingTalkService.UpdateFormDataSyncDataById(resData, item);

                    continue;
                }

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

                var invNumList = new List<string>();

                #region 发票明细（用于拼接发票号）
                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lvuaqzva").Value != null)
                {
                    var detailObjList1 = (List<object>)ydDataSource["tableField_lvuaqzva"];

                    if (detailObjList1.Count() > 0 && !string.IsNullOrWhiteSpace(((Dictionary<string, object>)detailObjList1.FirstOrDefault())["textField_lvuaqzvb"].ToString()))
                    {
                        foreach (var objItem in detailObjList1)
                        {
                            invNumList.Add(((Dictionary<string, object>)objItem)["textField_lvuaqzvb"].ToString());
                        }
                    }
                }
                #endregion

                if (invNumList.Count > 0)
                {
                    dataSource.发票号 = string.Join(",", invNumList);

                    if (dataSource.发票号.Length >= 101)
                        dataSource.发票号 = dataSource.发票号.Substring(1, 100);
                }

                var results = NCImportFunc.NCImport(FK_FYBX_SyncServiceModel.ImportXml.TemplateHeade(), FK_FYBX_SyncServiceModel.ImportXml.Header(dataSource, item + "fybx"), _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 = "同步成功！"
                    });

                    var recitemData = _db_nc.Queryable<ap_payitem>().Where(w => w.pk_paybill == xE.Element("sendresult").Element("content").Value).ToList();

                    foreach (var recitem in recitemData)
                    {
                        var a = dataSource.明细.FirstOrDefault(f => f.无税金额 == recitem.def11);

                        recitem.scomment = a.摘要;

                        _db_nc.Updateable(recitem).ExecuteCommand();
                    }
                }
                else
                {
                    ncResData.Add(new YiDaResDto()
                    {
                        bSuccess = false,
                        ncNo = "",
                        log = "同步失败！原因为【" + resultdescription + "】！"
                    });
                }

                var results_付款单审核 = HttpRequestHelper.ApproveNCFKBill(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 = xE.Element("sendresult").Element("content").Value;
                    finalResData.log = string.Join(" || ", ncResData.Select(s => s.log));
                }
                else
                {
                    finalResData.bSuccess = true;
                    finalResData.syncTime = DateTime.Now;
                    finalResData.ncNo = xE.Element("sendresult").Element("content").Value;
                    finalResData.log = string.Join(" || ", ncResData.Select(s => s.log));
                }

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