using Masuit.Tools.Systems;
using SafeCampus.Application.Services.Business.CameraInfoService;
using SafeCampus.Application.Services.Business.PersonInfoService;
using SafeCampus.Application.Services.Business.Warn.Dto;
using SafeCampus.Application.Services.Business.Warn.Service;
using System;

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

/// <summary>
/// 学校画像控制器
/// </summary>
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Tag = "学校画像", Order = 85)]
[Route("violation/portraitSummary")]
[RolePermission]
public class VioPortraitSummary
{
    private readonly IPersonInfoService _personInfoService;
    private readonly ICameraInfoService _cameraInfoService;
    private readonly IWarnInfoService _warnInfoService;

    public VioPortraitSummary(IPersonInfoService personInfoService, ICameraInfoService cameraInfoService, IWarnInfoService warnInfoService)
    {
        _personInfoService = personInfoService;
        _cameraInfoService = cameraInfoService;
        _warnInfoService = warnInfoService;
    }

    /// <summary>
    /// 获取学生性别
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetStudentSex()
    {
        var label = new List<string> { "男", "女" };
        var nan = await _personInfoService.GetCount("GENDER_MALE");
        var nv = await _personInfoService.GetCount("GENDER_FEMALE");
        var value = new List<int>() { nan, nv };
        return new { label, value };
    }

    /// <summary>
    /// 获取学生年龄
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetStudentAge()
    {
        return await _personInfoService.GetAge();
    }

    /// <summary>
    /// 获取地理位置
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetAddress()
    {
        var random = new Random();
        var label = new List<string> { "太原", "大同", "朔州", "忻州", "阳泉", "吕梁", "晋中", "长治", "晋城", "临汾", "运城" };
        var value = label.Select(item => random.Next(12, 999)).ToList();
        //var value = new List<int>() { 10, 5, 8, 5, 1, 3, 4, 7, 6, 5, 1 };
        return new { label, value };
    }

