using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using System.Text;
using System.Web;
using YBDevice.Core;
using YBDevice.Entity;

namespace YBDevice.NApi.Controllers
{
    /// <summary>
    /// 小程序管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WxOpenController : ControllerBase
    {
        public static readonly string Component_Token = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Token;
        public static readonly string Component_EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.Component_EncodingAESKey;
        public static readonly string Component_Appid = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Appid;
        public static readonly string Component_Secret = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Secret;

        private readonly IHttpClientFactory _clientFactory;
        private readonly IUserService _userService;
        private readonly IWxOpenService _wxOpenService;
        private readonly ILoggerService _loggerService;

        public WxOpenController(IHttpClientFactory clientFactory, IUserService userService, IWxOpenService wxOpenService, ILoggerService loggerService)
        {
            _clientFactory = clientFactory;
            _userService = userService;
            _wxOpenService = wxOpenService;
            _loggerService = loggerService;
        }

        /// <summary>
        /// wx.login登陆成功之后发送的请求
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> OnLoginAsync([FromBody] WXOpenLoginSubmitModel model)
        {
            return await _wxOpenService.OnLoginAsync(model);
        }

        /// <summary>
        /// 检查登录状态是否已失效
        /// </summary>
        /// <param name="sessionId">sessionid</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> CheckStatusAsync(string sessionId = "")
        {
            return await _wxOpenService.CheckStatusAsync(sessionId);
        }

        /// <summary>
        /// 签名测试
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="rawData"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultInfo CheckWxOpenSignature(string sessionId, string rawData, string signature)
        {
            var checkSuccess = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.CheckSignature(sessionId, rawData, signature);
            return new ResultInfo(checkSuccess ? ResultState.SUCCESS : ResultState.FAIL, checkSuccess ? "签名校验成功" : "签名校验失败");
        }

        /// <summary>
        /// 解密用户数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DecodeEncryptedDataAsync([FromBody] WxOpenDecryptSubmitModel model)
        {
            return await _wxOpenService.DecryptDataAsync(model);
        }

        /// <summary>
        /// 解密用户资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorizeFilter]
        public async Task<ResultInfo> DecryptUserInfoAsync([FromBody] WxOpenDecryptSubmitModel model)
        {
            return await _wxOpenService.DecryptUserInfoAsync(model);
        }

        /// <summary>
        /// 手机号授权登录注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DecryptPhoneAsync([FromBody] WxOpenDecryptSubmitModel model)
        {
            return await _wxOpenService.DecryptPhoneAsync(model);
        }

        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> SendCodeAsync(string phone)
        {
            if (string.IsNullOrEmpty(phone))
            {
                return new ResultInfo(ResultState.FAIL, "手机号不可为空");
            }
            if (!Validate.IsValidMobile(phone))
            {
                return new ResultInfo(ResultState.FAIL, "手机号码不合法");
            }
            Random rd = new Random();
            var yzm = rd.Next(100000, 999999);
            var platform = "小白健康";
            var content = $"【{platform}】您好，欢迎使用{platform},您的手机验证码是:{yzm}，验证码一分钟内有效,若非本人操作，请忽略！";
            var data = new
            {
                phone = phone,
                Content = HttpUtility.UrlEncode(content)
            };
            var par = $"ybdevice_yam_{phone}";
            if (!string.IsNullOrEmpty(RedisHelpers.stringGet<string>(par)))
            {
                return new ResultInfo(ResultState.FAIL, "请求频繁");
            }
            var url = "http://sms.ybhdmob.com/Message/Send?token=ybhdmob";
            var request = new HttpRequestMessage(HttpMethod.Post,
                   url);
            string body = data.ToJson();
            request.Content = new StringContent(body, Encoding.UTF8, "application/json");
            var client = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                var results = result.ToObject<SMSMODEL>();
                //记录日志
                var msg = $"短信发送:参数:{data.ToJson()}\r\n返回值:{result}";
                _loggerService.AddLogger(msg);
                if (results != null && results.code == 0)
                {
                    RedisHelpers.Insert(par, yzm.ToString(), 60);
                }
                return new ResultInfo(ResultState.SUCCESS, "验证码已发送");
            }
            else
            {
                return new ResultInfo(ResultState.FAIL, "短信发送失败");
            }
        }

        /// <summary>
        /// 输入手机号进行注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> RegisterAsync([FromBody] RegModel model)
        {
            return await _wxOpenService.RegisterAsync(model);
        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> SubmitAdviceAsync([FromBody] YB_Advice model)
        {
            return await _userService.SubmitAdviceAsync(model);
        }

        /// <summary>
        /// 解密用户资料,V2-20211126
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DeUserInfoAsync(WxOpenDecryptSubmitModel model)
        {
            return await _wxOpenService.DeUserInfoAsync(model);
        }

        /// <summary>
        /// 解密手机号,V2-20211126
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DeUserPhone(WxOpenDecryptSubmitModel model)
        {
            return await _wxOpenService.DecryptPhoneAsync(model);
            // return await _wxOpenService.DeUserPhone(model);已弃用

        }

        /// <summary>
        /// 根据手机号进行注册,V2-20211126
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DeRegisterAsync(RegModel model)
        {
            return await _wxOpenService.RegisterAsync(model);
            //return await _wxOpenService.DeRegisterAsync(model);已弃用
        }

        /// <summary>
        /// 获取小程序升级信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> UpgradeAsync(WxOpenUpgradeC2SDto input)
        {
            return await _wxOpenService.UpgradeAsync(input);
        }
    }
}