using Infrastructure.CloudSdk.mqttmessagecenter;
using OpenAuth.App.ServiceApp;
using OpenAuth.Repository.Domain;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace OpenAuth.WebApi.Model.mqtt
{
    public class ThingRequestHandler : IMqttMessageHandler
    {
        private readonly ILogger<ThingRequestHandler> _logger;
        private readonly MqttClientManager _mqttClientManager;
        AirportMaintenanceApp _app;
        ManageApp _manageApp;
        private readonly MqttMessageCenter _mqttCenter;

        public ThingRequestHandler(ILogger<ThingRequestHandler> logger, MqttClientManager mqttClientManager, AirportMaintenanceApp app, ManageApp manageApp, MqttMessageCenter mqttCenter)
        {
            _logger = logger;
            _mqttClientManager = mqttClientManager;
            _app = app;
            _manageApp = manageApp;
            _mqttCenter = mqttCenter;
        }

        public bool CanHandle(string topic)
        {
            return topic.Contains("/requests");
        }
        string bid, tid, previousgateway;
        long timestamp;
        public async Task HandleAsync(string topic, string payload)
        {
            _logger.LogError($"[Request] Topic={topic}, Payload={payload}");
            if (payload.Contains("config"))
            {
                var root = JsonNode.Parse(payload)?.AsObject();
                if (root == null)
                {
                    return;
                }
                string gateway = root["gateway"]?.ToString() ?? "";
                if (previousgateway == gateway)
                {
                    return;
                }
                bid = root["bid"]?.ToString() ?? "";
                tid = root["tid"]?.ToString() ?? "";
                timestamp = long.Parse(root["timestamp"]?.ToString() ?? "0");
                var requestData = new
                {
                    bid = bid,
                    method = "config",
                    tid = tid,
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    gateway = gateway,
                    data = new
                    {
                        app_id = "164821",
                        app_key = "a5f80db847b285fd5fe51db7aa9f606",
                        app_license = "QXJX7VKLC03wYHujKbchjqIBiSgpjv46hLGY4B9Ez46RllbKZN9H+rVawveJWbbX/l4r6zPM5aZ/EzmCESUg046rSRziVhDOJ0tPw1cWqKAq6TuqaLK5bH88UFyB3ahv66YF3D/NmAgOfj5VRtT55cc67u/OIsF54lxhs/raAv0=",
                        ntp_server_host = "ntp.aliyun.com",
                        //ntp_server_host = "175.27.168.120",
                        //ntp_server_port = 6012
                    }
                };
                string payloadreq = JsonSerializer.Serialize(requestData);
                await _mqttClientManager.PublishAsync($"thing/product/{gateway}/requests_reply", payloadreq);
                await _app.UpdateGateway(gateway, tid);
            }
            if (payload.Contains("airport_bind_status"))
            {
                //解析返回的设备sn
                var root = JsonNode.Parse(payload)?.AsObject();
                if (root == null)
                {
                    return;
                }
                // 从 data.devices 中提取 sn 列表
                var snList = root?["data"]?["devices"]?.AsArray()
                    .Select(d => d?["sn"]?.ToString())
                    .Where(sn => !string.IsNullOrEmpty(sn))
                    .ToList();

                // 生成 bind_status 对象列表
                var bindStatusList = snList?.Select(sn => new
                {
                    device_callsign = "sdhc",
                    is_device_bind_organization = false,
                    organization_id = "371300",
                    organization_name = "sdhc",
                    sn = sn
                }).ToArray();

                // 构造最终请求对象
                var requestData = new
                {
                    bid = Guid.NewGuid().ToString(),
                    data = new
                    {
                        output = new
                        {
                            bind_status = bindStatusList
                        },
                        result = 0
                    },
                    tid = Guid.NewGuid().ToString(),
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    method = "airport_bind_status"
                };
                string payloadreq = JsonSerializer.Serialize(requestData);
                string getway = topic.Split('/')[2];
                await _mqttClientManager.PublishAsync($"thing/product/{getway}/requests_reply", payloadreq);

            }
            if (payload.Contains("airport_organization_get"))//
            {
                var root = JsonNode.Parse(payload)?.AsObject();

                var requestData = new
                {
                    bid = Guid.NewGuid().ToString(),
                    data = new
                    {
                        output = new
                        {
                            organization_name = "sdhc"
                        },
                        result = 0
                    },
                    tid = Guid.NewGuid().ToString(),
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    method = "airport_organization_get"
                };
                string payloadreq = JsonSerializer.Serialize(requestData);
                string getway = topic.Split('/')[2];
                await _mqttClientManager.PublishAsync($"thing/product/{getway}/requests_reply", payloadreq);

            }
            if (payload.Contains("airport_organization_bind"))
            {
                string getway = topic.Split('/')[2];
                // 解析 JSON
                var root = JsonNode.Parse(payload)?.AsObject();
                // 获取 bind_devices 数组
                var bindDevices = root?["data"]?["bind_devices"]?.AsArray();
                string dronesn = "", uavsn = "";
                LasaDronePort lasaDronePort = new LasaDronePort();
                LasaUav lasaUav = new LasaUav();
                if (bindDevices != null)
                {
                    foreach (var device in bindDevices)
                    {
                        var obj = device?.AsObject();
                        if (obj["device_model_key"].ToString().Contains("3-"))
                        {
                            lasaDronePort.Id = Guid.NewGuid().ToString();
                            lasaDronePort.OrgId = obj["organization_id"]?.ToString();
                            lasaDronePort.CreateTime = DateTime.Now;
                            lasaDronePort.IsDelete = false;
                            lasaDronePort.TypeId = "Dock 3";
                            lasaDronePort.Sn = obj["sn"].ToString();
                            lasaDronePort.BindStatus = 1;
                            lasaDronePort.Name = obj["device_callsign"]?.ToString();
                            dronesn = obj["sn"].ToString();
                            lasaDronePort.GateWay = getway;
                        }
                        else
                        {
                            lasaUav.Id = Guid.NewGuid().ToString();
                            lasaUav.IsDelete = false;
                            //lasaUav.TypeId = obj["device_model_key"].ToString();
                            lasaUav.TypeId = "M4TD";
                            lasaUav.CreateTime = DateTime.Now;
                            lasaUav.Sn = obj["sn"].ToString();
                            lasaUav.PId = lasaDronePort.Id;
                            lasaUav.Name = obj["device_callsign"]?.ToString();
                            uavsn = obj["sn"].ToString();
                        }
                    }
                }
                uavsn = uavsn == "" ? "01" : uavsn;
                _manageApp.AddDronePort(lasaDronePort);
                _manageApp.AddLasaUav(lasaUav);
                var topics = new List<string>();
                topics.AddRange(new[]
                {
                    $"sys/product/{dronesn}/osd",
                    $"sys/product/{uavsn}/osd", 
                });
                await _mqttCenter.SubscribeAsync(topics.ToArray());
                var requestData = new
                {
                    bid = Guid.NewGuid().ToString(),
                    data = new
                    {
                        output = new
                        {
                            err_infos = new[]
                            {
                                new
                                {
                                    err_code = 0,
                                    sn = dronesn
                                },
                                new
                                {
                                    err_code = 0,
                                    sn = uavsn
                                }
                            }
                        },
                        result = 0
                    },
                    tid = Guid.NewGuid().ToString(),
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    method = "airport_organization_bind"
                };
                string payloadreq = JsonSerializer.Serialize(requestData);
                await _mqttClientManager.PublishAsync($"thing/product/{getway}/requests_reply", payloadreq);
            }
        }
    }
}
