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.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Containers;
using System;
using System.Collections.Generic;
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 RedirectUrl;
        public static string MessageUrl;
        public static string TemplateId;

        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");
            MessageUrl = Configs.GetValue("MessageUrl");
            TemplateId = Configs.GetValue("TemplateId");
            //根据appId判断获取  
            if (!AccessTokenContainer.CheckRegistered(AppId))    //检查是否已经注册  
            {
                AccessTokenContainer.Register(AppId, AppSecret);    //如果没有注册则进行注册  
            }
        }

        /// <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>
        /// 获取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 => new
                    {
                        p.openid,
                        p.text,
                        time = GetTime(p.time).ToString("yyyy-MM-dd HH:mm:ss"),
                        receiver = p.opercode == Opercode.客服收到消息 ? CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick + "(客服)" : UserApi.Info(accesstoken, p.openid).nickname,
                        sender = p.opercode == Opercode.客服发送消息 ? CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick + "(客服)" : UserApi.Info(accesstoken, p.openid).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

        #region 微信方法

        /// <summary>
        /// 发送微信模板消息
        /// </summary>
        /// <param name="wocode">工单编号</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="url">链接地址</param>
        /// <param name="openid">接收方</param>
        /// <param name="templateid">模板id</param>
        public static object SendWechatMsg1(string wocode, string title, string wotype,string state, string content, string orderid, string openid, string templateid = "")
        {
            var url = "id=" + orderid + "&type=" + state;
            var obj = new
            {
                first = new { value = title, color = "#173177" },
                keyword1 = new { value = "心连心集团" },
                keyword2 = new { value = wocode },
                keyword3 = new { value = content }
            };
            //{ { first.DATA} }
            //工单类型：{ { keyword1.DATA} }
            //工单编号：{ { keyword2.DATA} }
            //{ { remark.DATA} }
            var sendResult = SendTemplateMsg(openid, url, obj, templateid);
            return sendResult;
        }
        public static object SendWechatMsg(string wocode, string title, string statename, string content, string tel, string url, string openid, string templateid = "")
        {
            url = "id=" + url;
            var obj = new
            {
                first = new { value = title, color = "#173177" },
                keyword1 = new { value = wocode },
                keyword2 = new { value = statename },
                keyword3 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                keyword4 = new { value = tel },
                remark = new { value = content }
            };
            //var obj = new
            //{
            //    first = new { value = title, color = "#173177" },
            //    keyword1 = new { value = wocode },
            //    keyword2 = new { value = statename },
            //    keyword3 = new { value = tel },
            //    remark = new { value = content }
            //};

            var sendResult = SendTemplateMsg(openid, url, obj, templateid);
            return sendResult;
        }

        /// <summary>
        ///  发送模板消息【需要安全验证】
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="url"></param>
        /// <param name="jsondata"></param>
        /// <param name="templateid"></param>
        /// <returns></returns>
        public static object SendTemplateMsg(string openid, string url, object jsondata, string templateid)
        {
            var log = LogFactory.GetLogger("发送模板消息1");
            try
            {
                //string accesstoken = GetCommonToken();
                if (string.IsNullOrEmpty(templateid))
                {
                    templateid = TemplateId;
                }
                if (MessageUrl.IndexOf("?") != -1)
                {
                    url = MessageUrl + "&" + url;
                }
                else
                {
                    url = MessageUrl + "?" + url;
                }
              
                //var result = TemplateApi.SendTemplateMessageAsync(AppId, openid, templateid, url, jsondata.ToJObject());
                SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(AppId, openid, templateid, url, jsondata);

                //return AppId + "||||" + openid + "||||" + templateid + "||||" + url + "||||" ;
                object result = sendResult;
                //log.Error("发送模板消息1:" + sendResult + "||||:" + AppId + "||||" + openid + "||||" + templateid + "||||" + url + "||||" + jsondata.ToJson());
                return result;
            }
            catch (Exception ex)
            {
                log.Error("发送模板消息：如果你只是拿到了用户的openid，但该用户没有关注公众号，发送时会抛出下面的错误：" + ex.Message);
                return "请求接口失败";
            }
        }
        #endregion
    }
}
