using SafeCampus.Application.Services.Business.CameraGroupService;
using SafeCampus.Application.Services.Business.PersonInfoService;
using SafeCampus.Application.Services.Business.Warn.Dto;
using SafeCampus.Application.Services.Business.Warn.Service;
using SafeCampus.Core.Extension;
using MoYu.FriendlyException;
using SafeCampus.Application.Services.Business.AttendanceService;
using SafeCampus.Application.Services.Business.BuildingService;
using SafeCampus.Application.Services.Business.ClassRoomCallService;
using SafeCampus.Application.Services.Business.ClassRoomCallTaskService;
using SafeCampus.Application.Services.Business.DormitoryService;
using SafeCampus.Web.Core.Controllers.Application.Business;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.DepartmentService;
using SafeCampus.Application.Services.Business.MajorService;
using SafeCampus.Application.Services.Business.PersonSetInfoService;

namespace SafeCampus.Web.Core.Controllers.Application.LargeScreen;

/// <summary>
/// 大屏控制器
/// </summary>
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Tag = "大屏接口", Order = 84)]
[Route("large/screen")]
[AllowAnonymous]
public class LargeScreenController
{
    private readonly IPersonInfoService _personInfoService;
    private readonly ICameraGroupService _cameraGroupService;
    private readonly IWarnInfoService _warnInfoService;
    private readonly ISimpleCacheService _simpleCacheService;
    private readonly IAttendanceService _attendanceService;
    private readonly IBuildingService _buildingService;
    private readonly IDormitoryService _dormitoryService;
    private readonly IConfigService _configService;
    private readonly IClassRoomCallTaskService _classRoomCallTaskService;
    private readonly IClassRoomCallService _classRoomCallService;
    private readonly IDeepelephManager _deepelephManager;
    private readonly IPersonSetInfoService _personSetInfoService;
    private readonly IMajorService _majorService;
    private readonly IDepartmentService _departmentService;


    public LargeScreenController(IPersonInfoService personInfoService, ICameraGroupService cameraGroupService, IWarnInfoService warnInfoService, ISimpleCacheService simpleCacheService, IAttendanceService attendanceService, IBuildingService buildingService, IDormitoryService dormitoryService, IConfigService configService, IClassRoomCallTaskService classRoomCallTaskService, IClassRoomCallService classRoomCallService, IDeepelephManager deepelephManager, IPersonSetInfoService personSetInfoService, IMajorService majorService, IDepartmentService departmentService)
    {
        _personInfoService = personInfoService;
        _cameraGroupService = cameraGroupService;
        _warnInfoService = warnInfoService;
        _simpleCacheService = simpleCacheService;
        _attendanceService = attendanceService;
        _buildingService = buildingService;
        _dormitoryService = dormitoryService;
        _configService = configService;
        _classRoomCallTaskService = classRoomCallTaskService;
        _classRoomCallService = classRoomCallService;
        _deepelephManager = deepelephManager;
        _personSetInfoService = personSetInfoService;
        _majorService = majorService;
        _departmentService = departmentService;
    }

