using DotNetCore.CAP;
using Furion.DistributedIDGenerator;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System.Text;
using System.Web;
using YBDevice.Entity;

namespace YBDevice.NApi.Controllers.Body
{
    /// <summary>
    /// 八电极接口
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiController]
    public class BodyController : ControllerBase
    {
        public static string appId = Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;
        public static string appSecret = Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret;
        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 IBodyService _bodyService;
        private readonly IOrderService _orderService;
        private readonly IDeviceService _deviceService;
        private readonly INoticeService _noticeService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICapPublisher _capBus;
        public BodyController(IBodyService bodyService, IOrderService orderService, IDeviceService deviceService, INoticeService noticeService, IHttpContextAccessor httpContextAccessor, ICapPublisher capPublisher)
        {
            _bodyService = bodyService;
            _orderService = orderService;
            _deviceService = deviceService;
            _noticeService = noticeService;
            _httpContextAccessor = httpContextAccessor;
            _capBus = capPublisher;
        }
        /// <summary>
        /// 接收八电极秤发过来的消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> GetAsync([FromBody] BodyRequstDto data)
        {
            //对结果进行解析
            return await _bodyService.HandlerBodyDataAsync(data);
        }
        /// <summary>
        /// PCH01W接收端
        /// </summary>
        /// <param name="data"></param>
        [HttpPost]
        public async Task<Object> GetData([FromBody] BodyRequstDto data)
        {
            return await _bodyService.Handler01WDataAsync(data);
        }

        /// <summary>
        ///二维码结果r=重量|左手阻抗|右手阻抗|左脚阻抗|左脚阻抗|全身阻抗|身高| and SN=xxx and t=2，重量单位kg，分度值0.05，阻抗单位欧母，分度值1，身高单位cm，分度值0.5
        ///示例r=60.05|500.1|250|250|300|300|600|180.5|and SN=xxx and t=2
        /// </summary>
        /// <param name="r"></param>
        /// <param name="sn"></param>
        /// <param name="t"></param>
        /// <param name="type">1-测试,2-正式</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult get(string r, string sn, string t, int type = 1)
        {
            //对结果进行解析
            var arr = r.Split('|');
            if (arr.Length != 7)
            {
                return Redirect($"/qr/error?msg=1&eid=0");
            }
            //对数据进行拼接
            var str = $"{sn}|{arr[0]}|{arr[6]}|{arr[1]}|{arr[2]}|{arr[3]}|{arr[4]}|{arr[5]}|{t}";
            //对参数进行base64编码
            var data = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{str}"));
            var url = $"{Configs.GetString("APIURL")}/body/r?data={data}";
            //对url进行base64编码
            url = Convert.ToBase64String(Encoding.UTF8.GetBytes(url));
            //跳转授权页面
            var state = "xbpage";//用于识别请求可靠性
            var redirecturl = $"{Configs.GetString("APIURL")}/Auth/page?r={url}";
            var rurl = OAuthApi.GetAuthorizeUrl(appId, redirecturl, state, OAuthScope.snsapi_userinfo);
            return Redirect(rurl);
        }

        /// <summary>
        /// 八电极数据结果展示
        /// </summary>
        /// <param name="d">sn|weight|height|lefthandimp|righthandimp|leftfootimp|rightfootimp|bodyimp</param>
        /// <returns></returns>
        [WeChatFilter]
        [HttpGet]
        public IActionResult br(string d)
        {
            var arr = d.Split('|');
            if (arr.Length != 9)
            {
                return Redirect($"/qr/error?msg=1&eid={Guid.Empty}");
            }
            //对数据进行拼接
            //对参数进行base64编码
            var data = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{d}"));
            var url = $"{Configs.GetString("APIURL")}/body/qr?data={data}";
            //对url进行base64编码
            url = Convert.ToBase64String(Encoding.UTF8.GetBytes(url));
            //跳转授权页面
            var state = "xbpage";//用于识别请求可靠性
            var redirecturl = $"{Configs.GetString("APIURL")}/Auth/page?r={url}";
            var rurl = OAuthApi.GetAuthorizeUrl(appId, redirecturl, state, OAuthScope.snsapi_userinfo);
            return Redirect(rurl);
        }

        /// <summary>
        /// 八电极推送的模版消息数据解析
        /// </summary>
        /// <param name="data"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> qrAsync(string data, string info)
        {
            //记录发送过来的数据
            //  _loggerService.AddLogger($"八电极二维码扫码数据,r={r},sn={sn},t={t}");
            var ua = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString();
            //对data进行base64解密,格式:sn|重量|身高|左手阻抗|右手阻抗|左脚阻抗|左脚阻抗|全身阻抗|设备类型
            var str = Encoding.UTF8.GetString(Convert.FromBase64String(data));
            var arr = str.Split('|');
            string sn = arr[0];
            decimal weight = arr[1].ToDecimal();
            decimal height = arr[2].ToDecimal();
            decimal lefthandimp = arr[3].ToDecimal();
            decimal righthandimp = arr[4].ToDecimal();
            decimal leftfootimp = arr[5].ToDecimal();
            decimal rightfootimp = arr[6].ToDecimal();
            decimal bodyimp = arr[7].ToDecimal();
            //对info进行base64解密，然后urldecode解码
            info = HttpUtility.UrlDecode(Encoding.UTF8.GetString(Convert.FromBase64String(info)));
            UserBaseInfoS2SDto userInfo = info.ToObject<UserBaseInfoS2SDto>();
            Guid eid = Guid.Empty;//错误代码

            //根据设备绑定的订单,跳转到不同的页面
            var equ = await _deviceService.GetDeviceByEcodeAsync(sn);
            var orderinfo = await _orderService.GetBodyOrderAsync(equ, userInfo);
            if (orderinfo == null)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str}",
                    FromInfo = "八电极扫码,未找到可用的订单",
                    UA = ua,
                    Id = eid
                });
                return RedirectToAction("error", "qr", new { msg = (int)ErrorInfoDesc.NoOrder, eid = eid });
            }
            //订单信息有误
            if (orderinfo.code > 0)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str},返回:{orderinfo.code}",
                    FromInfo = "八电极模版消息,获取订单失败",
                    UA = ua,
                    Id = eid
                });
                return RedirectToAction("error", "qr", new { msg = orderinfo.code, eid = eid });
            }
            if (!int.TryParse(arr[8], out int tid))
            {
                Guid resultid = Guid.Parse(arr[8]);
                //记录数据
                await _orderService.UpdateBodyResultAsync(resultid, userInfo, orderinfo);
            }
            var jsondata = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{orderinfo.ToJson()}"));
            return RedirectToAction("f", "qr", new { info = jsondata });
        }

        /// <summary>
        /// 数据解析,二维码展示
        /// </summary>
        /// <param name="data"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> rAsync(string data, string info)
        {
            //记录发送过来的数据
            //  _loggerService.AddLogger($"八电极二维码扫码数据,r={r},sn={sn},t={t}");
            var ua = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString();
            //对data进行base64解密,格式:sn|重量|身高|左手阻抗|右手阻抗|左脚阻抗|左脚阻抗|全身阻抗|设备类型
            var str = Encoding.UTF8.GetString(Convert.FromBase64String(data));
            var arr = str.Split('|');
            string sn = arr[0];
            //对info进行base64解密，然后urldecode解码
            info = HttpUtility.UrlDecode(Encoding.UTF8.GetString(Convert.FromBase64String(info)));
            UserBaseInfoS2SDto userInfo = info.ToObject<UserBaseInfoS2SDto>();
            Guid eid = Guid.Empty;//错误代码
            #region 检查设备
            var equ = await _deviceService.GetDeviceByEcodeAsync(sn);
            if (equ == null)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str}",
                    FromInfo = "八电极扫码,设备未找到",
                    UA = ua,
                    Id = eid
                });
                //去激活小程序
                var order = await _orderService.GetDevMagOrderAsync(equ, userInfo);
                return RedirectToAction("bmini", "qr", new { sn = order.appid, n = order.NickName, h = order.HeadImg });
                //  return RedirectToAction("error", "qr", new { msg = (int)ErrorInfoDesc.devnotfound, eid = eid });
            }
            //判断设备是否可用
            if (equ.Status == (int)DeviceStatus.Stop)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str}",
                    FromInfo = "八电极扫码,设备已停止运行",
                    UA = ua,
                    Id = eid
                });
                return RedirectToAction("error", "qr", new { msg = (int)ErrorInfoDesc.deverror, eid = eid });
            }
            //判断设备是否激活
            if (!equ.ActiveTime.HasValue
                //|| equ.EndTime < DateTime.Now 
                || equ.Status == DeviceStatus.UnActive)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str}",
                    FromInfo = "八电极扫码,设备未激活",
                    UA = ua,
                    Id = eid
                });
                //跳转到打开设备管理小程序的页面
                //获取设备绑定的设备管理小程序
                var order = await _orderService.GetDevMagOrderAsync(equ, userInfo);
                return RedirectToAction("bmini", "qr", new { sn = order.appid, n = order.NickName, h = order.HeadImg });
            }
            #endregion
            //根据设备绑定的订单,跳转到不同的页面
            var orderinfo = await _orderService.GetOrderByTrendAsync(equ, userInfo);
            if (orderinfo == null)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str}",
                    FromInfo = "八电极扫码,未找到可用的订单",
                    UA = ua,
                    Id = eid
                });
                return RedirectToAction("error", "qr", new { msg = (int)ErrorInfoDesc.NoOrder, eid = eid });
            }
            //订单信息有误
            if (orderinfo.code > 0)
            {
                eid = IDGen.NextID();
                await _capBus.PublishAsync("system.service.insertnoticelogger", new YB_NoticeLogger
                {
                    UserInfo = info,
                    Info = $"参数:{str},返回:{orderinfo.code}",
                    FromInfo = "八电极扫码,获取订单失败",
                    UA = ua,
                    Id = eid
                });
                return RedirectToAction("error", "qr", new { msg = orderinfo.code, eid = eid });
            }
            //记录数据
            decimal height = arr[2].ToDecimal();
            decimal weight = arr[1].ToDecimal();
            decimal lefthandimp = arr[3].ToDecimal();
            decimal righthandimp = arr[4].ToDecimal();
            decimal leftfootimp = arr[5].ToDecimal();
            decimal rightfootimp = arr[6].ToDecimal();
            decimal bodyimp = arr[7].ToDecimal();
            await _orderService.InsertResultAsync(equ, userInfo, orderinfo, height, weight, 2, bodyimp, leftfootimp, rightfootimp
                , lefthandimp, righthandimp);
            var jsondata = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{orderinfo.ToJson()}"));
            return RedirectToAction("f", "qr", new { info = jsondata });
        }
    }
}
