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 WL_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 WL_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()
        {
            DBHelper.WriteLog($"进入程序");

            DingTalkService _dingTalkService = new DingTalkService(_AppType, _SystemToken, _UserId, _FormId);

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

            DBHelper.WriteLog(JsonConvert.SerializeObject(idList), "idList");

            // NC ID对照表数据
            var ncDataIdList = _db_nc.Queryable<xx_idcontrast>().Where(w => w.bill_type == "material").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_marbasclassDic = _db_nc.Queryable<bd_marbasclass>().ToList();
            var pk_measdocDic = _db_nc.Queryable<bd_measdoc>().ToList();
            var pk_mattaxesDic = _db_nc.Queryable<bd_mattaxes>().ToList();
            var pk_brandDic = _db_nc.Queryable<bd_branddoc>().ToList();
            #endregion

            #region 循环数据处理业务逻辑
            foreach (var item in idList.Where(w => !ncDataIdList.Select(s => s.file_id).ToList().Contains(w)))
            {

                DBHelper.WriteLog($"进入程序1");

                // 获取此条数据详情
                string createTime = "";
                string modifyTime = "";
                var ydDataSource = _dingTalkService.GetFormDataById(item, out createTime, out modifyTime);


                DBHelper.WriteLog(ydDataSource["radioField_lycrvvtk"].ToString(), "222");

                if (ydDataSource["radioField_lycrvvtk"].ToString() == "Y")
                {
                    DBHelper.WriteLog($"进入程序2");

                    #region 构建数据体
                    var dataSource = new WL_SyncServiceModel.DataModel()
                    {
                        pk_group = "0",
                        pk_org = "0",
                        code = ydDataSource["textField_lr3axfje"].ToString(),
                        name = ydDataSource["textField_lr383i4h"].ToString(),
                        ename = ydDataSource["textField_lwitq6vu"].ToString(),

                        materialshortname = ydDataSource["textField_lwitq6vv"].ToString(),
                        materialspec = ydDataSource["textField_ltxy3kh3"].ToString(),
                        materialtype = ydDataSource["textField_ltxy3kh4"].ToString(),
                        ematerialspec = ydDataSource["textField_lwitq6vw"].ToString(),
                        materialmnecode = ydDataSource["textField_lwitq6vx"].ToString(),
                    };

                    if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lwitq6w4").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["selectField_lwitq6w4"].ToString()))
                    {
                        var data = pk_marbasclassDic.FirstOrDefault(f => f.name.Trim() == ydDataSource["selectField_lwitq6w4"].ToString());
                        if (data != null)
                        {
                            dataSource.pk_marbasclass = data.code; // 分类
                        }
                    }
                    else
                    {
                        var resData = new YiDaResDto();
                        resData.bSuccess = false;
                        resData.syncTime = DateTime.Now;
                        resData.ncNo = "";
                        resData.log = "物料分类为空，无法传入NC";

                        _dingTalkService.UpdateFormDataSyncDataById(resData, item);

                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lwitq6w5"].ToString()))
                    {
                        dataSource.pk_measdoc = pk_measdocDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lwitq6w5"].ToString()).code; // 主计量单位
                    }

                    if (ydDataSource.FirstOrDefault(f => f.Key == "selectField_lwitq6w6").Value != null && !string.IsNullOrWhiteSpace(ydDataSource["selectField_lwitq6w6"].ToString()))
                    {
                        dataSource.pk_mattaxes = pk_mattaxesDic.FirstOrDefault(f => f.mattaxesname == ydDataSource["selectField_lwitq6w6"].ToString()).mattaxescode; // 税类
                    }
                    //if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_lwitq6we"].ToString()))
                    //{
                    //    dataSource.pk_brand = pk_brandDic.FirstOrDefault(f => f.name == ydDataSource["selectField_lwitq6we"].ToString()).code; // 品牌
                    //}
                    if (!string.IsNullOrWhiteSpace(ydDataSource["selectField_ltxy3kh6"].ToString()))
                    {

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

                    #region 数据传入NC并获取结果
                    var xmlData = WL_SyncServiceModel.ImportXml.Header(dataSource, item);
                    XElement tempData = WL_SyncServiceModel.ImportXml.TemplateHeade();

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

                    DBHelper.WriteLog($"进入程序3");

                    XElement xE = XElement.Parse(results);
                    string resultcode = xE.Element("sendresult").Element("resultcode").Value;
                    string resultdescription = xE.Element("sendresult").Element("resultdescription")?.Value;
                    #endregion

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

                    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_material>().First(f => f.code == dataSource.code && f.pk_org == _Static_pk_org_jt);

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

                            newId++;

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

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

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