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 XMD_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 XMD_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\",\"textField_ltxrn8h1\":\"PM00408\"}");
            //var idList = _dingTalkService.GetFormIdList("");

            // 获取当前最大Id
            var newId = 100000001;
            var maxData = _db_nc.Queryable<bd_project>().OrderByDescending(obd => obd.pk_project).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_projectclassDic = _db_nc.Queryable<bd_projectclass>().ToList();
            var bd_stordocDic = _db_nc.Queryable<bd_stordoc>().ToList();
            #endregion

            #region 循环数据处理业务逻辑
            foreach (var item in idList)
            {
                // 获取此条数据详情
                string createTime = "";
                string modifyTime = "";
                var ydDataSource = _dingTalkService.GetFormDataById(item, out createTime, out modifyTime);

                if (ydDataSource["radioField_lycrvvtk"].ToString() == "Y")
                {

                    #region 构建数据体
                    var data = new bd_project();
                    data.begin_flag = "N";
                    data.bill_type = "4D10";
                    data.creationtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    data.ts = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    data.creator = "1001G1100000000B6553";
                    data.def6 = ydDataSource["textField_lrim7i38"].ToString(); // 项目地址
                    data.def7 = ydDataSource["textField_lrn2oy4n"].ToString(); // 体系
                    data.enablestate = 2;


                    data.pk_eps = "";
                    data.pk_group = _Static_pk_org_jt;
                    data.pk_org = _Static_pk_org_jt;
                    // data.pk_projectclass = "";

                    if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lrhjdu45").Value != null)
                    {
                        if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lrhjdu45"].ToString()))
                        {
                            var tempData = bd_projectclassDic.FirstOrDefault(f => f.type_name == ydDataSource["selectField_lrhjdu45"].ToString());
                            if (tempData != null)
                            {
                                data.pk_projectclass = tempData.pk_projectclass; // 项目类型
                            }
                        }
                    }

                    //if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lrn2oy4c").Value != null)
                    //{
                    //    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lrn2oy4c"].ToString()))
                    //    {
                    //        var tempData = bd_stordocDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lrn2oy4c"].ToString());
                    //        if (tempData != null)
                    //        {
                    //            data.pk_stordoc1 = tempData.pk_stordoc; // 仓库
                    //        }
                    //    }
                    //}

                    data.project_code = ydDataSource["textField_ltxrn8h1"].ToString();
                    data.project_name = ydDataSource["textField_lrr3rg6i"].ToString();
                    data.transi_type = "4D10-01";



                    #endregion

                    #region 数据传入NC并获取结果
                    var nowData = _db_nc.Queryable<bd_project>().First(f => f.project_code == data.project_code);
                    if (nowData == null)
                    {
                        data.pk_project = _Static_PK_bd_project + newId;
                        _db_nc.Insertable(data).ExecuteCommand();

                        newId++;
                    }
                    else
                    {
                        data.pk_project = nowData.pk_project;
                        _db_nc.Updateable(data).ExecuteCommand();
                    }

                    #endregion

                    #region 回写状态
                    var ncResData = new YiDaResDto()
                    {
                        syncTime = DateTime.Now,
                    };

                    DBHelper.WriteLog($"Id为【{JsonConvert.SerializeObject(item)}】的单据操作成功!");

                    ncResData.bSuccess = true;
                    ncResData.ncNo = data.pk_project;
                    ncResData.log = "同步成功！";

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