using AlibabaCloud.SDK.Dingtalkyida_1_0.Models;
using HH.YiDaSyncNC.Dtos;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tea;

namespace HH.YiDaSyncNC.Helper
{
    class DingTalkService
    {
        public string _AppType;
        public string _SystemToken;
        public string _UserId;
        public string _FormId;

        public DingTalkService(string AppType, string SystemToken, string UserId, string FormId)
        {
            _AppType = AppType;
            _SystemToken = SystemToken;
            _UserId = UserId;
            _FormId = FormId;
        }

        #region 封装后的宜搭接口

        #region 获取表单Id集合
        public List<string> GetFormIdList()
        {
            var pageIndex = 1;
            var pageSize = 50;

            var bFinish = false;

            var resIdList = new List<string>();

            while (!bFinish)
            {
                var resData = GetFormIdListFunc("", "", "", "", "", pageIndex, pageSize);
                if (resData.StatusCode == 200)
                {
                    if (resData.Body.Data.Count == 0)
                    {
                        bFinish = true;
                    }
                    else
                    {
                        resIdList.AddRange(resData.Body.Data);
                    }
                }
                else
                {
                    throw new Exception(JsonConvert.SerializeObject(resData));
                }

                pageIndex++;
            }

            return resIdList;
        }
        #endregion

        #region 获取表单Id集合
        public List<string> GetFormIdList(string search)
        {
            var pageIndex = 1;
            var pageSize = 50;

            var bFinish = false;

            var resIdList = new List<string>();

            while (!bFinish)
            {
                var resData = GetFormIdListFunc("", "", "", "", search, pageIndex, pageSize);
                if (resData.StatusCode == 200)
                {
                    if (resData.Body.Data.Count == 0)
                    {
                        bFinish = true;
                    }
                    else
                    {
                        resIdList.AddRange(resData.Body.Data);
                    }
                }
                else
                {
                    throw new Exception(JsonConvert.SerializeObject(resData));
                }

                pageIndex++;
            }

            return resIdList;
        }
        #endregion

        #region 获取表单Id集合（24小时内更新过的数据）
        public List<string> GetModifyFormIdList()
        {
            var pageIndex = 1;
            var pageSize = 50;

            var bFinish = false;

            var resIdList = new List<string>();

            var modifyFromTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            var modifyToTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");

            while (!bFinish)
            {
                var resData = GetFormIdListFunc(modifyFromTime, modifyToTime, modifyFromTime, modifyToTime, "", pageIndex, pageSize);
                if (resData.StatusCode == 200)
                {
                    if (resData.Body.Data.Count == 0)
                    {
                        bFinish = true;
                    }
                    else
                    {
                        resIdList.AddRange(resData.Body.Data);
                    }
                }
                else
                {
                    throw new Exception(JsonConvert.SerializeObject(resData));
                }

                pageIndex++;
            }

            return resIdList;
        }
        #endregion

        #region 通过数据Id获取数据详情（单条）
        public Dictionary<string, object> GetFormDataById(string id, out string createTime, out string modifyTime)
        {
            var resData = GetFormDataByIdsFunc(new List<string>() { id });
            if (resData.StatusCode == 200)
            {
                createTime = resData.Body.Result[0].CreateTimeGMT;
                modifyTime = resData.Body.Result[0].ModifiedTimeGMT;
                return resData.Body.Result[0].FormData;
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(resData));
            }
        }
        #endregion

        #region 更新同步标识信息
        public UpdateFormDataResponse UpdateFormDataSyncDataById(YiDaResDto resData, string FormInstanceId)
        {
            var data = new Dictionary<string, string>();
            data.Add("textField_ltxyt75i", resData.bSuccess ? "同步成功" : "同步失败");
            data.Add("dateField_ltxyt75l", UnixTimeHelper.ConvertToMilliseconds(resData.syncTime).ToString());
            data.Add("textField_ltxyt75m", resData.ncNo);
            data.Add("textField_ltxyt75n", resData.log);
            data.Add("radioField_lycrvvtk", resData.bNeedSync);

            return UpdateFormDataByIdFunc(JsonConvert.SerializeObject(data), FormInstanceId);
        }