    /// <summary>
    /// 获取大屏首页数据
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetHomeData()
    {
        var startTime = DateTime.Now.Date;
        var entTime = DateTime.Now;
        //学生人数
        //总人数
        var ZRS = await _personInfoService.GetCount(null);
        //男生
        var nan = await _personInfoService.GetCount("GENDER_MALE");
        //女生
        var nv = await _personInfoService.GetCount("GENDER_FEMALE");
        //按设备分组统计设备数量
        var SheBei = await _cameraGroupService.GetBIList();
        //今日告警列表
        var warnlist = await _warnInfoService.GetListNoPage(new WarnInfoSearch
        {
            StartTick = startTime,
            EndTick = entTime

        });

        //今日告警统计按告警类型
        var warnType = typeof(AlarmType).EnumToEnumModel();
        var alarmStatistics = warnType.Select(x => new
        {
            Name = x.Description,
            //Code = x.Name,
            Value = warnlist.Count(xx => xx.AlarmType == x.Name)
        }).Where(x => x.Value > 0).ToList();
        //按场景统计告警类型
        var warnGroup=  _simpleCacheService.Get<List<WarnGroupInfo>>(SafeCampusConst.WarnGroup);
        foreach (var item in warnGroup)
        {
            foreach (var warnGroupSubset in item.Subset)
            {
                warnGroupSubset.Value = warnlist.Count(x => x.AlarmType == warnGroupSubset.Code);
            }
            item.Value = item.Subset.Sum(x => x.Value);
        }

        var list = new List<object>
        {
            new { Name = "男生人数", Value = nan },
            new { Name = "女生人数", Value = nv }
        };
        return new
        {
            //数字统计
            StudentPersonNum=new{TotalNum=ZRS,MaleNum=nan,FemaleNum=nv},
            StudentPersonStatistion=list,
            //统计图表
            AlarmStatisti =new
            {
                //按类型统计
                TypeStatisti=alarmStatistics,
                //按告警分组 统计
                GroupStatisti=warnGroup,
                //告警列表
                WarnList=warnlist
            },
            //设备
            Camera= SheBei,
        };
    }
    /// <summary>
    /// 获取学生归寝大屏数据
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetStudentReturnBed(long buildId)
    {
        if (buildId<=0)
        {
            throw Oops.Oh("没有班级");
        }
        var startTime = DateTime.Now.Date;
        var entTime = DateTime.Now;
        //寝室人数
        var list = await _dormitoryService.GetBiReturnPageList(new ReturnDormitoryISearch
        {
            BuildId = buildId,
            ReturnTime = DateTime.Now
        });

        //总人数
        var Qsrs = list.Sum(x => x.PersonCount);
        //在寝人数
        var zqrs = list.Sum(x => x.DormitoryCount);
        //不在寝人数
        var bzqrs = Qsrs - zqrs;
        //寝室列表
        //归寝时间显示
        var json = await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE,
            BizConfigConst.BIZ_DORMITORY_TIME);
        if (json == null)
        {
            return new ReturnTimeInput();
        }
        var config=JsonConvert.DeserializeObject<ReturnTimeInput>(json.ConfigValue);
        var guiqinsj= config.TimeBegin+" - "+config.TimeEnd;
        //出入记录
        var sushelou =await _buildingService.GetInfo(buildId);
        var crjl = await _attendanceService.GetNoPageList(new AttendanceSearch
        {
            StartTick = startTime,
            EndTick = entTime,
            CameraId = sushelou.InsCameraId,
            CameraIds=new List<string>{sushelou.InsCameraId,sushelou.OutCameraId}
        });
        return new
        {
            Building=new{TotalNum=Qsrs,InNum=zqrs,NoInNum=bzqrs},
            DormitoryList=list,
            ReturnTime=guiqinsj,
            AttendList=crjl,
        };
    }
    /// <summary>
    /// 获取智慧课堂大屏数据
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetSmartClassroom(string personSetId)
    {
        if (string.IsNullOrEmpty(personSetId))
        {
            throw Oops.Oh("没有班级");
        }
        //课堂信息
        var startTime = DateTime.Now.Date;
        var entTime = DateTime.Now;
        //学生信息
        var xuesheng = await _personInfoService.GetPageList(new PersonInfoSearch
            { PageSize = 1000, PageNum = 1, PersonSetId = personSetId });
        //点名信息
        var task =await _classRoomCallTaskService.GetPageList(new ClassRoomCallTaskSearch {PageNum = 1,PageSize = 10,PersonSetId = personSetId });
        
        var taskId = task.List.Any()?task.List.First().TaskId:"";
        var classRoom = await _classRoomCallService.GetNoPageList(new ClassRoomCallSearch { TaskId = taskId });
        //告警信息
        var warnGroup = _simpleCacheService.Get<List<WarnGroupInfo>>(SafeCampusConst.WarnGroup).FirstOrDefault(x=>x.Code=="ZHKT");
        var warnlist = await _warnInfoService.GetListNoPage(new WarnInfoSearch
            { AlarmTypes = warnGroup.Subset.Select(x => x.Code).ToArray(),StartTick = startTime, EndTick = entTime,CameraId = personSetId == "YS001" ? "SXT001" : "SXT002" });
        //告警信息统计
        var tongji = warnlist.GroupBy(x => x.AlarmTypeDesc).Select(x=>new{Labale=x.Key,Value=x.Count()}).ToList();
        foreach (var personInfoDto in xuesheng.List)
        {
            var rollCall=classRoom.Where(x=>x.PersonId==personInfoDto.PersonId).MinBy(x=>x.Tick);
            if (rollCall != null)
            {
                personInfoDto.State = rollCall.Tick.TimeOfDay> TimeSpan.Parse("09:00:00")?"迟到":"正常";
                personInfoDto.InsTime = rollCall.Tick;
            }
            else
            {
                personInfoDto.State = "缺勤";
                personInfoDto.InsTime = null;
            }
        }
        return new
        {
            ClassRoom=new
            {
                Teacher="王明祥",
                ClassTime=DateTime.Now.ToString("yyyy-MM-dd 09:00:00"),
                ClassBreakTime=DateTime.Now.ToString("yyyy-MM-dd 12:00:00"),
                CameraId= personSetId== "YS001" ? "SXT001": "SXT002"
            },
            AlarmList= warnlist,
            //AlarmListCount= warnlist.GroupBy(x=>x.PersonId).Count(),
            Statisti =new{Labale= tongji.Select(x=>x.Labale).ToList(),Value=tongji.Select(x=>x.Value).ToList()},
            NormalClass= xuesheng.List.Count(x=>!warnlist.Any(xx=>xx.PersonId==x.PersonId)),
            StudentList=xuesheng.List,
            //RollCall= classRoom.Where(x=>x.AlarmType!= "class_room_call").ToList()
        };
    }
    /// <summary>
    /// 直播流拉取
    /// 拉流的时候，选pullStreamUrls和rtsPullStreamUrls里面的链接，pushStreamUrls和h5rtsPullStreamUrls直接忽略。
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <returns></returns>
    public async Task<dynamic> GetStartVideoLive(string sensorId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/start_video_live"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
            })
            .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="sensorId">摄像头id</param>
    /// <param name="videoToken">视频token</param>
    /// <param name="streamId">流ID</param>
    /// <returns></returns>
    public async Task<dynamic> GetStopVideoLive(string sensorId, string videoToken, string streamId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/stop_video_live"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
                videoToken,
                streamId
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"]["streamId"].ToString();
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 获取宿舍楼列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<BuildingInfoDto>> GetNoPageList()
    {
        return await _buildingService.GetNoPageList();
    }
    /// <summary>
    /// 获取班级列表
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetPersonSetNoPageList(long? majorId,string setName)
    {
        return await _personSetInfoService.GetPageList(majorId, setName);
    }
    /// <summary>
    /// 获取专业
    /// </summary>
    /// <param name="depId">院系id</param>
    /// <returns></returns>
    public async Task<dynamic> GetMajorNoPageList(long? depId)
    {
        return await _majorService.GetNoPageList(new MajorSearch{DepId = depId});
    }
    /// <summary>
    /// 获取院系
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetDepartment()
    {
        return await _departmentService.GetNoPageList(new DepartmentSearch());
    }
}