using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Tools;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Ashermed.BaseFramework;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.Api.ContractModel.App;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.Tencent;

namespace ASHermed.SingleSignOnFramework
{
    /// <summary>
	/// 腾讯服务
	/// </summary>
	public class TencentOutService : ITencentOutService
    {
        private readonly IHttpClientHelp _httpClient;
        private ILogger<TencentOutService> _logger;
        HttpClientHelper _httpClientHelper;
        //object LOCK_CGI_ACCESS_TOKEN = new object();
        private string _cgiAccessToken;
        private long _tokenMillis;
        private long _DURATION_MILLIS;
        /// <summary>
        /// 腾讯服务
        /// </summary>
        /// <param name="httpClient"></param>
        /// <param name="logger"></param>
        /// <param name="httpClientHelper"></param>
        public TencentOutService(IHttpClientHelp httpClient, ILogger<TencentOutService> logger, HttpClientHelper httpClientHelper)
        {
            _httpClient = httpClient;
            _DURATION_MILLIS = 1L * 1800 * 1000;
            _logger = logger;
            _httpClientHelper = httpClientHelper;
        }



        /// <summary>
        /// 导入用户
        /// </summary>
        public void ImportUser(string url, string api, List<(string Name, string FileName, object Value)> dic)
        {
            var result = _httpClient.HttpPost<TencentResponse>(url, api, dic);
        }

        public ImRepBody CreateGroup(string url, string api, List<(string Name, string FileName, object Value)> dic)
        {
            var result = _httpClient.HttpPost<ImRepBody>(url, api, dic);
            return result.Data;
        }
        public ImRepBody CreateGroup(string url, string api, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<ImRepBody>(url + api, dic.ToJson());
            return result;
        }

        public GroupAddMemberReb AddGroupMember(string url, string api, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<GroupAddMemberReb>(url + api, dic.ToJson());
            return result;
        }

        public TencentResponse DeleteGroupMember(string url, string api, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<TencentResponse>(url + api, dic.ToJson());
            return result;
        }

        public TencentResponse ForbiddenUser(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<TencentResponse>(url + apiUrl, dic.ToJson());
            return result;
        }

        public TencentMsgRes SendMsgToGroup(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<TencentMsgRes>(url + apiUrl, dic.ToJson());
            return result;
        }

        public TencentResponse SendSysMsgToGroup(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<TencentResponse>(url + apiUrl, dic.ToJson());
            return result;
        }

        public AddFriendReb FriendAdd(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<AddFriendReb>(url + apiUrl, dic.ToJson());
            return result;
        }
        public IMRecord GetIMRecord(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<IMRecord>(url + apiUrl, dic.ToJson());
            return result;
        }
        public MsgFriendReb SendFriendMsg(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<MsgFriendReb>(url + apiUrl, dic.ToJson());
            return result;
        }

        public ImGroup GetGroupMemberInfo(string url, string apiUrl, Dictionary<string, object> dic)
        {
            var result = _httpClientHelper.HttpPost<ImGroup>(url + apiUrl, dic.ToJson());
            return result;
        }

        /// <summary>
        /// 获取cgi的token
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public string GetCgiAccessToken(string appid, string appsecret)
        {
            lock (this)
            {
                var curtime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
                if (string.IsNullOrEmpty(_cgiAccessToken) || curtime - _tokenMillis > _DURATION_MILLIS)
                {
                    var result = _httpClient.HttpGet<AuthToken>("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret, "");
                    //JSONObject cgiTokenObj = HttpUtil.getJson(WxchatUrlUtil.getCgiAccessTokenUrl(appid, appsecret));
                    _logger.LogInformation(JsonConvert.SerializeObject(result.Data));
                    _cgiAccessToken = result.Data.access_token;
                    _tokenMillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
                }
                return _cgiAccessToken;
            }
        }
        public string ResetCgiAccessToken(string appId, string appSecret)
        {
            lock (this)
            {

                var result = _httpClient.HttpGet<AuthToken>("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret, "");
                //JSONObject cgiTokenObj = HttpUtil.getJson(WxchatUrlUtil.getCgiAccessTokenUrl(appid, appsecret));
                _cgiAccessToken = result.Data.access_token;
                _tokenMillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

                return _cgiAccessToken;
            }
        }

        public CommonResponse SendTemplateMessage(string token, string openId, string templateId, string jumpUrl, string appid, string pagepath, List<TemplateDataObject> data)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;

            Dictionary<string, object> param = new Dictionary<string, object>();
            param.Add("touser", openId);
            param.Add("template_id", templateId);
            param.Add("url", jumpUrl);
            //param.Add("miniprogram", new Dictionary<string, string>() {
            //    {"appid", appid},
            //    {"pagepath", pagepath}
            //});
            Dictionary<string, Dictionary<string, string>> map = new Dictionary<string, Dictionary<string, string>>();
            foreach (var dataObject in data)
            {
                map.Add(dataObject.field, new Dictionary<string, string>() {
                {"value", dataObject.value},
                {"color", dataObject.color}
                });
            }
            param.Add("data", map);

            var res = _httpClientHelper.HttpPost<CommonResponse>(url, param.ToJson());
            //Logger logger = Logger.getLogger(WxchatUtil.class);
            return res;
        }

        public void SendAtAll(string apiUrl, string jsonObject)
        {
            var res = _httpClientHelper.HttpPost<string>(apiUrl, jsonObject);
        }



    }
}
