using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common.ApiBase;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;
using Senparc.Weixin.WxOpen.Entities;
using Senparc.Weixin.WxOpen.Entities.Request;
using Senparc.Weixin.WxOpen.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Api.DBServices;
using YBDevice.Entity;

namespace YBDevice.Api.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;


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

        /// <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 new WxOpenApp().DecryptDataAsync(model);
        }
    }
}
