using System.Dynamic;
using Infrastructure;
using Infrastructure.Cache;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.DroneDockManage;
using OpenAuth.App.ServiceApp.DroneDockManage.Response;
using StackExchange.Redis;

namespace OpenAuth.WebApi.Controllers.ServiceControllers.DroneDockManage
{
    /// <summary>
    /// 机场运维
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AirportMaintenanceController : ControllerBase
    {
        private readonly AirportMaintenanceApp _app;
        private readonly RedisCacheContext _cache;
        private readonly HttpClient _httpClient; 
        private readonly IAuth _auth;

        public AirportMaintenanceController(AirportMaintenanceApp app, 
             RedisCacheContext cache, HttpClient httpClient,IAuth auth)
        {
            _app = app;
            _cache = cache;
            _httpClient = httpClient;
            _auth = auth;
        }
        #region redis 多用户控制

        /// <summary>
        /// 添加修改mqtt客户端信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddOrUpdateRedisUser(MqttClientResp info)
        {
            var result = new Response<bool>();
            try
            {
                var clientKey = $"client:{info.UserId}";
                string lockSetKey = "locked_users";

                // 查询所有锁定用户
                var existingLocked = await _cache.SetMembersAsync(lockSetKey);

                // 如果有锁定用户，并且锁定的用户不是当前用户，则拒绝
                if (existingLocked.Length > 0 && info.IsLock == true)
                {
                    bool isCurrentUserLocked = existingLocked.Any(u => u == info.UserId);
                    if (!isCurrentUserLocked)
                    {
                        result.Code = 400;
                        result.Message = "已有其他用户处于锁定状态，不能添加新的锁定用户。";
                        result.Result = false;
                        return result;
                    }
                }

                // 存客户端信息
                _cache.HashSetAsync(clientKey, new HashEntry[]
                {
                    new("ClientId", info.ClientId),
                    new("UserId", info.UserId),
                    new("UserName", info.UserName),
                    new("ConnectTime", info.ConnectTime.ToString("O")),
                    new("IsLock", info.IsLock ? "true" : "false")
                });

                if (info.IsLock)
                {
                    await _cache.SetAddAsync(lockSetKey, info.UserId);
                }
                else
                {
                    await _cache.SetRemoveAsync(lockSetKey, info.UserId);
                }

                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取当前用户mqtt客户端信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<MqttClientResp>> GetRedisUser(string id)
        {
            var result = new Response<MqttClientResp>();
            try
            {
                result.Result = ParseClient(await _cache.HashGetAllAsync($"client:{id}"));
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        private MqttClientResp ParseClient(HashEntry[] entries)
        {
            if (entries == null || entries.Length == 0)
                return null;
            var dict = entries.ToDictionary(e => e.Name.ToString(), e => e.Value.ToString());
            return new MqttClientResp
            {
                ClientId = dict["ClientId"],
                UserId = dict["UserId"],
                UserName = dict["UserName"],
                ConnectTime = DateTime.Parse(dict["ConnectTime"]),
                IsLock = bool.Parse(dict["IsLock"])
            };
        }

        /// <summary>
        /// 获取所有锁定的用户客户端信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<MqttClientResp>> GetLockedClients()
        {
            var userIds = await _cache.SetMembersAsync("locked_users");

            var result = new List<MqttClientResp>();

            foreach (var userId in userIds)
            {
                var entries = await _cache.HashGetAllAsync($"client:{userId}");
                if (entries.Length > 0)
                    result.Add(ParseClient(entries));
            }

            return result;
        }

        #endregion
        /// <summary>
        /// 获取态势感知项目id
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public Response<dynamic> GetTsgzProjectId()
        {
            return _app.GetdTsgzProjectId();
        }
        [HttpGet]
        public Task<Response<dynamic>> GetTsgzAccessToken()
        {
            return _app.GetTsgzAccessToken();
        }
        
        // todo 是否允许获取无人机控制权
        // 先查询有没有锁，如果锁是自己的，则允许，如果锁不是自己的，则不允许，如果没有锁，则查看无人机状态是不是空闲中
        //  mode_code 0 空闲中 4 作业中 
        

        /// <summary>
        /// 申请调用无人机
        /// </summary>
        /// <param name="dronePortSn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<dynamic>> ApplyDroneControl(string dronePortSn)
        {
           return await _app.ApplyDroneControl(dronePortSn);
        }
    }
}