        // 仅更新状态
        public UpdateFormDataResponse UpdateFormDataSyncDataByIdOnlyState(string FormInstanceId)
        {
            var data = new Dictionary<string, string>();
            data.Add("textField_ltxyt75i", "同步成功");

            return UpdateFormDataByIdFunc(JsonConvert.SerializeObject(data), FormInstanceId);
        }
        #endregion

        #region 更新表单数据
        public UpdateFormDataResponse UpdateFormDataById(Dictionary<string, string> resData, string FormInstanceId)
        {
            return UpdateFormDataByIdFunc(JsonConvert.SerializeObject(resData), FormInstanceId);
        }
        #endregion


        #region 获取【流程表单】id集合
        /// <summary>
        /// 获取【流程表单】id集合
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public List<string> GetFormCodeList(string search)
        {
            var pageIndex = 1;
            var pageSize = 50;

            var bFinish = false;

            var resIdList = new List<string>();

            while (!bFinish)
            {
                var resData = GetFormCodeListFunc("", "", "", "", search, pageIndex, pageSize);
                if (resData.StatusCode == 200)
                {
                    if (resData.Body.Data.Count == 0)
                    {
                        bFinish = true;
                    }
                    else
                    {
                        resIdList.AddRange(resData.Body.Data);
                    }
                }
                else
                {
                    throw new Exception(JsonConvert.SerializeObject(resData));
                }

                pageIndex++;
            }

            return resIdList;
        }

        #endregion

