using Nirvana.Common;
using Nirvana.Data;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.Open.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;
using YBDevice.NApi.DBServices;

namespace YBDevice.NApi
{
    /// <summary>
    /// 八电极处理接口
    /// </summary>
    public partial class BodyApp : Repository<YB_WifiBind>
    {
        public string component_AppId = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Appid;
        public string component_Secret = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Secret;
        public string component_Token = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Token;
        public string component_EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.Component_EncodingAESKey;
        /// <summary>
        /// 数据包解析
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static BodyAnalyDto AnalyProto(BodyRequstDto data)
        {
            BodyAnalyDto dto = new BodyAnalyDto();
            //检查是否为有效的base64数据
            if (!AESEncrypt.IsBase64(data.@params))
            {
                dto.data = data.@params;
                return dto;
            }
            //数据为base64加密
            byte[] resultByte = Convert.FromBase64String(data.@params);
            dto.data = resultByte.BytesToHexStr();
            int len = resultByte.Count();//数据总长度
            //长度格式是否正确,固定长度为36位
            if(len !=36)
            {
                return dto;
            }
            //前15个字节为sn。中间以 00 分隔。后面为测量结果数据 AA 00 01 F4 00 64 00 64 00 64 00 64 02 30 06 A4 00 00 00 00 
            int i = 0;
            byte[] snbyte = new byte[15];
            for (i = 0; i < 15; i++)
            {
                snbyte[i] = resultByte[i];
            }
            dto.sn = snbyte.BytesToHexStr().Replace(" ", "");
            dto.splitstr = resultByte[i].ByteToHexStr();
            int datalen = len - 16;//数据体长度
            byte[] databyte = new byte[datalen];
            i++;
            for (int j = 0; j < datalen; j++)
            {
                databyte[j] = resultByte[i];
                i++;
            }
            dto.Header = databyte[0].ByteToHexStr();
            if(dto.Header != "AA")
            {
                return dto;
            }
            dto.ischecked = true;
            string tmpstr = "";
            for(int j = 1; j < datalen; j++)
            {
                tmpstr += databyte[j].ByteToHexStr();
                if(j == 3)
                {
                    dto.Weight = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 5)
                {
                    dto.lefthandimp = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 7)
                {
                    dto.righthandimp = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 9)
                {
                    dto.leftfootimp = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 11)
                {
                    dto.rightfootimp = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 13)
                {
                    dto.bodyimp = tmpstr.HexToDesc();
                    tmpstr = "";
                }
                if(j == 15)
                {
                    dto.height = tmpstr.HexToDesc();
                    tmpstr = "";
                }
            }
            return dto;
        }
        /// <summary>
        /// 处理wifi模块发送过来的数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> HandlerBodyDataAsync(BodyRequstDto data)
        {
            var result = AnalyProto(data);
            if (!result.ischecked)
            {
                return -1;
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                //检查设备是否存在
                if(!await dbClient.Queryable<YB_Device>().AnyAsync(x=>x.Ecode == result.sn))
                {
                    new LoggerApp().InsertErrorLog($"八电极wifi结果推送,设备未找到,参数:{result.ToJson()}", 3);
                    return -1;
                }
                //获取设备绑定的用户列表
                var list = await dbClient.Queryable<YB_WifiBind>().Where(x => x.DevCode == result.sn && x.Subscribe == 1).ToListAsync();
                if(list.Count == 0)
                {
                    new LoggerApp().InsertErrorLog($"八电极wifi结果推送,未绑定用户或均已取关,参数:{result.ToJson()}", 3);
                    return -1;
                }
                //发送模版消息
                var tpldata = new {
                    first = new TemplateDataItem($"收到新的测量结果"),
                    keyword1 = new TemplateDataItem($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}"),
                    keyword2 = new TemplateDataItem($"{result.height}"),
                    keyword3 = new TemplateDataItem($"{result.Weight}"),
                    keyword4 = new TemplateDataItem($"{result.lefthandimp},{result.righthandimp},{result.leftfootimp},{result.rightfootimp},{result.bodyimp}"),
                    remark = new TemplateDataItem($"{result.sn}")
                };
                var token = AuthorizerContainer.TryGetAuthorizerAccessToken(component_AppId, "wxda671f842dfda2b8");
                string url = $"https://ybapi.ybhdmob.com/qr/br?d={result.sn}|{result.Weight}|{result.height}|{result.lefthandimp}|{result.righthandimp}|{result.leftfootimp}|{result.rightfootimp}|{result.bodyimp}";
                list.ForEach(x => {
                    SendTemplateMessageResult results = TemplateApi.SendTemplateMessage(token, x.OpenId, "0P6GebIlc5vjYJnO272DNt94VS1SDqxDxRgNzAQTmDA", url, tpldata);
                    //记录发送结果
                    new LoggerApp().InsertErrorLog($"八电极wifi结果推送,模版消息推送,参数:{result.ToJson()}\r\n结果:{results.ToJson()}", 3);
                });
                return 0;
            }
        }
    }
}
