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

            {
                var codeList = new string[] { "KH01748" };
                var ncNo = new string[] { "1001G1100000000F2XJU" };

                for (int i = 0; i < codeList.Count(); i++)
                {
                    var idList1 = _dingTalkService.GetFormIdList("{\"serialNumberField_ls14do3x\":\"" + codeList[i] + "\"}");

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

                    ncResData1.bSuccess = true;
                    ncResData1.ncNo = ncNo[i];//1001G1100000000DVG2J    1001G1100000000DVG3B
                    ncResData1.log = "同步成功！";

                    var ydRes1 = _dingTalkService.UpdateFormDataSyncDataById(ncResData1, idList1.FirstOrDefault());
                }
            }


            {
                //var codeList = new string[] { "KH01717" };

                //for (int i = 0; i < codeList.Count(); i++)
                //{
                //    var idList1 = _dingTalkService.GetFormIdList("{\"serialNumberField_ls14do3x\":\"" + codeList[i] + "\"}");

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

                //    ncResData1.bSuccess = false;
                //    ncResData1.ncNo = "";
                //    ncResData1.log = "同步失败！【纳税人识别号已存在】";

                //    var ydRes1 = _dingTalkService.UpdateFormDataSyncDataById(ncResData1, idList1.FirstOrDefault());
                //}
            }



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

            ////var idList = _dingTalkService.GetFormIdList("{\"radioField_lycrvvtk\":\"Y\"}");

            ////// 获取当前最大Id
            ////var newId = 100000001;
            ////var maxData = _db_nc.Queryable<bd_project>().OrderByDescending(obd => Convert.ToDateTime(obd.creationtime)).First();
            ////if (maxData != null && maxData.pk_project.Contains(_Static_PK_bd_project))
            ////{
            ////    newId = Convert.ToInt32(maxData.pk_project.Replace(_Static_PK_bd_project, "")) + 1;
            ////}

            //#region 获取NC中选项数据的Id
            //var bd_custclassDic = _db_nc.Queryable<bd_custclass>().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<KH_SyncServiceModel.DataModel.SuplinkmanItem>();

            ////    var suplinkmanObjList = new List<object>();

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

            ////    foreach (var objItem in suplinkmanObjList)
            ////    {
            ////        suplinkmanDataList.Add(new KH_SyncServiceModel.DataModel.SuplinkmanItem()
            ////        {
            ////            name = ((Dictionary<string, object>)objItem)["textField_lrhhdm5n"].ToString(),
            ////            cell = ((Dictionary<string, object>)objItem)["textField_lrhhdm5o"].ToString(),
            ////            vjob = ((Dictionary<string, object>)objItem)["textField_lrhhdm5p"].ToString()
            ////        });
            ////    }


            ////    var dataSource = new KH_SyncServiceModel.DataModel()
            ////    {
            ////        pk_group = "0",
            ////        pk_org = "0",
            ////        code = ydDataSource["serialNumberField_ls14do3x"].ToString(),
            ////        name = ydDataSource["textField_lr25icbn"].ToString(),
            ////        taxpayerid = ydDataSource["textField_lt425f37"].ToString(),
            ////        custprop = "0",

            ////    };

            ////    if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lrrdx03y").Value != null)
            ////    {
            ////        if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lrrdx03y"].ToString()))
            ////        {
            ////            var a = bd_custclassDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lrrdx03y"].ToString());
            ////            if (a != null)
            ////                dataSource.pk_custclass = a.code; // 分类s
            ////        }
            ////    }

            ////    dataSource.suplinkman = suplinkmanDataList;

            ////    var xmlData = KH_SyncServiceModel.ImportXml.Header(dataSource, item);

            ////    XElement tempData = KH_SyncServiceModel.ImportXml.TemplateHeade();

            ////    var results = NCImportFunc.NCImport(tempData, xmlData, _NCApiUrl + "?account=01&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 = "同步成功！";
            ////    }
            ////    else
            ////    {
            ////        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

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

            //ncResData.bSuccess = true;
            //ncResData.ncNo = "1001G1100000000DVKOQ";//1001G1100000000DVG2J    1001G1100000000DVG3B
            //ncResData.log = "同步成功！";

            //var ydRes = _dingTalkService.UpdateFormDataSyncDataById(ncResData, idList.FirstOrDefault());
        }
    }
}
