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 CGDD_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_po_order_bb = ConfigurationManager.AppSettings["po_order_bb"];

        public CGDD_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 void DataSync()
        {
            DingTalkService _dingTalkService = new DingTalkService(_AppType, _SystemToken, _UserId, _FormId);

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

            //var idList = _dingTalkService.GetFormIdList();

            // var idList = _dingTalkService.GetFormIdList("{\"textField_lr26y1io\":\"TESTDD202505200001\"}");

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




            // 获取当前最大Id
            var newId = 100000001;
            var maxData = _db_nc.Queryable<po_order_bb>().Where(w => w.pk_order_bb.Contains(_Static_PK_po_order_bb)).OrderByDescending(obd => obd.pk_order_bb).First();
            if (maxData != null && maxData.pk_order_bb.Contains(_Static_PK_po_order_bb))
            {
                newId = Convert.ToInt32(maxData.pk_order_bb.Replace(_Static_PK_po_order_bb, "")) + 1;
            }

            #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();
            #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()))
                {
                    LogHelper.WriteLog("", "有NC单据号，需走修订流程，此时跳过：" + ydDataSource.FirstOrDefault(f => f.Key == "textField_ltxyt75m").Value);
                    continue;
                }

                var dataSource = new CGDD_SyncServiceModel.DataModel();
                dataSource.集团 = "0";

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

                dataSource.订单编号 = ydDataSource["textField_lr26y1io"].ToString();
                dataSource.订单日期 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                dataSource.供应商 = ydDataSource["textField_lr26l3hf"].ToString();

                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");

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

                var detailObjList = (List<object>)ydDataSource["tableField_ltxyt76f"]; // 采购物耗明细
                foreach (var objItem in detailObjList)
                {
                    var detailItem = new CGDD_SyncServiceModel.DataModel.OrderB();

                    detailItem.数量 = ((Dictionary<string, object>)objItem)["numberField_ltxyt75z"].ToString(); // 主数量

                    if (detailItem.数量 == "0")
                    {
                        continue;
                    }

                    detailItem.物料编码 = ((Dictionary<string, object>)objItem)["textField_ltxyt75w"].ToString(); // 物料编码
                    // detailItem.物料名称 = ((Dictionary<string, object>)objItem)["textField_ltxyt75x"].ToString(); // 物料编码

                    if (!string.IsNullOrWhiteSpace(((Dictionary<string, object>)objItem)["textField_ltxyt75y"].ToString()))
                    {
                        DBHelper.WriteLog(((Dictionary<string, object>)objItem)["textField_ltxyt75y"].ToString(), "计量单位");
                        detailItem.计量单位 = bd_measdocDic.FirstOrDefault(f => f.name.Trim() == ((Dictionary<string, object>)objItem)["textField_ltxyt75y"].ToString().Trim()).code; // 计量单位
                    }

                    detailItem.项目 = ((Dictionary<string, object>)objItem)["textField_lu23oe2w"].ToString(); // 项目编码

                    detailItem.无税单价 = ((Dictionary<string, object>)objItem)["numberField_lutkmlw0"].ToString(); // 本币无税单价

                    detailItem.含税单价 = ((Dictionary<string, object>)objItem)["numberField_ltxyt761"].ToString(); // 含税单价

                    detailItem.无税金额 = ((Dictionary<string, object>)objItem)["numberField_lutkmlvz"].ToString(); // 无税金额

                    detailItem.税额 = ((Dictionary<string, object>)objItem)["numberField_lutkmlw3"].ToString(); // 税额

                    detailItem.价税合计 = ((Dictionary<string, object>)objItem)["numberField_ltxyt764"].ToString(); // 本币价税合计

                    detailItem.联系人 = ((Dictionary<string, object>)objItem)["textField_lutkmlwb"].ToString(); // 

                    detailItem.收货地址 = ((Dictionary<string, object>)objItem)["textField_ltxyt76a"].ToString(); // 

                    detailList.Add(detailItem);
                }

                dataSource.pk_order_b = detailList;


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



                var results = NCImportFunc.NCImport(CGDD_SyncServiceModel.ImportXml.TemplateHeade(), CGDD_SyncServiceModel.ImportXml.Header(dataSource, item), _NCApiUrl + "?account=LY01&groupcode=0");

                DBHelper.WriteLog(results);
                XElement xE = XElement.Parse(results);

                string resultcode = xE.Element("sendresult").Element("resultcode").Value;

                DBHelper.WriteLog($"状态码:" + resultcode);

                string content = xE.Element("sendresult").Element("content")?.Value;

                string resultdescription = xE.Element("sendresult").Element("resultdescription")?.Value;

                var ncResData = new YiDaResDto()
                {
                    syncTime = DateTime.Now,
                };

                // NC接口执行完成后的处理
                if (resultcode == "1")
                {
                    DBHelper.WriteLog($"Id为【{JsonConvert.SerializeObject(item)}】的单据操作成功!");

                    ncResData.bSuccess = true;
                    ncResData.ncNo = xE.Element("sendresult").Element("content").Value;
                    ncResData.log = "同步成功！";

                    // 更新审核状态，并插入在途状态表
                    var po_order = _db_nc.Queryable<po_order>().First(f => f.pk_order == xE.Element("sendresult").Element("content").Value);
                    var po_order_b = _db_nc.Queryable<po_order_b>().Where(w => w.pk_order == xE.Element("sendresult").Element("content").Value).ToList();

                    po_order.approver = "1001G1100000000B6553";
                    po_order.forderstatus = "3";
                    po_order.taudittime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    _db_nc.Updateable(po_order).ExecuteCommand();

                    foreach (var itemB in po_order_b)
                    {
                        var bb = new po_order_bb();
                        bb.dplanarrvdate = itemB.dplanarrvdate;
                        bb.nmaxhandlenum = itemB.nastnum;
                        bb.nonwaynum = itemB.nastnum;

                        bb.pk_group = itemB.pk_group;
                        bb.pk_order = itemB.pk_order;
                        bb.pk_order_b = itemB.pk_order_b;
                        bb.pk_org = itemB.pk_org;
                        bb.pk_org_v = itemB.pk_org_v;
                        bb.ts = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        bb.pk_order_bb = _Static_PK_po_order_bb + newId;

                        _db_nc.Insertable(bb).ExecuteCommand();

                        newId++;
                    }
                }
                else
                {

                    DBHelper.WriteLog($"Id为【{JsonConvert.SerializeObject(item)}】的单据操作失败!" + resultdescription + ";");

                    ncResData.bSuccess = false;
                    ncResData.ncNo = "";
                    ncResData.log = "同步失败！原因为【" + resultdescription + "】";
                }

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

            #endregion
        }
    }
}
