using HH.YiDaSyncNC.Dtos.NC;
using HH.YiDaSyncNC.Helper;
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 BZJ_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 BZJ_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 idList = _dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"未回款\",\"textField_ltxyt75i\":\"同步成功\"}");
            //idList.AddRange(_dingTalkService.GetFormIdList("{\"radioField_m06hhw2p\":\"已回款\",\"textField_ltxyt75i\":\"同步成功\"}"));

            var idList = _dingTalkService.GetFormIdList("{\"textField_ltxyt75i\":\"同步成功\"}");
            LogHelper.WriteLog(JsonConvert.SerializeObject(idList.Count), "idList");

            #region 获取NC中选项数据的Id
            var ct_bondapplyList = _db_nc.Queryable<ct_bondapply>().Where(w => w.approvestatus != "-1").ToList();
            var ar_gatheritemList = _db_nc.Queryable<ar_gatheritem>().Where(w => ct_bondapplyList.Select(s => s.pk_bondapply).ToList().Contains(w.src_billid)).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;
                }

                // 如果NC单据号为空，说明没有传入过NC，此时跳过
                if (ydDataSource.FirstOrDefault(f => f.Key == "radioField_m06hhw2p").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["radioField_m06hhw2p"].ToString()) && ydDataSource["radioField_m06hhw2p"].ToString() == "回款完成")
                {
                    LogHelper.WriteLog("", "回款完成，跳过");
                    continue;
                }
                else
                {
                    
                }

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

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

                var billno = ydDataSource.FirstOrDefault(f => f.Key == "textField_ltxyt75m").Value.ToString();

                LogHelper.WriteLog(billno, "billno");
                LogHelper.WriteLog(JsonConvert.SerializeObject(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrmz8ehi")), "numberField_lrmz8ehi");
                LogHelper.WriteLog(JsonConvert.SerializeObject(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrpp7wpi")), "numberField_lrpp7wpi");

                #region 履约保证金
                if (ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrmz8ehi").Value != null)
                {
                    var baData = ct_bondapplyList.FirstOrDefault(f => f.billno == billno);

                    LogHelper.WriteLog(JsonConvert.SerializeObject(baData), "baData");

                    var giData = ar_gatheritemList.Where(w => w.src_billid == baData.pk_bondapply && ar_gatherbillList.Contains(w.pk_gatherbill)).ToList();

                    LogHelper.WriteLog(JsonConvert.SerializeObject(giData), "giData");

                    if (giData.Count > 0)
                    {
                        var ncMoney = giData.Sum(s => s.money_cr);


                        var lvMoney = Convert.ToDecimal(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrmz8ehi").Value.ToString());
                        var syMoney = Convert.ToDecimal(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrpp7wph").Value.ToString());

                        LogHelper.WriteLog(JsonConvert.SerializeObject(lvMoney), "lvMoney");
                        LogHelper.WriteLog(JsonConvert.SerializeObject(syMoney), "syMoney");

                        if (ncMoney > lvMoney)
                        {
                            // 当收款 > 保证金总额
                            // 剩余金额 = 0
                            updateData.Add("numberField_lrpp7wph", "0");
                            updateData.Add("radioField_m06hhw2p", "回款完成");
                        }
                        else if (ncMoney == lvMoney)
                        {
                            // 当收款 == 保证金总额
                            // 剩余金额 = 0
                            updateData.Add("numberField_lrpp7wph", "0");
                            updateData.Add("radioField_m06hhw2p", "回款完成");
                        }
                        if (ncMoney < lvMoney && ncMoney != syMoney)
                        {
                            // 当收款 < 保证金总额
                            // 剩余金额 = 保证金总额 - 收款
                            updateData.Add("numberField_lrpp7wph", (lvMoney - ncMoney).ToString("#0.00"));
                            updateData.Add("radioField_m06hhw2p", "已回款");
                        }

                        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
                    {
                        updateData.Add("radioField_m06hhw2p", "未回款");
                        LogHelper.WriteLog("无回款记录", "履约 回写完成------------------------------------------------");
                    }
                }
                #endregion

                #region 投标保证金
                if (ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrpp7wpi").Value != null)
                {
                    var baData = ct_bondapplyList.FirstOrDefault(f => f.billno == billno);

                    LogHelper.WriteLog(JsonConvert.SerializeObject(baData), "baData");

                    var giData = ar_gatheritemList.Where(w => w.src_billid == baData.pk_bondapply && ar_gatherbillList.Contains(w.pk_gatherbill)).ToList();

                    LogHelper.WriteLog(JsonConvert.SerializeObject(giData), "giData");

                    if (giData.Count > 0)
                    {
                        var ncMoney = giData.Sum(s => s.money_cr);


                        var lvMoney = Convert.ToDecimal(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrpp7wpi").Value.ToString());
                        var syMoney = Convert.ToDecimal(ydDataSource.FirstOrDefault(f => f.Key == "numberField_lrpocd42").Value.ToString());

                        if (ncMoney > lvMoney)
                        {
                            // 当收款 > 保证金总额
                            // 剩余金额 = 0
                            updateData.Add("numberField_lrpocd42", "0");
                            updateData.Add("radioField_m06hhw2p", "回款完成");
                        }
                        else if (ncMoney == lvMoney)
                        {
                            // 当收款 == 保证金总额
                            // 剩余金额 = 0
                            updateData.Add("numberField_lrpocd42", "0");
                            updateData.Add("radioField_m06hhw2p", "回款完成");
                        }
                        if (ncMoney < lvMoney && ncMoney != syMoney)
                        {
                            // 当收款 < 保证金总额
                            // 剩余金额 = 保证金总额 - 收款
                            updateData.Add("numberField_lrpocd42", (lvMoney - ncMoney).ToString("#0.00"));
                            updateData.Add("radioField_m06hhw2p", "已回款");
                        }

                        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
                    {
                        updateData.Add("radioField_m06hhw2p", "未回款");
                        LogHelper.WriteLog("无回款记录", "履约 回写完成------------------------------------------------");
                    }
                }
                #endregion
            }

            #endregion
        }

    }
}
