using Microsoft.AspNetCore.SignalR;
using MoYu.FriendlyException;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Web.Core.Controllers.Application.Business.Dto;
using SafeCampus.Web.Core.Hub;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 预警事件查询接口
/// </summary>
[Route("/business/[controller]")]
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 93,Tag = "预警数据同步")]
[Obsolete]
public class AlarmApi:IDynamicApiController
{
    private readonly IDeepelephManager _deepelephManager;
    private readonly IHubContext<SubscribeHub, IChatClient> _hubContext;

    public AlarmApi(IDeepelephManager deepelephManager, IHubContext<SubscribeHub, IChatClient> hubContext)
    {
        _deepelephManager = deepelephManager;
        _hubContext = hubContext;
    }

    /// <summary>
    /// 预警列表（同步数据）
    /// </summary>
    /// <param name="search">查询信息</param>
    /// <returns></returns>
    public async Task<dynamic> GetAlarmListSync(AlarmSearch search)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/alarm/query-list"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                //alarmType=search.alarmType.GetDescription(),
                //beginTime=search.beginTime.HasValue?search.beginTime.Value.ToString("yyyy-MM-dd HH:mm:ss") :"",
                //endTime= search.endTime.HasValue ? search.endTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                //search.cameraId,
                pageIndex=search.PageNum,
                pageSize=search.PageSize,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        //if ((bool)model["success"])
        //{
        //    return model["data"];
        //}

        //throw Oops.Oh(model["message"].ToString());
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        if (model["data"] != null)
        {
            return new
            {
                pageNum = search.PageNum,
                pageSize = model["data"]["size"],
                total = model["data"]["total"],
                pages = model["data"]["pages"],
                list = model["data"]["items"]
            };
        }
        return new
        {
            pageNum = search.PageNum,
            pageSize = 0,
            total = 0,
            pages = 0,
            list = new List<string>()
        };
    }
    /// <summary>
    /// 根据预警id查询预警（同步数据）
    /// </summary>
    /// <param name="alarmId">预警id</param>
    /// <returns></returns>
    public async Task<dynamic> GetAlarmByIdSync(string alarmId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/alarm/query"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                alarmId
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 发送分组消息
    /// </summary>
    /// <param name="group"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    public async Task<bool> SendGroupMsg(string group,string msg)
    {
        await _hubContext.Clients.Group(group).ReceiveMessage("System", msg);
        return true;
    }
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="user"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    public async Task<bool> SendMsg(string user, string msg)
    {
        await _hubContext.Clients.All.ReceiveMessage(user,msg);
        return true;
    }
    /// <summary>
    /// 测试
    /// </summary>
    /// <returns></returns>
    public async Task<bool> Test()
    {
        Thread.Sleep(5000);
        return true;
    }
}