        #region 通过数据Id获取【表单数据】详情（单条）
        /// <summary>
        ///  通过数据Id获取【表单数据】详情（单条）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public Dictionary<string, object> GetFormDataByCode(string id)
        {
            var resData = GetFormDataByCodesFunc(new List<string>() { id });
            if (resData.StatusCode == 200)
            {
                return resData.Body.Result[0].Data;
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(resData));
            }
        }
        #endregion

        #endregion

        #region 宜搭接原始口
        public AlibabaCloud.SDK.Dingtalkyida_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkyida_1_0.Client(config);
        }

        #region 获取多个表单实例ID
        public SearchFormDataIdListResponse GetFormIdListFunc(string CreateFromTime, string CreateToTime, string ModifiedFromTime, string ModifiedToTime, string SearchFieldJson, int CurrentPage, int PageSize)
        {
            AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient();
            SearchFormDataIdListHeaders searchFormDatasHeaders = new SearchFormDataIdListHeaders();
            searchFormDatasHeaders.XAcsDingtalkAccessToken = CommHelper.GetAccessToken();

            SearchFormDataIdListRequest searchFormDatasRequest = new SearchFormDataIdListRequest
            {
                ModifiedToTimeGMT = ModifiedToTime,
                SystemToken = _SystemToken,
                ModifiedFromTimeGMT = ModifiedFromTime,
                SearchFieldJson = SearchFieldJson,
                UserId = _UserId,
                CreateToTimeGMT = CreateToTime,
                CreateFromTimeGMT = CreateFromTime,
                PageNumber = CurrentPage,
                PageSize = PageSize
            };
            var rsp = client.SearchFormDataIdListWithOptions(_AppType, _FormId, searchFormDatasRequest, searchFormDatasHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            return rsp;
        }
        #endregion

        #region 批量获取表单实例数据
        public BatchGetFormDataByIdListResponse GetFormDataByIdsFunc(List<string> IdList)
        {
            AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchGetFormDataByIdListHeaders batchGetFormDataByIdListHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchGetFormDataByIdListHeaders();
            batchGetFormDataByIdListHeaders.XAcsDingtalkAccessToken = CommHelper.GetAccessToken();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchGetFormDataByIdListRequest batchGetFormDataByIdListRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchGetFormDataByIdListRequest
            {
                FormUuid = _FormId,
                AppType = _AppType,
                SystemToken = _SystemToken,
                FormInstanceIdList = IdList,
                NeedFormInstanceValue = true,
                UserId = _UserId,
            };
            var rsp = client.BatchGetFormDataByIdListWithOptions(batchGetFormDataByIdListRequest, batchGetFormDataByIdListHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            return rsp;
        }
        #endregion

        #region 更新表单实例数据
        public UpdateFormDataResponse UpdateFormDataByIdFunc(string UpdateFormDataJson, string FormInstanceId)
        {
            AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.UpdateFormDataHeaders updateFormDataHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.UpdateFormDataHeaders();
            updateFormDataHeaders.XAcsDingtalkAccessToken = CommHelper.GetAccessToken();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.UpdateFormDataRequest updateFormDataRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.UpdateFormDataRequest
            {
                AppType = _AppType,
                SystemToken = _SystemToken,
                UserId = _UserId,
                Language = "zh_CN",
                FormInstanceId = FormInstanceId,
                UseLatestVersion = true,
                UpdateFormDataJson = UpdateFormDataJson,
            };
            try
            {
                var rsp = client.UpdateFormDataWithOptions(updateFormDataRequest, updateFormDataHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
                return rsp;
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题

                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
            }

            return null;
        }
        #endregion



        #region 获取多个【流程表单】实例ID 【默认审批通过的】
        /// <summary>
        /// 获取多个【流程表单】实例ID
        /// </summary>
        /// <param name="CreateFromTime"></param>
        /// <param name="CreateToTime"></param>
        /// <param name="ModifiedFromTime"></param>
        /// <param name="ModifiedToTime"></param>
        /// <param name="SearchFieldJson"></param>
        /// <param name="CurrentPage"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public GetInstanceIdListResponse GetFormCodeListFunc(string CreateFromTime, string CreateToTime, string ModifiedFromTime, string ModifiedToTime, string SearchFieldJson, int CurrentPage, int PageSize)
        {
            AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstanceIdListHeaders getInstanceIdListHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstanceIdListHeaders();
            getInstanceIdListHeaders.XAcsDingtalkAccessToken = CommHelper.GetAccessToken();
            // 实例状态，取值：
            //RUNNING：运行中
            //TERMINATED：已终止
            //COMPLETED：已完成
            //ERROR：异常

            //审批结果，取值：
            //agree：同意
            //disagree：拒绝
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstanceIdListRequest getInstanceIdListRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstanceIdListRequest
            {
                ModifiedToTimeGMT = ModifiedToTime,
                SystemToken = _SystemToken,
                ModifiedFromTimeGMT = ModifiedFromTime,
                SearchFieldJson = SearchFieldJson,
                UserId = _UserId,
                CreateToTimeGMT = CreateToTime,
                CreateFromTimeGMT = CreateFromTime,
                PageNumber = CurrentPage,
                PageSize = PageSize,
                InstanceStatus = "COMPLETED",//"COMPLETED",//实例状态
                ApprovedResult = "agree",//"agree",//审批结果
                AppType = _AppType,
                FormUuid = _FormId
            };
            var rsp = client.GetInstanceIdListWithOptions(getInstanceIdListRequest, getInstanceIdListHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            return rsp;
        }
        #endregion

        #region 批量获取【流程表单】实例数据
        public GetInstancesByIdListResponse GetFormDataByCodesFunc(List<string> IdList)
        {
            AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstancesByIdListHeaders getInstancesByIdListHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstancesByIdListHeaders();
            getInstancesByIdListHeaders.XAcsDingtalkAccessToken = CommHelper.GetAccessToken();

            AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstancesByIdListRequest getInstancesByIdListRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.GetInstancesByIdListRequest
            {
                AppType = _AppType,
                SystemToken = _SystemToken,
                UserId = _UserId,
                Language = "zh_CN",
                ProcessInstanceIds = string.Join(",", IdList),
            };
            var rsp = client.GetInstancesByIdListWithOptions(getInstancesByIdListRequest, getInstancesByIdListHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            return rsp;
        }
        #endregion
        #endregion
    }
}
