using Furion;
using Furion.DynamicApiController;
using MessagePack;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Waste.Application
{
    /// <summary>
    /// 测试专用
    /// </summary>
    public class TestAppService : IDynamicApiController
    {
        private static string ApiUrl = App.Configuration["SZDevPlatSetting:ApiUrl"];
        private static string UserId = App.Configuration["SZDevPlatSetting:UserId"];
        private static string ApiSecret = App.Configuration["SZDevPlatSetting:ApiSecret"];
        private static string ApiSecretHash = App.Configuration["SZDevPlatSetting:ApiSecretHash"];
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILoggerService _loggerService;
        public TestAppService(ILoggerService loggerService, IHttpClientFactory clientFactory)
        {
            _loggerService = loggerService;
            _clientFactory = clientFactory;
        }
        /// <summary>
        /// 接收测试
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [NonUnify]
        public string Subscribe(BusinessApiS2CDto data)
        {
            var msg = $"平台推送的消息内容:{data.ToJson()}";
            _loggerService.AddLogger(msg, 1);
            return "success";
        }

        [HttpGet]
        public void ConnectServer()
        {

        }

        [HttpGet]
        public async Task TestSendAsync()
        {
            GarbagePltC2SDto garbageC2SDto = new GarbagePltC2SDto { 
                Weight=10.1,
                secret = "6Vxkfkg3kxqkkzgT",
                secrethash = "51fb893bccc1395e",
                ScanningTime= 1627917492,
                DStatus=0,
                deviceid = "08d954b6-df45-4de1-8fde-f5109798b855",
                Trash = "000F000002",
                Type = 4
            };
            if(garbageC2SDto.Weight == ((int)garbageC2SDto.Weight).ToDouble())
            {
                garbageC2SDto.Weight = garbageC2SDto.Weight.ToDouble(0);
            }
            var url = $"{ApiUrl}/api/garbages";
            string[] paramlist = new string[] {
                garbageC2SDto.Weight.ToString(),garbageC2SDto.Trash,garbageC2SDto.Type.ToString(),garbageC2SDto.ScanningTime.ToString(),garbageC2SDto.DStatus.ToString()
            };
            int timestamp = 1627917492;
            int nonce = 497458578;
            string sign = GetUserApiSign(garbageC2SDto.secret, paramlist);
            var c2s_dto = new SuZhouPostApiBaseDto<GarbageC2SDto>
            {
                Data = new GarbageC2SDto
                {
                    DStatus = garbageC2SDto.DStatus,
                    ScanningTime = garbageC2SDto.ScanningTime,
                    Trash = garbageC2SDto.Trash,
                    Type = garbageC2SDto.Type,
                    Weight = garbageC2SDto.Weight
                },
                SecretHash = garbageC2SDto.secrethash,
                Nonce = nonce,
                Signature = sign,
                TimeStamp = timestamp,
                DeviceId = garbageC2SDto.deviceid
            };
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var bytes = MessagePackSerializer.Serialize(c2s_dto);
            request.Content = new ByteArrayContent(bytes);
            request.Headers.Add("Accept", "application/x-msgpack");
            request.Content.Headers.Add("Content-Type", "application/x-msgpack");
            var client = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                //记录日志
                _loggerService.AddLogger($"测量信息上报成功:参数:{c2s_dto.ToJson()}", 3);
            }
            else
            {
                var msg = await response.Content.ReadAsStringAsync();
                //记录日志
                _loggerService.AddLogger($"测量信息上报失败:参数:{c2s_dto.ToJson()}\r\n返回值:{msg}", 3);
            }
        }

        private string GetUserApiSign(string secret, params string[] dataparams)
        {
            StringBuilder sb = new StringBuilder();
            if (dataparams != null && dataparams.Length > 0)
            {
                foreach (var item in dataparams)
                {
                    sb.Append(item);
                }
            }
            if (!string.IsNullOrEmpty(secret))
            {
                sb.Append(secret);
            }
            else
            {
                sb.Append(ApiSecret);
            }
            string str = sb.ToString();
            string sign = Md5.md5(str, 16).ToLower();
            return sign;
        }
    }
}
