using Dm;
using MoYu.FriendlyException;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.ClassRoomCallService;
using SafeCampus.Application.Services.Business.ClassRoomCallTaskService;
using SafeCampus.Core.Extension;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 教室点名接口
/// </summary>
[Route("/business/[controller]")]
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 95,Tag = "教室点名管理")]
public class ClassRoomCallApi : IDynamicApiController
{
    private readonly IClassRoomCallTaskService _classRoomCallTaskService;
    private readonly IClassRoomCallService _classRoomCallService;
    private readonly IDeepelephManager _deepelephManager;

    public ClassRoomCallApi(IDeepelephManager deepelephManager, IClassRoomCallTaskService classRoomCallTaskService, IClassRoomCallService classRoomCallService)
    {
        _deepelephManager = deepelephManager;
        _classRoomCallTaskService = classRoomCallTaskService;
        _classRoomCallService = classRoomCallService;
    }
    /// <summary>
    /// 点名事件查询
    /// </summary>
    /// <param name="search">查询参数</param>
    /// <returns></returns>
    [Obsolete]
    public async Task<dynamic> GetRoomCall(ClassRoomCallTaskSearchRequest search)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/class-room-call/data/query"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                beginTime = new DateTimeOffset(search.startTime).ToUnixTimeMilliseconds(),
                endTime = new DateTimeOffset(search.endTime).ToUnixTimeMilliseconds(),
                cameraId = search.cameraId,
                search.taskId,
                pageIndex = search.PageNum,
                pageSize = search.PageSize,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        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>
    /// 点名任务下发
    /// </summary>
    /// <returns></returns>
    public async Task<bool> TaskSubmit(ClassRoomCallTaskAdd input)
    {
        var taskId = DateTime.Now.ToString("yyyyMMddHHmmssss");// Guid.NewGuid().ToString("N");
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/class-room-call/task/submit"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                taskId,
                continueTime = input.ContinueTime,
                cameraId = input.CameraId,
                personSetId = input.PersonSetId,
                similarity = input.Similarity
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        await _classRoomCallTaskService.Add(new ClassRoomCallTaskDto
        {
            CameraId = input.CameraId,
            CreateTime = DateTime.Now,
            ContinueTime = input.ContinueTime,
            EndTime = DateTime.Now.AddMinutes(input.ContinueTime),
            PersonSetId = input.PersonSetId,
            Similarity = input.Similarity,
            TaskId = taskId,
        });
        return true;
    }

    /// <summary>
    /// 删除点名任务,删除关联点名数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<bool> Delete(long id)
    {
        return await _classRoomCallTaskService.Remove(id);
    }
    /// <summary>
    /// 获取点名任务列表
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<ClassRoomCallTaskDto>> GetTaskPageList(ClassRoomCallTaskSearch search)
    {
        return await _classRoomCallTaskService.GetPageList(search);
    }

    /// <summary>
    /// 添加点名记录
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [Obsolete]
    public async Task<bool> Add(ClassRoomCallDto input)
    {
        return await _classRoomCallService.Add(input);
    }

    /// <summary>
    /// 修改点名信息，人工处理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [Obsolete]
    public async Task<bool> Update(ClassRoomCallUpdate input)
    {
        return await _classRoomCallService.Update(input);
    }
    /// <summary>
    /// 手动点名
    /// </summary>
    /// <returns></returns>
    public async Task<bool> ManualRoll(List<ClassRoomCallInsert> input)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        foreach (var item in input)
        {
            var model = new ClassRoomCallDto
            {
                TenantCode = appSettings.TenantCode,
                PoiId = appSettings.PoiId,
                TaskId = item.TaskId,
                AlarmType = "class_room_call",
                AlarmTypeDesc = AlarmType.class_room_call.GetDescription(),
                EventId ="",
                CameraId = "",
                Tick = DateTime.Now,
                PersonSetId = item.PersonSetId,
                PersonId = item.PersonId,
                Similarity =  1,
                FaceScore = 100,
                SnapshotUrl = "",
                SnapshotData = "",  
                Rects = "",
                Extend = "",
                CreateTime = DateTime.Now,
                TrackId = "SDDM"+ item.PersonId
            };
            await _classRoomCallService.Add(model);
        }

        return true;
    }

    /// <summary>
    /// 删除点名记录（只可删除待处理的记录）
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<bool> Remove(long id)
    {
        return await _classRoomCallService.Remove(id);
    }

    /// <summary>
    /// 分页获取列表
    /// </summary>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<ClassRoomCallList>> GetPageList(ClassRoomCallSearch search)
    {
        return await _classRoomCallService.GetPageList(search);
    }

    /// <summary>
    /// 不分页获取列表
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    public async Task<List<ClassRoomCallList>> GetNoPageList(ClassRoomCallSearch search)
    {
        return await _classRoomCallService.GetNoPageList(search);
    }
}