    /// <summary>
    /// 获取属性标签
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetStudentAttr()
    {
        var random = new Random();
        var label = new List<string> { "打闹", "趴桌子", "爱运动", "喜欢读书", "性格孤僻" };
        var value = label.Select(item => random.Next(12, 99)).ToList();
        //var value = new List<int>() { 10, 5, 8, 5, 1 };
        return new { label, value };
    }
    /// <summary>
    /// 学生--告警分类统计
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetStudentDetail(SummarySeach seach)
    {
        var random = new Random();
        var label = new List<string> { "打闹", "趴桌子", "爱运动", "喜欢读书", "性格孤僻" };
        var value = label.Select(item => random.Next(2, 20)).ToList();
        return await Task.FromResult(new { label, value ,PF="93",XF="90"});
    }
    /// <summary>
    /// 学生--出勤情况
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> Attendance(SummarySeach seach)
    {
        switch (seach.SearchType)
        {
            case SearchType.ThisWeek:
            case SearchType.LastWeek:
            case SearchType.ThisMonth:
            default:
                var random = new Random();
                var label = new List<string> { "正常出勤", "缺勤", "迟到" };
                var value = label.Select(item => random.Next(2, 20)).ToList();
                return await Task.FromResult(new { label, value,msg= $"{(value[0] / value.Sum()) *100}%出勤率，在班级中属于中等水平" });
        }
    }
    /// <summary>
    /// 学生--出校
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> OutsideSchool(SummarySeach seach)
    {
        var camera = await _cameraInfoService.GetPageList(new CameraSearch { GroupId = ApplicationConst.XXDM, PageSize = 1000, PageNum = 1 });
        var cameraIds = camera.List.Select(x => x.SensorId).ToList();
        DateTime endWeek = DateTime.Now;
        // 获取本周的第一天（假设一周从周一开始）
        DateTime startOfWeek = endWeek.AddDays(-(int)endWeek.DayOfWeek + (int)DayOfWeek.Monday);
        switch (seach.SearchType)
        {
            case SearchType.ThisWeek:
                var list = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfWeek,
                    EndTick = endWeek
                });
                return await Task.FromResult(new{data= list.Select(x => new { x.Tick, x.PersonName, x.PersonSetName, x.SnapshotUrl }).ToList(), msg= $"有{list.Count}次出校访问经历，在班级中属于优秀水平" });
            case SearchType.LastWeek:
                DateTime startOfLastWeek = startOfWeek.AddDays(-7);
                DateTime endOfLastWeek = startOfLastWeek.AddDays(6).Date.AddDays(1).AddTicks(-1); // 上周的最后一刻
                var list1 = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfLastWeek,
                    EndTick = endOfLastWeek
                });
                return await Task.FromResult(new { data = list1.Select(x => new { x.Tick, x.PersonName, x.PersonSetName, x.SnapshotUrl }).ToList(), msg = $"有{list1.Count}次出校访问经历，在班级中属于优秀水平" });
            case SearchType.ThisMonth:
                DateTime startOfMonth = new DateTime(endWeek.Year, endWeek.Month, 1);
                var list2 = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfMonth,
                    EndTick = endWeek
                });
                return await Task.FromResult(new { data = list2.Select(x => new { x.Tick, x.PersonName, x.PersonSetName, x.SnapshotUrl }).ToList(), msg = $"有{list2.Count}次出校访问经历，在班级中属于优秀水平" });
            default:
                return null;
        }
    }
    /// <summary>
    /// 学生--图书馆
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> Library(SummarySeach seach)
    {
        var data= await StudentSummary(seach, ApplicationConst.TSG);
        return new { data.label, data.value, msg = $"每周平均使用图书馆6次，与班级其他学生相较为频繁" };
    }
    /// <summary>
    /// 学生--食堂
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> Canteen(SummarySeach seach)
    {
        var data= await StudentSummary(seach, ApplicationConst.ST);
        return new { data.label, data.value, msg = $"与全校学生消费情况相比较为节俭" };
    }
    /// <summary>
    /// 学生画像统计
    /// </summary>
    /// <param name="seach"></param>
    /// <param name="groupId"></param>
    /// <returns></returns>
    private async Task<dynamic> StudentSummary(SummarySeach seach,long groupId)
    {
        var camera = await _cameraInfoService.GetPageList(new CameraSearch { GroupId = groupId, PageSize = 1000, PageNum = 1 });
        var cameraIds = camera.List.Select(x => x.SensorId).ToList();
        DateTime endWeek = DateTime.Now;
        // 获取本周的第一天（假设一周从周一开始）
        DateTime startOfWeek = endWeek.AddDays(-(int)endWeek.DayOfWeek + (int)DayOfWeek.Monday);
        var label = new List<string>();
        var value = new List<int>();
        switch (seach.SearchType)
        {
            case SearchType.ThisWeek:
                var list = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfWeek,
                    EndTick = endWeek
                });

                for (var i = startOfWeek; i < endWeek;)
                {
                    label.Add(i.ToString("yyyy-MM-dd"));
                    value.Add(list.Count(x => x.Tick.Year == i.Year && x.Tick.Month == i.Month && x.Tick.Day == i.Day));
                    i = i.AddDays(1);
                }
                return new { label, value };
            case SearchType.LastWeek:
                DateTime startOfLastWeek = startOfWeek.AddDays(-7);
                DateTime endOfLastWeek = startOfLastWeek.AddDays(6).Date.AddDays(1).AddTicks(-1); // 上周的最后一刻
                var list1 = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfLastWeek,
                    EndTick = endOfLastWeek
                });

                for (var i = startOfWeek; i < endWeek;)
                {
                    label.Add(i.ToString("yyyy-MM-dd"));
                    value.Add(list1.Count(x => x.Tick.Year == i.Year && x.Tick.Month == i.Month && x.Tick.Day == i.Day));
                    i = i.AddDays(1);
                }
                return new { label, value };
            case SearchType.ThisMonth:
                DateTime startOfMonth = new DateTime(endWeek.Year, endWeek.Month, 1);
                var list2 = await _warnInfoService.GetListNoPage(new WarnInfoSearch
                {
                    AlarmType = AlarmType.visual_fence.GetDisplay(),
                    CameraIds = cameraIds,
                    PersonId = seach.PersonId,
                    StartTick = startOfMonth,
                    EndTick = endWeek
                });

                for (var i = startOfWeek; i < endWeek;)
                {
                    label.Add(i.ToString("yyyy-MM-dd"));
                    value.Add(list2.Count(x => x.Tick.Year == i.Year && x.Tick.Month == i.Month && x.Tick.Day == i.Day));
                    i = i.AddDays(1);
                }
                return new { label, value};
            default:
                return null;
        }
    }
}