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_HK_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_HK_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 class DetailItem
        {
            public decimal ncMoney { get; set; }
            public decimal ydMoney { get; set; }
            public long ncBilldate { get; set; }
            public bool bAll { get; set; }
        }

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


            {


                //var idList2= _dingTalkService.GetFormIdList("{\"textField_ltxyt75i\":\"" + "同步完成" + "\"}");
                //foreach (var item in idList2)
                //{
                //    var ydRes1 = _dingTalkService.UpdateFormDataSyncDataByIdOnlyState(item);
                //}
            }


            // 宜搭全量数据Id
            //var idList = _dingTalkService.GetFormIdList("{\"radioField_lycrvvtk\":\"Y\",\"selectField_lvituew9\":\"正常\"}");
            //var idList = _dingTalkService.GetFormIdList("{\"textField_lvdosccc\":\"KP_2025030300450\"}");

            var idList = _dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"未回款\",\"textField_ltxyt75i\":\"同步成功\"}");
            idList.AddRange(_dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"已回款\",\"textField_ltxyt75i\":\"同步成功\"}"));
            idList.AddRange(_dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"未回款\",\"textField_ltxyt75i\":\"同步失败\"}"));
            idList.AddRange(_dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"已回款\",\"textField_ltxyt75i\":\"同步失败\"}"));

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

            #region 获取NC中选项数据的Id
            var so_saleorder_bList = _db_nc.Queryable<so_saleorder_b>().Where(w => w.vbdef10 != "~" && w.dr == 0).ToList();
            var ar_gatheritemList = _db_nc.Queryable<ar_gatheritem>().Where(w => so_saleorder_bList.Select(s => s.csaleorderbid).ToList().Contains(w.src_itemid)).ToList();
            var ar_gatherbillList = _db_nc.Queryable<ar_gatherbill>().Where(w => ar_gatheritemList.Select(s => s.pk_gatherbill).ToList().Contains(w.pk_gatherbill) && w.billstatus == "1").Select(s => s.pk_gatherbill).ToList();
            #endregion

            var i = 1;

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

                LogHelper.WriteLog("", "【序号 " + i + " / " + idList.Count + "】" + item + " 开始回写");
                i++;

                var updateData = new Dictionary<string, string>();
                var detailData = new List<DetailItem>();

                #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()))
                        {
                            var bChange = false;
                            foreach (var objItem in detailObjList1)
                            {
                                var rowId = ((Dictionary<string, object>)objItem)["textField_lvdojfup"].ToString();

                                var sbData = so_saleorder_bList.Where(f => f.vbdef10 == rowId);
                                if (sbData != null)
                                {
                                    var giData = ar_gatheritemList.Where(w => sbData.Select(s => s.csaleorderbid).ToList().Contains(w.src_itemid) && ar_gatherbillList.Contains(w.pk_gatherbill)).ToList();
                                    if (giData.Count > 0)
                                    {
                                        var ncMoney = giData.Sum(s => s.money_cr);
                                        var ydMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp2y"].ToString());

                                        decimal ydReMoney = 0;
                                        object ydReMoney_;

                                        if (((Dictionary<string, object>)objItem).TryGetValue("numberField_lvg084lb", out ydReMoney_))
                                        {
                                            ydReMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvg084lb"].ToString());
                                        }

                                        var ncBilldate = UnixTimeHelper.ConvertToMilliseconds(Convert.ToDateTime(giData.OrderByDescending(ob => Convert.ToDateTime(ob.billdate)).FirstOrDefault().billdate));

                                        //var detailItem = new DetailItem()
                                        //{
                                        //    ncMoney = (ncMoney + ydReMoney) > ydMoney ? ydMoney : (ncMoney + ydReMoney),
                                        //    ydMoney = ydMoney,
                                        //    ncBilldate = ncBilldate,
                                        //    bAll = ((ncMoney + ydReMoney) >= ydMoney)
                                        //};

                                        var detailItem = new DetailItem()
                                        {
                                            ncMoney = ncMoney > ydMoney ? ydMoney : ncMoney,
                                            ydMoney = ydMoney,
                                            ncBilldate = ncBilldate,
                                            bAll = ncMoney >= ydMoney
                                        };

                                        detailData.Add(detailItem);

                                        ((Dictionary<string, object>)objItem)["numberField_lvg084lb"] = (detailItem.ncMoney).ToString("#0.00");
                                        ((Dictionary<string, object>)objItem)["dateField_m0f55roc"] = ncBilldate.ToString();

                                        bChange = true;
                                    }
                                }
                            }

                            if (bChange)
                                updateData.Add("tableField_lvc9x4vt", JsonConvert.SerializeObject(detailObjList1));
                        }
                    }
                }
                #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()))
                        {
                            var bChange = false;
                            foreach (var objItem in detailObjList2)
                            {
                                var rowId = ((Dictionary<string, object>)objItem)["textField_lvdojfur"].ToString();

                                var sbData = so_saleorder_bList.Where(f => f.vbdef10 == rowId);
                                if (sbData != null)
                                {
                                    var giData = ar_gatheritemList.Where(w => sbData.Select(s => s.csaleorderbid).ToList().Contains(w.src_itemid) && ar_gatherbillList.Contains(w.pk_gatherbill)).ToList();
                                    if (giData.Count > 0)
                                    {
                                        var ncMoney = giData.Sum(s => s.money_cr);
                                        var ydMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvd8pp41"].ToString());

                                        decimal ydReMoney = 0;
                                        object ydReMoney_;

                                        if (((Dictionary<string, object>)objItem).TryGetValue("numberField_lvg084l9", out ydReMoney_))
                                        {
                                            ydReMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvg084l9"].ToString());
                                        }

                                        var ncBilldate = UnixTimeHelper.ConvertToMilliseconds(Convert.ToDateTime(giData.OrderByDescending(ob => Convert.ToDateTime(ob.billdate)).FirstOrDefault().billdate));

                                        //var detailItem = new DetailItem()
                                        //{
                                        //    ncMoney = (ncMoney + ydReMoney) > ydMoney ? ydMoney : (ncMoney + ydReMoney),
                                        //    ydMoney = ydMoney,
                                        //    ncBilldate = ncBilldate,
                                        //    bAll = ((ncMoney + ydReMoney) >= ydMoney)
                                        //};

                                        var detailItem = new DetailItem()
                                        {
                                            ncMoney = ncMoney > ydMoney ? ydMoney : ncMoney,
                                            ydMoney = ydMoney,
                                            ncBilldate = ncBilldate,
                                            bAll = ncMoney >= ydMoney
                                        };

                                        detailData.Add(detailItem);

                                        ((Dictionary<string, object>)objItem)["numberField_lvg084l9"] = (detailItem.ncMoney).ToString("#0.00");
                                        ((Dictionary<string, object>)objItem)["dateField_m0dp1g0e"] = ncBilldate.ToString();

                                        bChange = true;
                                    }
                                }
                            }

                            if (bChange)
                                updateData.Add("tableField_lvd8pp44", JsonConvert.SerializeObject(detailObjList2));
                        }
                    }
                }
                #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()))
                        {
                            var bChange = false;
                            foreach (var objItem in detailObjList3)
                            {
                                var rowId = ((Dictionary<string, object>)objItem)["textField_lvdojfus"].ToString();

                                var sbData = so_saleorder_bList.Where(f => f.vbdef10 == rowId);
                                if (sbData != null)
                                {
                                    var giData = ar_gatheritemList.Where(w => sbData.Select(s => s.csaleorderbid).ToList().Contains(w.src_itemid) && ar_gatherbillList.Contains(w.pk_gatherbill)).ToList();
                                    if (giData.Count > 0)
                                    {
                                        var ncMoney = giData.Sum(s => s.money_cr);
                                        var ydMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvdnme0z"].ToString());

                                        decimal ydReMoney = 0;
                                        object ydReMoney_;

                                        if (((Dictionary<string, object>)objItem).TryGetValue("numberField_lvg084la", out ydReMoney_))
                                        {
                                            ydReMoney = Convert.ToDecimal(((Dictionary<string, object>)objItem)["numberField_lvg084la"].ToString());
                                        }

                                        var ncBilldate = UnixTimeHelper.ConvertToMilliseconds(Convert.ToDateTime(giData.OrderByDescending(ob => Convert.ToDateTime(ob.billdate)).FirstOrDefault().billdate));

                                        //var detailItem = new DetailItem()
                                        //{
                                        //    ncMoney = (ncMoney + ydReMoney) > ydMoney ? ydMoney : (ncMoney + ydReMoney),
                                        //    ydMoney = ydMoney,
                                        //    ncBilldate = ncBilldate,
                                        //    bAll = ((ncMoney + ydReMoney) >= ydMoney)
                                        //};

                                        var detailItem = new DetailItem()
                                        {
                                            ncMoney = ncMoney > ydMoney ? ydMoney : ncMoney,
                                            ydMoney = ydMoney,
                                            ncBilldate = ncBilldate,
                                            bAll = ncMoney >= ydMoney
                                        };

                                        detailData.Add(detailItem);

                                        ((Dictionary<string, object>)objItem)["numberField_lvg084la"] = (detailItem.ncMoney).ToString("#0.00");
                                        ((Dictionary<string, object>)objItem)["dateField_m0f55roe"] = ncBilldate.ToString();

                                        bChange = true;
                                    }
                                }
                            }

                            if (bChange)
                                updateData.Add("tableField_lvdnme13", JsonConvert.SerializeObject(detailObjList3));
                        }
                    }
                }
                #endregion

                if (detailData.Count > 0)
                {
                    // 回款时间
                    updateData.Add("dateField_m0f5xiio", detailData.OrderByDescending(ob => ob.ncBilldate).FirstOrDefault().ncBilldate.ToString());

                    // 已回款金额
                    updateData.Add("numberField_m0f55roa", detailData.Sum(s => s.ncMoney).ToString("#0.00"));

                    // 回款状态
                    updateData.Add("radioField_m06hhw2p", detailData.FirstOrDefault(f => !f.bAll) != null ? "已回款" : "回款完成");

                    LogHelper.WriteLog(JsonConvert.SerializeObject(updateData), "数据构建完成");

                    // 回传状态
                    updateData.Add("radioField_m4253oqe", "N");
                    // 回传状态
                    updateData.Add("textField_m4253oqd", "回传成功");


                    var ydRes = _dingTalkService.UpdateFormDataById(updateData, item);

                    LogHelper.WriteLog(JsonConvert.SerializeObject(ydRes), "ydRes 回写完成------------------------------------------------");
                }
                else
                {
                    LogHelper.WriteLog("无回款记录", "回写完成------------------------------------------------");
                }
            }

            #endregion
        }
    }
}
