using System.Dynamic;
using System.Net;
using System.Text;
using Infrastructure;
using Infrastructure.Cache;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenAuth.App.Interface;

namespace OpenAuth.App.ServiceApp.DroneDockManage
{
    public class AirportMaintenanceApp
    {
        private readonly RedisCacheContext _cache;
        private readonly HttpClient _httpClient;
        private readonly IAuth _auth;

        public AirportMaintenanceApp(
            RedisCacheContext cache, HttpClient httpClient, IAuth auth)
        {
            _cache = cache;
            _httpClient = httpClient;
            _auth = auth;
        }

        public Response<dynamic> GetdTsgzProjectId()
        {
            var conf = ConfigHelper.GetConfigRoot();
            var projectId = conf["TaiShiGanZhi:ProjectId"];
            return new Response<dynamic>()
            {
                Result = new
                {
                    ProjectId = projectId
                }
            };
        }

        public async Task<Response<dynamic>> GetTsgzAccessToken()
        {
            //using var client = new HttpClient();
            var conf = ConfigHelper.GetConfigRoot();
            var apiUrl = conf["TaiShiGanZhi:ApiUrl"];
            var loginUrl = conf["TaiShiGanZhi:LoginUrl"];
            var param = new
            {
                account = conf["TaiShiGanZhi:Username"],
                password = conf["TaiShiGanZhi:Password"]
            };
            var content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8,
                "application/json");
            // 执行创建数据存储
            var response = await _httpClient.PostAsync(apiUrl + loginUrl, content);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                return new Response<dynamic>()
                {
                    Result = false,
                    Message = "登录失败"
                };
            }

            var result = await response.Content.ReadAsStringAsync();
            var jsonObject = JObject.Parse(result);
            if (jsonObject["code"].ToInt() == 200)
            {
                return new Response<dynamic>()
                {
                    Result = new
                    {
                        AccessToken = jsonObject["result"]["token"].ToString()
                    }
                };
            }

            return new Response<dynamic>()
            {
                Code = 500,
                Message = "获取态势感知token失败"
            };
        }

        public async Task<Response<dynamic>> ApplyDroneControl(string dronePortSn)
        {
            var conf = ConfigHelper.GetConfigRoot();
            var apiUrl = conf["TaiShiGanZhi:ApiUrl"];
            var currentUserId = _auth.GetUserId();
            string lockSetKey = "locked_users";
            dynamic info = new ExpandoObject();
            // 查询所有锁定用户
            var existingLocked = await _cache.SetMembersAsync(lockSetKey);

            // 如果有锁定用户，并且锁定的用户不是当前用户，则拒绝
            if (existingLocked.Length > 0)
            {
                var isCurrentUserLocked = existingLocked.Any(u => u == currentUserId);
                if (!isCurrentUserLocked)
                {
                    info.approved = false;
                    // 已被其他用户锁定
                    return new Response<dynamic>
                    {
                        Code = 400,
                        Message = "已被其他用户锁定",
                        Result = info
                    };
                }
            }

            info.approved = true;
            var result = await _httpClient.GetAsync(apiUrl + $"/api/Manage/GetDronePortInfo?dronePortSn={dronePortSn}");
            if (result.StatusCode == HttpStatusCode.OK)
            {
                var json = await result.Content.ReadAsStringAsync();
                var jsonObject = JObject.Parse(json);
                info.dronePortState = jsonObject["result"]?["modeCode"];
                info.droneInDock = jsonObject["result"]?["droneInDock"];
                return new Response<dynamic>
                {
                    Result = info
                };
            }
            return new Response<dynamic>
            {
                Code = 500,
                Message = "获取无人机状态失败"
            };
        }
    }
}