using JT808.Protocol.MessageBody;
using JT808.Protocol;
using langguanApi.Model;
using langguanApi.Service;
using langguanApi.Service.HJ212;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Utilities;
using System.Text;
using JT808.Protocol.Extensions;
using static langguanApi.Service.WeatherService;
using langguanApi.Common.Gps;
using NPOI.SS.Formula.Functions;
using static langguanApi.Common.Gps.ProtocolParser;
namespace langguanApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly HomeService _homeService;
        public HomeController(HomeService homeService)
        {
            _homeService = homeService;
        }
        /// 
        /// 首页view
        /// 
        /// 
        [HttpGet("view")]
        public async Task View()
        {
            return Ok(await _homeService.View());
        }
        [HttpGet("test")]
        /// 
        /// test
        /// 
        /// 数字
        /// 字符串
        /// 
        public async Task test(int num = 1, string key = "")
        {
            // 示例数据(需替换为实际接收到的协议数据)
            string hexData = "787811010868120321167279808D3202001AB12F0D0A";
            byte[] loginPacket = BuildLoginPacket("123456789012345"); // 替换为实际的IMEI
   
            //       Console.WriteLine("经度:" + lon + " 纬度:" + lat);
            //  string rawText = "数据报:##0250QN=20240424224800000;ST=22;CN=2011;PW=123456;MN=LGYC022024690001;Flag=5;CP=&&DataTime=20240424224800;a34001-Rtd=356.2";
            //NetPackage netPackage = NetPackage.Parse(rawText, null);
            //((NetServer)Server).RaiseReceivedData(this, netPackage, rawText);
            return Ok();
        }
        public static Position? ParsePosition(byte[] data)
        {
            // 根据协议中的位置信息的偏移量和长度进行解析
            int positionOffset = 21; // 位置信息在数据中的偏移量
            int latitudeOffset = positionOffset + 0;
            int longitudeOffset = positionOffset + 4;
            int altitudeOffset = positionOffset + 8;
            // 检查数组长度是否足够长
            if (data.Length < altitudeOffset + 2)
            {
                Console.WriteLine("Data array is not long enough to contain position information.");
                return null;
            }
            // 解析纬度(单位:百万分之一度)
            int rawLatitude = BitConverter.ToInt32(data, latitudeOffset);
            double latitude = rawLatitude / 1000000.0;
            // 解析经度(单位:百万分之一度)
            int rawLongitude = BitConverter.ToInt32(data, longitudeOffset);
            double longitude = rawLongitude / 1000000.0;
            // 解析高度(单位:米)
            int rawAltitude = BitConverter.ToInt16(data, altitudeOffset);
            double altitude = rawAltitude;
            return new Position
            {
                Latitude = latitude,
                Longitude = longitude,
                Altitude = altitude
            };
        }
        static byte[] BuildLoginPacket(string imei)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryWriter writer = new BinaryWriter(ms);
                writer.Write(new byte[] { 0x78, 0x78 }); // 起始位
                writer.Write((byte)0x0D); // 包长度
                writer.Write((byte)0x01); // 协议号
                byte[] imeiBytes = Encoding.ASCII.GetBytes(imei);
                writer.Write(imeiBytes);
                writer.Write((short)0x0001); // 信息序列号
                byte[] content = ms.ToArray();
                short crc = CalculateCRC(content, 2, content.Length - 2);
                writer.Write(crc); // 错误校验
                writer.Write(new byte[] { 0x0D, 0x0A }); // 停止位
                return ms.ToArray();
            }
        }
        static short CalculateCRC(byte[] data, int start, int length)
        {
            // CRC计算方法(参考协议中的CRC-ITU算法)
            ushort crc = 0xFFFF;
            for (int i = start; i < start + length; i++)
            {
                crc = (ushort)(crc ^ (data[i] << 8));
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x8000) != 0)
                    {
                        crc = (ushort)((crc << 1) ^ 0x1021);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                }
            }
            return (short)crc;
        }
        static void ParseServerResponse(byte[] data, int length)
        {
            if (length < 10) // 根据协议响应包最小长度
            {
                Console.WriteLine("响应包长度错误");
                return;
            }
            if (data[0] == 0x78 && data[1] == 0x78)
            {
                Console.WriteLine("起始位正确");
                byte protocolNumber = data[3];
                if (protocolNumber == 0x01)
                {
                    Console.WriteLine("协议号正确: 登录信息包响应");
                    byte[] sequenceNumber = new byte[2];
                    Array.Copy(data, 4, sequenceNumber, 0, 2);
                    Console.WriteLine($"信息序列号: {BitConverter.ToString(sequenceNumber)}");
                    byte[] crc = new byte[2];
                    Array.Copy(data, length - 4, crc, 0, 2);
                    Console.WriteLine($"CRC: {BitConverter.ToString(crc)}");
                }
            }
        }
        static void ParseLocationPacket(byte[] data, int length)
        {
            if (length < 16) // 根据协议位置数据包最小长度
            {
                Console.WriteLine("位置数据包长度错误");
                return;
            }
            if (data[0] == 0x78 && data[1] == 0x78)
            {
                Console.WriteLine("起始位正确");
                byte protocolNumber = data[3];
                if (protocolNumber == 0x12) // 位置数据包协议号
                {
                    Console.WriteLine("协议号正确: 位置数据包");
                    int latitude = (data[5] & 0xFF) << 24 | (data[6] & 0xFF) << 16 | (data[7] & 0xFF) << 8 | (data[8] & 0xFF);
                    int longitude = (data[9] & 0xFF) << 24 | (data[10] & 0xFF) << 16 | (data[11] & 0xFF) << 8 | (data[12] & 0xFF);
                    double lat = latitude / 1800000.0;
                    double lon = longitude / 1800000.0;
                    Console.WriteLine($"纬度: {lat}, 经度: {lon}");
                }
            }
        }
        public struct Position
        {
            public double Latitude;
            public double Longitude;
            public double Altitude;
        }
    }
}