using CallCenter.Utility;
using CallCenterAPI.WechatSDK.Models;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.CustomService;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CallCenterAPI.WechatSDK
{
    public static class WxHelper
    {
        public static string WxId;
        public static string AppId;
        public static string AppSecret;

        public static string CommonToken;//Common的Token
        public static DateTime GetCommonTokenDate;//获取CommonToken的时间
        public static int CommonTokenExpiresIn;//有效时间（s）

        static WxHelper()
        {
            AppId = Configs.GetValue("WechatAppid");
            AppSecret = Configs.GetValue("WechatAppsecret");
        }

        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="wxLoginDto"></param>
        /// <returns></returns>
        public static WxLoginDto GetOpenId(WxLoginDto wxLoginDto)
        {

            if (string.IsNullOrWhiteSpace(wxLoginDto.Code))
            {
                var url = OAuthApi.GetAuthorizeUrl(AppId, wxLoginDto.RedirectUrl, "qwertyuidfghjkl", OAuthScope.snsapi_base);
                wxLoginDto.RedirectUrl = url;
                return wxLoginDto;
            }
            var access = OAuthApi.GetAccessToken(AppId, AppSecret, wxLoginDto.Code);
            wxLoginDto.OpenId = access.openid;
            return wxLoginDto;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="wxLoginDto"></param>
        /// <returns></returns>
        public static WxLoginDto GetUserInfo(WxLoginDto wxLoginDto)
        {
            if (string.IsNullOrWhiteSpace(wxLoginDto.Code))
            {
                var url = OAuthApi.GetAuthorizeUrl(AppId, wxLoginDto.RedirectUrl, "qwertyuidfghjkl", OAuthScope.snsapi_userinfo);
                wxLoginDto.RedirectUrl = url;
                return wxLoginDto;
            }
            var access = OAuthApi.GetAccessToken(AppId, AppSecret, wxLoginDto.Code);
            wxLoginDto.OpenId = access.openid;
            wxLoginDto.UserInfo = OAuthApi.GetUserInfo(access.access_token, access.openid);

            return wxLoginDto;
        }

        /// <summary>
        /// 获取common的token
        /// </summary>
        /// <returns></returns>
        public static string GetCommonToken()
        {
            double ss = DateTime.Now.Subtract(GetCommonTokenDate).TotalSeconds;
            if (ss > CommonTokenExpiresIn)
            {
                var obj = CommonApi.GetToken(AppId, AppSecret);
                if (obj != null && obj.errcode == ReturnCode.请求成功)
                {
                    GetCommonTokenDate = DateTime.Now.AddSeconds(-1);
                    CommonTokenExpiresIn = obj.expires_in;
                    CommonToken = obj.access_token;
                }
                else
                {
                    CommonToken = "";
                }
            }

            return CommonToken;
        }

        public static bool CheckSignature(string signature, string timestamp, string nonce, string token)
        {
            bool bl = false;
            string accesstoken = GetCommonToken();
            if (accesstoken != "")
            {
                bl = Senparc.Weixin.MP.CheckSignature.Check(signature, timestamp, nonce, token);
            }
            return bl;
        }

        #region 多客服

        /// <summary>
        /// 创建客服会话
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static bool CreateSession(string openid)
        {
            bool bl = false;
            string accesstoken = GetCommonToken();
            if (accesstoken != "")
            {
                CustomApi.SendText(accesstoken, openid, "您好，正在为您接通人工客服，请稍候......");
                var zxlist = CustomServiceApi.GetCustomOnlineInfo(accesstoken).kf_online_list;//在线客服列表
                if (zxlist.Count > 0)
                {
                    var kf = zxlist.OrderBy(p => p.accepted_case).FirstOrDefault();//获取当前已经接入用户最少的客服
                    if (kf != null)
                    {
                        var obj = CustomServiceApi.CreateSession(accesstoken, openid, kf.kf_account);//创建客服和用户之间的会话
                        if (obj.errcode == ReturnCode.请求成功)
                        {
                            bl = true;
                        }
                        else
                        {
                            CustomApi.SendText(accesstoken, openid, "接通人工客服异常，请重试");
                        }
                    }
                    else
                    {
                        CustomApi.SendText(accesstoken, openid, "人工客服正在忙碌中，请稍候联系");
                    }
                }
            }
            return bl;
        }

        /// <summary>
        /// 关闭客服会话
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static bool CloseSession(string openid, string kf_account)
        {
            bool bl = false;
            string accesstoken = GetCommonToken();
            if (accesstoken != "")
            {
                var obj = CustomServiceApi.CloseSession(accesstoken, openid, kf_account);
                if (obj.errcode == ReturnCode.请求成功)
                {
                    bl = true;
                    CustomApi.SendText(accesstoken, openid, "已经关闭与人工客服的会话");
                }
                else
                {
                    CustomApi.SendText(accesstoken, openid, "关闭会话异常,请重试");
                }
            }
            return bl;
        }

        /// <summary>
        /// 获取用户聊天记录
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static List<object> GetRecord(DateTime stime, DateTime etime, int pageSize, int pageIndex)
        {
            List<object> list = new List<object>();
            string accesstoken = GetCommonToken();
            if (accesstoken != "")
            {
                var result = CustomServiceApi.GetRecord(accesstoken, stime, etime, pageSize, pageIndex);
                if (result.errcode == ReturnCode.请求成功)
                {
                    list = result.recordlist.Select(p =>
                    {
                        var binfo = CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault();
                        var uinfo = UserApi.Info(accesstoken, p.openid);
                        return new
                        {
                            p.openid,
                            p.opercode,
                            p.text,
                            p.worker,
                            time = GetTime(p.time).ToString("yyyy-MM-dd HH:mm:ss"),
                            receiver = p.opercode == Opercode.客服收到消息 ? binfo.kf_nick+ "(客服)" : uinfo.nickname,
                            sender = p.opercode == Opercode.客服发送消息 ? binfo.kf_nick + "(客服)" : uinfo.nickname
                        };
                    }).ToList<object>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取聊天记录
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static List<object> GetMsgList(DateTime stime, DateTime etime, long msgid, int number)
        {
            List<object> list = new List<object>();
            string accesstoken = GetCommonToken();
            if (accesstoken != "")
            {
                var result = CustomServiceApi.GetMsgList(accesstoken, stime, etime, msgid, number);
                if (result.errcode == ReturnCode.请求成功)
                {
                    list = result.recordList.Select(p => new
                    {
                        p.openid,
                        p.opercode,
                        p.text,
                        p.worker,
                        time = p.time.ToString("yyyy-MM-dd HH:mm:ss"),
                        name = UserApi.Info(accesstoken, p.openid).nickname,
                        kfname = CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick
                    }).ToList<object>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取时间
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DateTime GetTime(double dt)
        {
            DateTime time = DateTime.MinValue;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            time = startTime.AddSeconds(dt);
            return time;
        }

        #endregion
    }
}
