using Microsoft.Extensions.Caching.Memory;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;
using static XYY.Common.Standard.QYWXWebHook;

namespace XYY.Common.Standard
{
    public partial class QYWXAPI
    {
        IMemoryCache memoryCache;
        public QYWXAPI()
        {
            this.memoryCache = new MemoryCache(new MemoryCacheOptions
            {
            });
        }
        public string GetToken(bool CommunicationNews = false)
        {

            /*
             corpid ww6335df98d0bd3b25
             corpsecret Kvrqo51WusTEIRlcyfo6vE2U-Kd_cb9eyJbMlTTF2Gg
             */
            string token = memoryCache.Get<string>("txltoken");
            if (token == null)
            {
                string corpid = "ww6335df98d0bd3b25";
                string corpsecret = "Kvrqo51WusTEIRlcyfo6vE2U-Kd_cb9eyJbMlTTF2Gg";
                if (CommunicationNews)
                {
                    corpsecret = "0T82vwSIfvjrMnpYSN18f7c9eeCg-tIvrWFIC9SktJk";
                }
                string url = $@"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
                RestClient restClient = new RestClient(url);
                RestRequest restRequest = new RestRequest(Method.GET);
                var response = restClient.Execute(restRequest);
                if (response.IsSuccessful)
                {
                    TokenResult result = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResult>(response.Content);
                    if (result != null && !string.IsNullOrEmpty(result.access_token))
                    {
                        token = result.access_token;
                        memoryCache.Set<string>("txltoken", token);
                    }
                    else
                    {
                        throw new Exception(result.errmsg);
                    }
                }
                else
                {
                    throw new Exception("获取WXToken失败" + (response.ErrorMessage ?? response.Content));
                }
            }
            return token;
        }

        public List<UserlistItem> GetUserInfoItemByDepartment(string token, int departmentId)
        {
            string url = $@"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={token}&department_id={departmentId}";
            RestClient client = new RestClient(url);
            RestRequest request = new RestRequest(Method.GET);
            var response = client.Execute(request);
            if (response.IsSuccessful)
            {
                UserInfoResult userIdResult = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoResult>(response.Content);
                if (userIdResult.errcode == 0)
                {
                    return userIdResult.userlist;
                }
                else
                {
                    throw new Exception(userIdResult.errmsg);
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage ?? response.Content);
            }
        }

        public List<UserlistItem> GetCustomers(string userId)
        {
            List<UserlistItem> result = new List<UserlistItem>();
            string token = GetToken(false);
            string url2 = $"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token={token}";
            RestClient client2 = new RestClient(url2);
            RestRequest restRequest2 = new RestRequest(Method.POST);
            restRequest2.AddJsonBody(new { userid_list = new string[] { userId } });
            var response2 = client2.Execute(restRequest2);
            if (response2.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception(response2.ErrorMessage ?? response2.Content);
            External_contact_Root root = Newtonsoft.Json.JsonConvert.DeserializeObject<External_contact_Root>(response2.Content);
            if (root.errcode != 0)
                throw new Exception(root.errmsg);

            result.AddRange(root.external_contact_list.Select(x => new UserlistItem
            {
                name = x.external_contact.name,
                position = x.external_contact.position,
                corp_name = x.external_contact.corp_name,
                avatar = x.external_contact.avatar,
                userid = x.external_contact.external_userid
            }));
            return result;

        }


        public List<UserlistItem> GetUserInfos()
        {
            List<UserlistItem> result = new List<UserlistItem>();
            string token = GetToken(false);
            string url = $"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={token}";
            RestClient client = new RestClient(url);
            RestRequest request = new RestRequest(Method.GET);
            var response = client.Execute(request);
            if (response.IsSuccessful)
            {
                DepartmentItemResult userIdResult = Newtonsoft.Json.JsonConvert.DeserializeObject<DepartmentItemResult>(response.Content);
                if (userIdResult.errcode == 0)
                {
                    userIdResult.department.ForEach(x => result.AddRange(GetUserInfoItemByDepartment(token, x.id)));
                    return result;
                }
                else
                {
                    throw new Exception(userIdResult.errmsg);
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage ?? response.Content);
            }

        }

        public class WXUserInfo
        {
            public string userid { get; set; }
            public string userName { get; set; }
            public string department { get; set; }
        }
        //如果好用，请收藏地址，帮忙分享。
        public class TokenResult
        {
            /// <summary>
            /// 
            /// </summary>
            public int errcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string access_token { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int expires_in { get; set; }
        }

        //如果好用，请收藏地址，帮忙分享。
        public class DepartmentItem
        {
            /// <summary>
            /// 
            /// </summary>
            public int id { get; set; }
            /// <summary>
            /// 广州研发中心
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string name_en { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> department_leader { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int parentid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int order { get; set; }
        }


        //如果好用，请收藏地址，帮忙分享。
        public class GetCustomerListResult
        {
            /// <summary>
            /// 
            /// </summary>
            public int errcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> external_userid { get; set; }
        }

        public class DepartmentItemResult
        {
            /// <summary>
            /// 
            /// </summary>
            public int errcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<DepartmentItem> department { get; set; }
        }


        //如果好用，请收藏地址，帮忙分享。
        public class Text
        {
            /// <summary>
            /// 文本
            /// </summary>
            public string value { get; set; }
        }

        public class AttrsItem
        {
            /// <summary>
            /// 
            /// </summary>
            public int type { get; set; }
            /// <summary>
            /// 文本名称
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Text text { get; set; }
        }

        public class Extattr
        {
            /// <summary>
            /// 
            /// </summary>
            public List<AttrsItem> attrs { get; set; }
        }

        public class Wechat_channels
        {
            /// <summary>
            /// 视频号名称
            /// </summary>
            public string nickname { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int status { get; set; }
        }


        public class External_attrItem
        {
            /// <summary>
            /// 
            /// </summary>
            public int type { get; set; }
            /// <summary>
            /// 文本名称
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Text text { get; set; }
        }

        public class External_profile
        {
            /// <summary>
            /// 企业简称
            /// </summary>
            public string external_corp_name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Wechat_channels wechat_channels { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<External_attrItem> external_attr { get; set; }
        }

        public class UserlistItem
        {
            /// <summary>
            /// 
            /// </summary>
            public string userid { get; set; }
            /// <summary>
            /// 李四
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<int> department { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<int> order { get; set; }
            /// <summary>
            /// 后台工程师
            /// </summary>
            public string position { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string mobile { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string gender { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string email { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string biz_mail { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<int> is_leader_in_dept { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> direct_leader { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string avatar { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string thumb_avatar { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string telephone { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string @alias { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int status { get; set; }
            /// <summary>
            /// 广州市海珠区新港中路
            /// </summary>
            public string address { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string english_name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string open_userid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int main_department { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Extattr extattr { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string qr_code { get; set; }
            /// <summary>
            /// 产品经理
            /// </summary>
            public string external_position { get; set; }

            public string corp_name { get; set; }

            /// <summary>
            /// 
            /// </summary>
            public External_profile external_profile { get; set; }
        }

        public class UserInfoResult
        {
            /// <summary>
            /// 
            /// </summary>
            public int errcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<UserlistItem> userlist { get; set; }
        }


    }
}
