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 GYS_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_xx_idcontrast = ConfigurationManager.AppSettings["xx_idcontrast"];
        public static string _Static_pk_org_jt = ConfigurationManager.AppSettings["pk_org_jt"];

        public GYS_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();

            // NC ID对照表数据
            var ncDataIdList = _db_nc.Queryable<xx_idcontrast>().Where(w => w.bill_type == "supplier").ToList();

            // 获取当前最大Id
            var newId = 100000001;
            var maxData = ncDataIdList.OrderByDescending(obd => Convert.ToDateTime(obd.ts)).FirstOrDefault();
            if (maxData != null && maxData.pk_idcontra.Contains(_Static_PK_xx_idcontrast))
            {
                newId = Convert.ToInt32(maxData.pk_idcontra.Replace(_Static_PK_xx_idcontrast, "")) + 1;
            }

            #region 获取NC中选项数据的Id
            var pk_supplierclassDic = _db_nc.Queryable<bd_supplierclass>().ToList();
            #endregion

            #region 循环数据处理业务逻辑
            // 向NC插入数据
            foreach (var item in idList)
            {
                string createTime = "";
                string modifyTime = "";

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

                var suplinkmanDataList = new List<GYS_SyncServiceModel.DataModel.SuplinkmanItem>();

                //tableField_lrn5j23r

                var suplinkmanObjList = new List<object>();

                if (ydDataSource.FirstOrDefault(f => f.Key == "tableField_lrn5j24e").Value != null)
                    suplinkmanObjList = (List<object>)ydDataSource["tableField_lrn5j24e"];

                foreach (var objItem in suplinkmanObjList)
                {
                    suplinkmanDataList.Add(new GYS_SyncServiceModel.DataModel.SuplinkmanItem()
                    {
                        name = ((Dictionary<string, object>)objItem)["textField_lrn5j244"].ToString(),
                        cell = ((Dictionary<string, object>)objItem)["textField_lrn5j245"].ToString(),
                    });
                }


                var dataSource = new GYS_SyncServiceModel.DataModel()
                {
                    pk_group = "0",
                    pk_org = "0",
                    code = ydDataSource["textField_lrhgjspd"].ToString(),
                    name = ydDataSource["textField_lrhgjspc"].ToString(),
                    taxpayerid = ydDataSource["textField_lrhgjspr"].ToString(),
                };

                if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lrn5j22q"].ToString()))
                {
                    var a = pk_supplierclassDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lrn5j22q"].ToString());
                    if (a != null)
                        dataSource.pk_supplierclass = a.code; // 分类s
                }
                if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lrn5j22p"].ToString()))
                {

                    switch (ydDataSource["selectField_lrn5j22p"].ToString())
                    {
                        case "启用":
                            dataSource.enablestate = ((int)EnumType.enablestate.已启用).ToString();
                            break;
                        case "未启用":
                            dataSource.enablestate = ((int)EnumType.enablestate.已停用).ToString();
                            break;
                    }
                }

                dataSource.suplinkman = suplinkmanDataList;

                var xmlData = GYS_SyncServiceModel.ImportXml.Header(dataSource, item);
                XElement tempData = GYS_SyncServiceModel.ImportXml.TemplateHeade();

                var results = NCImportFunc.NCImport(tempData, xmlData, _NCApiUrl + "?account=01&groupcode=0");

                XElement xE = XElement.Parse(results);
                string resultcode = xE.Element("sendresult").Element("resultcode").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 = "同步成功！";
                }
                else
                {
                    if (resultdescription.Contains("不允许重复"))
                    {
                        // 已存在数据，绑定Id
                        var nowData = _db_nc.Queryable<bd_supplier>().First(f => f.code == dataSource.code && f.pk_org == _Static_pk_org_jt);

                        var idcData = new xx_idcontrast()
                        {
                            bill_type = "supplier",
                            dr = 0,
                            file_id = item,
                            pk_bill = nowData.pk_supplier,
                            pk_idcontra = _Static_PK_xx_idcontrast + newId
                        };
                        _db_nc.Insertable(idcData).ExecuteCommand();

                        newId++;

                        ncResData.bSuccess = true;
                        ncResData.ncNo = nowData.pk_supplier;
                        ncResData.log = "数据已存在，无需同步，已自动对照！";
                    }
                    else
                    {
                        DBHelper.WriteLog($"Id为【{JsonConvert.SerializeObject(item)}】的单据操作失败!" + resultdescription + ";");

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


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

                    //if (resultdescription.Contains("不允许重复"))
                    //{
                    //    ncResData.bSuccess = true;
                    //    ncResData.ncNo = "";
                    //    ncResData.log = "数据已存在，无需同步！";
                    //}
                    //else
                    //{
                    //    ncResData.bSuccess = false;
                    //    ncResData.ncNo = "";
                    //    ncResData.log = "同步失败！原因为【" + resultdescription + "】";
                    //}
                }

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