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 ZC_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_fa_card = ConfigurationManager.AppSettings["fa_card"];
        public static string _Static_pk_org_jt = ConfigurationManager.AppSettings["pk_org_jt"];

        public ZC_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\"}");

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

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

            // 资产部门ID textField_lydsc49c
            // 管理部门ID textField_lydsc49b

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

                #region 构建数据体
                var data = new fa_card();
                data.archarea = 0;
                data.asset_code = ydDataSource["textField_lty0oyv4"].ToString();
                data.asset_name = ydDataSource["textField_lty0oyuj"].ToString();
                data.begin_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.bill_source = "handin";
                data.bill_type = "H1";
                data.billmaker = "1001G110000000000ADH";
                data.billmaketime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.business_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.creationtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.creator = "1001G110000000000ADH";
                data.currmoney = 0;
                data.dismant_cost = 0;
                data.dy_flag = "N";
                data.install_fee = 0;
                data.machinepower = 0;
                data.machinequan = 0;
                data.nettonnage = 0;
                data.other_cost = 0;
                data.pk_group = _Static_pk_org_jt;
                data.pk_org = "0001G110000000001MVP";
                data.pk_org_v = "0001G110000000001MVO";
                data.card_code = "0000001242";
                data.assetsuit_code = "营运部(项目)0354";

                // 主键
                data.pk_currency = "1002Z0100000000001K1";
                data.pk_transitype = "0001G110000000001B48";
                data.transi_type = "H1-00";
                data.ts = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

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

                ncResData.bSuccess = false;
                ncResData.ncNo = "";
                ncResData.log = "同步失败【使用部门为空！】";

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


                if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lwk48b8s").Value != null)
                {
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lwk48b8s"].ToString()))
                    {
                        var tempData = pam_addreducestyleDic.FirstOrDefault(f => f.style_name == ydDataSource["selectField_lwk48b8s"].ToString());
                        if (tempData != null)
                        {
                            data.pk_addreducestyle = tempData.pk_addreducestyle; // 增加方式
                        }
                    }
                }

                #endregion

                #region 数据传入NC并获取结果
                var nowData = _db_nc.Queryable<fa_card>().First(f => f.asset_code == data.asset_code);
                if (nowData == null)
                {
                    data.pk_card = "DINGTALKFAC100000006"; //_Static_PK_fa_card + newId;
                    _db_nc.Insertable(data).ExecuteCommand();

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

                #endregion

            }
#endregion
        }
    }
}
