using Masuit.Tools.DateTimeExt;
using MoYu.FriendlyException;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.CameraInfoService;
using SafeCampus.Application.Services.Business.DormitoryService;
using SafeCampus.Application.Services.Business.PersonSetInfoService;
using System;
using SafeCampus.Core.Extension;
using TencentCloud.Iot.V20180123.Models;
using TencentCloud.Nlp.V20190408.Models;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 寝室管理接口
/// </summary>
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 86, Tag = "寝室管理")]
[Route("/business/dormitory")]
[RolePermission]
public class DormitoryController 
{
    private readonly IDormitoryService _dormitoryService;
    private readonly IConfigService _configService;
    private readonly IDeepelephManager _deepelephManager;
    private readonly IPersonSetInfoService _personSetInfoService;
    private readonly ICameraInfoService _cameraInfoService;

    public DormitoryController(IDormitoryService dormitoryService, IConfigService configService, IDeepelephManager deepelephManager, IPersonSetInfoService personSetInfoService, ICameraInfoService cameraInfoService)
    {
        _dormitoryService = dormitoryService;
        _configService = configService;
        _deepelephManager = deepelephManager;
        _personSetInfoService = personSetInfoService;
        _cameraInfoService = cameraInfoService;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="input">添加参数</param>
    /// <returns></returns>
    public async Task<bool> Add(DormitoryInfoDto input)
    {
        return await _dormitoryService.Add(input);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="input">添加参数</param>
    /// <returns></returns>
    public async Task<bool> Update(DormitoryInfoDto input)
    {
        return await _dormitoryService.Update(input);
    }
    /// <summary>
    /// 获取详情（带寝室人员列表）
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<DormitoryInfoDto> GetInfo(long id)
    {
        return await _dormitoryService.GetInfo(id);
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id">id</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<bool> Delete(BaseIdListInput id)
    {
        return await _dormitoryService.Delete(id.Ids);
    }
    /// <summary>
    /// 寝室分配人员
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> SetAssignPerson(DormitorySetPersonInput input)
    {
        return await _dormitoryService.SetAssignPerson(input);
    }
    /// <summary>
    /// 获取列表
    /// </summary>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<DormitoryInfoList>> GetPageList(DormitoryInfoSearch search)
    {
        return await _dormitoryService.GetPageList(search);
    }
    /// <summary>
    /// 查询归寝寝室列表
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<ReturnDormitoryList>> GetReturnPageList(ReturnDormitoryISearch search)
    {
        if (!search.BuildId.HasValue)
        {
            throw Oops.Oh("填写宿舍楼id");
        }
        return await _dormitoryService.GetReturnPageList(search);
    }
    /// <summary>
    /// 查询寝室归寝详情
    /// </summary>
    /// <param name="id">寝室id</param>
    /// <param name="returnTime">归寝日期</param>
    /// <returns></returns>
    public async Task<ReturnDormitoryDto> GetReturnInfo(long id,DateTime returnTime)
    {
        var model= await _dormitoryService.GetReturnInfo(id, returnTime);
        model.AttendanceDtos = model.AttendanceDtos?.GroupBy(x => x.PersonId).Select(x => x.MaxBy(xx=>xx.Tick)).ToList();
        foreach (var modelPersonInfo in model.PersonInfos)
        {
            modelPersonInfo.Attendances = null;
        }
        return model;
    }
    /// <summary>
    /// 设置归寝时间
    /// </summary>
    /// <returns></returns>
    public async Task<bool> SetReturnTime(ReturnTimeInput input)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var configId = 0;
        var query = await $"{appSettings.SXAPIURL}/dfield-api/ecology/func/v1/conf/query-paged"
            .SetBody(new
            {
                funcType= "attendance",
                pageIndex=1,
                pageSize=10,
                tenantCode = appSettings.TenantCode,
                poiId =appSettings.PoiId,
                token = _deepelephManager.GetToken(),
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var queryList = JsonConvert.DeserializeObject<JObject>(query);
        if (queryList["data"]?[0] != null)
        {
            configId = queryList["data"][0]["configId"].ParseToInt();
        }
        var time = new { timeBegin = input.TimeBegin, timeEnd = input.TimeEnd };
        var personSetIds = await _personSetInfoService.GetPageList(null,null);
        var cameras = await _cameraInfoService.GetPageList(new CameraSearch{PageSize = 1000,PageNum = 1});
        var body = new
        {
            token = _deepelephManager.GetToken(),
            tenantCode = appSettings.TenantCode,
            poiId = appSettings.PoiId,
            enable = true,
            configId,
            funcType = "attendance",
            funcStart = input.FuncStart,
            funcEnd = input.FuncEnd,
            enableAlarmRateLimit = false,
            cameras = cameras.List.Select(x => new
            {
                cameraId = x.SensorId,
                cameraName = x.SensorName,
                calibrationContentStatus = false,
                deviceStatus = "online"
            }).ToList(),
            timePeriodType = "every_day",
            timePeriod = new List<object> { time },
            similarity = 0.4,
            personSetIds = personSetIds.Select(x => x.PersonSetId).ToArray()
        };
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/func/v1/conf/submit"
            .SetBody(body)
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var sysConfig = await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE, BizConfigConst.BIZ_DORMITORY_TIME);
            if (sysConfig != null)
            {
                await _configService.Edit(new ConfigEditInput
                {
                    Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                    ConfigKey = BizConfigConst.BIZ_DORMITORY_TIME,
                    ConfigValue = JsonConvert.SerializeObject(input)
                });
            }
            else
            {
                await _configService.Add(new ConfigAddInput
                {
                    Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                    ConfigKey = BizConfigConst.BIZ_DORMITORY_TIME,
                    ConfigValue = JsonConvert.SerializeObject(input)
                });
            }
            return true;
        }
        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 获取归寝时间
    /// </summary>
    /// <returns></returns>
    public async Task<ReturnTimeInput> GetReturnTime()
    {
        var json = await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE,
            BizConfigConst.BIZ_DORMITORY_TIME);
        if (json == null)
        {
            return new ReturnTimeInput();
        }
        return JsonConvert.DeserializeObject<ReturnTimeInput>(json.ConfigValue);
    }
}