using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.Warn.Dto;
using SafeCampus.Application.Services.Business.Warn.Service;
using SimpleTool;
using SafeCampus.Core.Extension;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Logical;
using SafeCampus.Application.Services.Business;
using SafeCampus.Web.Core.Controllers.Application.Business.Dto;
using System.Collections.Generic;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 预警事件查询接口
/// </summary>
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 92, Tag = "预警事件")]
[Route("/business/warn")]
[RolePermission]
public class WarnInfoController
{
    private readonly IWarnInfoService _warnInfoService;
    private readonly IDeepelephManager _deepelephManager;
    private readonly ISimpleCacheService _simpleCacheService;
    private readonly IConfigService _configService;

    public WarnInfoController(IWarnInfoService warnInfoService, IDeepelephManager deepelephManager, ISimpleCacheService simpleCacheService, IConfigService configService)
    {
        _warnInfoService = warnInfoService;
        _deepelephManager = deepelephManager;
        _simpleCacheService = simpleCacheService;
        _configService = configService;
    }

    /// <summary>
    /// 删除预警信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<bool> DeleteInfoD(long Id)
    {
        return await _warnInfoService.Delete(Id);
    }
    /// <summary>
    /// 编辑预警信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> UpdateInfoU(WarnInfoDto input)
    {
        return await _warnInfoService.Update(input);
    }
    /// <summary>
    /// 获取预警信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<WarnInfoDto> GetInfo(long Id)
    {
        var model = await _warnInfoService.GetInfo(Id);
        if (!string.IsNullOrEmpty(model.Extend))
        {
            var extend = JsonConvert.DeserializeObject<JObject>(model.Extend);
            model.Extend = extend["age"]!=null?$"年龄：{extend["age"]};年龄置信度：{extend["ageProb"]};":"";
        }

        try
        {
            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 = model.AlarmId
                })
                .SetContentType("application/json")
                .PostAsAsync<string>();
            var json = JsonConvert.DeserializeObject<JObject>(str);
            if ((bool)json["success"])
            {
                if (json["data"]["videoUrl"] != null)
                {
                    model.VideoUrl = json["data"]["videoUrl"].ToString();
                }
            }
        }
        catch (SystemException)
        {

        }

        return model;
    }
    /// <summary>
    /// 获取预警信息列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<SqlSugarPagedList<WarnInfoList>> GetList([FromQuery] WarnInfoSearch input)
    {
        return await _warnInfoService.GetList(input);
    }
    /// <summary>
    /// 获取告警分组
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetWarnGroup(string cameraId)
    {
        var list = new List<WarnGroupInfo>();
        list = _simpleCacheService.Get<List<WarnGroupInfo>>(SafeCampusConst.WarnGroup);
        if (list != null)
        {
            if (!string.IsNullOrEmpty(cameraId))
            {
                return list.Where(x => x.CameraId.Contains(cameraId)).ToList();
            }
            return list;
        }
        var basePath = AppContext.BaseDirectory;//获取项目目录
        var json = basePath.CombinePath("SeedData", "Json", "WarnGroup.json");//获取文件路径
        var dataString = FileHelper.ReadFile(json);//读取文件
        list = JsonConvert.DeserializeObject<List<WarnGroupInfo>>(dataString);
        _simpleCacheService.Set(SafeCampusConst.WarnGroup, list);
        return list.Where(x=>x.CameraId.Contains(cameraId)).ToList();
    }
    /// <summary>
    /// 设置场景开关
    /// </summary>
    /// <returns></returns>
    public async Task<bool> SetWarnGroupDevice(ConfigJsonInput input)
    {
        var jsonList = JsonConvert.DeserializeObject<List<WarnGroupInfo>>(input.ConfigJson);
        _simpleCacheService.Set(SafeCampusConst.WarnGroup, jsonList);
        return true;
    }
    /// <summary>
    /// 关联摄像头和告警分组
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> SetWarnGroupCamera(ConfigJsonCamera input)
    {
        var list = _simpleCacheService.Get<List<WarnGroupInfo>>(SafeCampusConst.WarnGroup);
        var model = list.FirstOrDefault(x => x.Code == input.Code);
        if (model != null)
        {
            model.CameraId = input.CameraList;
        }
        _simpleCacheService.Set(SafeCampusConst.WarnGroup, list);
        return true;
    }
    /// <summary>
    /// 设置预警推送设置
    /// </summary>
    /// <returns></returns>
    public async Task<bool> SetWarnPushSetting(ConfigPush push)
    {
        var sysConfig=await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE, BizConfigConst.BIZ_SMS_STATES);
        if (sysConfig != null)
        {
            await _configService.Edit(new ConfigEditInput
            {
                Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                ConfigKey = BizConfigConst.BIZ_SMS_STATES,
                ConfigValue = push.PushState.ToString()
            });
        }
        else
        {
            await _configService.Add(new ConfigAddInput
            {
                Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                ConfigKey = BizConfigConst.BIZ_SMS_STATES,
                ConfigValue = push.PushState.ToString()
            });
        }
        var sysConfigDay = await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE, BizConfigConst.BIZ_SMS_STATES_DAY);
        if (sysConfigDay != null)
        {
            await _configService.Edit(new ConfigEditInput
            {
                Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                ConfigKey = BizConfigConst.BIZ_SMS_STATES_DAY,
                ConfigValue = push.DaySum.ToString()
            });
        }
        else
        {
            await _configService.Add(new ConfigAddInput
            {
                Category = CateGoryConst.CONFIG_BIZ_DEFINE,
                ConfigKey = BizConfigConst.BIZ_SMS_STATES_DAY,
                ConfigValue = push.DaySum.ToString()
            });
        }
        return true;
    }
    /// <summary>
    /// 获取预警推送内容
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetWarnPushSetting()
    {
        var configPush = new ConfigPush
        {
            PushState = (await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE, BizConfigConst.BIZ_SMS_STATES))
                .ConfigValue.ToBoolean(),
            DaySum = (await _configService.GetByConfigKey(CateGoryConst.CONFIG_BIZ_DEFINE, BizConfigConst.BIZ_SMS_STATES_DAY))
                .ConfigValue.ToInt()
        };
        return configPush;
    }
    /// <summary> 
    /// 预警统计-饼图 Alarm 今日告警情况，Hand今日处理情况
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetWarnStatistics()
    {
        //今日告警情况饼图
        //今日处理情况

        var startTime = DateTime.Now.Date;
        var entTime = DateTime.Now;

        var list = 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,
            Count = list.Count(xx => xx.AlarmType == x.Name)
        }).Where(x => x.Count > 0).ToList();
        var numbers = new Dictionary<int, string> { { 0, "未处理" }, { 1, "已处理" } };
        var handStatistics = numbers.Select(x => new
        {
            Name = x.Value,
            Count = list.Count(xx => xx.WarnHand == x.Key)
        }).ToList();
        return new { Alarm = alarmStatistics, Hand = handStatistics };
    }
    /// <summary>
    /// 获取七天统计柱状图
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetWeekWarnStatistics()
    {
        var result = new StatistionModel
        {
           DataX = new List<string>(),
           DataY = new List<SeriesData>()
        };
        var startTime = DateTime.Now.AddDays(-7).Date;
        var entTime = DateTime.Now;

        var list = await _warnInfoService.GetListNoPage(new WarnInfoSearch
        {
            StartTick = startTime,
            EndTick = entTime

        });
        //var warnType = typeof(AlarmType).EnumToEnumModel();
        var climb_over = new List<int>();
        var crowd = new List<int>();
        var fire_smoke = new List<int>();
        var visual_fence = new List<int>();
        var wander = new List<int>();
        for (DateTime i = startTime; i <= entTime;)
        {
            var itemList = list.Where(x =>
                    x.Tick.Year == i.Year && x.Tick.Month == i.Month && x.Tick.Day == i.Day)
                .ToList();

            //var alarmStatistics = warnType.Where(x=>x.Value<=4).Select(x => new StatistionFunModel
            //{
            //    Name = x.Description,
            //    Code=x.Name,
            //    Count = itemList.Count(xx => xx.AlarmType == x.Name),
            //    Date = i.ToString("MM-dd")
            //}).ToList();
            result.DataX.Add(i.ToString("MM-dd"));
            climb_over.Add(itemList.Count(x=>x.AlarmType== "climb_over"));
            crowd.Add(itemList.Count(x=>x.AlarmType== "crowd"));
            fire_smoke.Add(itemList.Count(x=>x.AlarmType== "fire_smoke"));
            visual_fence.Add(itemList.Count(x=>x.AlarmType== "visual_fence"));
            wander.Add(itemList.Count(x=>x.AlarmType== "wander"));
            //result.Add(new StatistionModel
            //{
            //    Date = i.ToString("MM-dd"),
            //    visual_fence = 
            //    //FunList = alarmStatistics
            //});
            i = i.AddDays(1);
        }
        result.DataY.Add(new SeriesData
        {
            Name = AlarmType.climb_over.GetDescription(),
            Data = climb_over
        });
        result.DataY.Add(new SeriesData
        {
            Name = AlarmType.crowd.GetDescription(),
            Data = crowd
        });
        result.DataY.Add(new SeriesData
        {
            Name = AlarmType.fire_smoke.GetDescription(),
            Data = fire_smoke
        });
        result.DataY.Add(new SeriesData
        {
            Name = AlarmType.visual_fence.GetDescription(),
            Data = visual_fence
        });
        result.DataY.Add(new SeriesData
        {
            Name = AlarmType.wander.GetDescription(),
            Data = wander
        });
        return result ;
    }
    /// <summary>
    /// 获取告警枚举列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<WarnType>> GetAlarmType()
    {
        return await _warnInfoService.GetWarnType();
    }
    /// <summary>
    /// 根据监控id获取大屏告警数据
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<dynamic> GetLargeScreenData(string cameraId)
    {
        var startTime = DateTime.Now.AddDays(-7).Date;
        var entTime = DateTime.Now;
        var list=await _warnInfoService.GetListNoPage(new WarnInfoSearch
        {
            StartTick = startTime,
            EndTick = entTime,
            PageNum = 1,
            PageSize = 20,
            CameraId = cameraId
        });
        var warnType = typeof(AlarmType).EnumToEnumModel();
        var alarmStatistics = warnType.Select(x => new StatistionFunModel
        {
            Name = x.Description,
            Code = x.Name,
            Count = list.Count(xx => xx.AlarmType == x.Name),
        }).Where(x=>x.Count>0).ToList();
        return new { item = list, statistion = alarmStatistics };
    }
    /// <summary>
    /// 处理预警
    /// </summary>
    /// <returns></returns>
    public async Task<bool> HandWarn(HandWarnInput input)
    {
        return await _warnInfoService.HandWarn(input);
    }
}