using AutoMapper;
using Entity.Api.Req;
using Entity.DbModel.Station;
using Entity.Dto;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Entity;
using HybirdFrameworkCore.Utils;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using Repository.Station;
using SqlSugar;

namespace Service.Station;

[Scope]
public class EquipAlarmRecordService : BaseServices<EquipAlarmRecord>
{
    public EquipAlarmProcessRecordRepository ProcessRecordRepository { get; set; }

    public EquipAlarmRecordService(EquipAlarmRecordRepository dal)
    {
        BaseDal = dal;
    }

    /// <summary>
    /// 查询未处理报警列表
    /// </summary>
    /// <param name="typeCode">设备类型:-1-查询全部;0-充电机;1-电表;2-水冷机;3-plc<</param>
    /// <param name="equipCode">设备编码</param>
    /// <returns></returns>
    public Result<PageResult<EquipAlarmRecord>> QueryEquipAlarmPage(QueryAlarmReq req)
    {
        int totalCount = 0;
        int reqTypeCode = req.TypeCode;
        var equipCode = req.EquipCode;
        var errorLevel = req.ErrorLevel;
        List<EquipAlarmRecord> list = BaseDal.Queryable().WhereIF(reqTypeCode != -1, it => it.EquipTypeCode == reqTypeCode)
            .WhereIF(ObjUtils.IsNotNullOrWhiteSpace(equipCode), it => it.EquipCode == equipCode)
            .WhereIF(ObjUtils.IsNotNullOrWhiteSpace(errorLevel), it => it.ErrorLevel == errorLevel)
            .WhereIF(req.StartTime.HasValue && req.ProcessTime.HasValue,
                it => it.StartTime >= req.StartTime && it.StartTime <= req.ProcessTime)
            .OrderBy(it => it.CreatedTime, OrderByType.Desc)
            .ToPageList(req.PageNum, req.PageSize, ref  totalCount);

        PageResult<EquipAlarmRecord> result = new PageResult<EquipAlarmRecord>()
        {
            PageNum = req.PageNum,
            PageSize = req.PageSize,
            ToTal = totalCount,
            Rows = list
        };
       return Result<PageResult<EquipAlarmRecord>>.Success(result);
    }

    /// <summary>
    /// 导出未处理报警日志 🔖
    /// </summary>
    /// <returns></returns>
    public async Task<IActionResult> ExportEquipAlarmRecord()
    {
        List<EquipAlarmRecord> equipAlarmRecords = await BaseDal.QueryAsync();

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<EquipAlarmRecordDto, EquipAlarmRecord>().ReverseMap();
        });

        IMapper mapper = config.CreateMapper();

        List<EquipAlarmRecordDto> logExList = mapper.Map<List<EquipAlarmRecordDto>>(equipAlarmRecords);

        IExcelExporter excelExporter = new ExcelExporter();

        var res = await excelExporter.ExportAsByteArray(logExList);

        return new FileStreamResult(new MemoryStream(res), "application/octet-stream")
            { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "未处理报警日志.xlsx" };
    }
    
    /// <summary>
    /// 查询已处理报警列表
    /// </summary>
    /// <param name="typeCode">设备类型:-1-查询全部;0-充电机;1-电表;2-水冷机;3-plc</param>
    /// <param name="equipCode">设备编码</param>
    /// <returns></returns>
    public Result<PageResult<EquipAlarmProcessRecord>> QueryEquipAlarmProcessPage(QueryAlarmReq req)
    {
        int totalCount = 0;
        int reqTypeCode = req.TypeCode;
        var equipCode = req.EquipCode;
        var errorLevel = req.ErrorLevel;
        List<EquipAlarmProcessRecord> list = ProcessRecordRepository.Queryable()
                .WhereIF(reqTypeCode != -1, it => it.EquipTypeCode == reqTypeCode)
            .WhereIF(ObjUtils.IsNotNullOrWhiteSpace(equipCode), it => it.EquipCode == equipCode)
            .WhereIF(ObjUtils.IsNotNullOrWhiteSpace(errorLevel), it => it.ErrorLevel == errorLevel)
            .WhereIF(req.StartTime.HasValue && req.ProcessTime.HasValue,
                it => it.StartTime >= req.StartTime && it.ProcessTime <= req.ProcessTime)            .OrderBy(it => it.CreatedTime, OrderByType.Desc)
            .ToPageList(req.PageNum, req.PageSize, ref  totalCount);

        PageResult<EquipAlarmProcessRecord> result = new PageResult<EquipAlarmProcessRecord>()
        {
            PageNum = req.PageNum,
            PageSize = req.PageSize,
            ToTal = totalCount,
            Rows = list
        };


       return Result<PageResult<EquipAlarmProcessRecord>>.Success(result);
    }
    
    /// <summary>
    /// 导出已处理报警日志 🔖
    /// </summary>
    /// <returns></returns>
    public async Task<IActionResult> ExportEquipAlarmProcessRecord()
    {
        List<EquipAlarmProcessRecord> equipAlarmProcessRecords = await ProcessRecordRepository.QueryAsync();

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<EquipAlarmProcessRecordDto, EquipAlarmProcessRecord>().ReverseMap();
        });

        IMapper mapper = config.CreateMapper();

        List<EquipAlarmProcessRecordDto> logExList = mapper.Map<List<EquipAlarmProcessRecordDto>>(equipAlarmProcessRecords);

        IExcelExporter excelExporter = new ExcelExporter();

        var res = await excelExporter.ExportAsByteArray(logExList);

        return new FileStreamResult(new MemoryStream(res), "application/octet-stream")
            { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "已处理报警日志.xlsx" };
    }
}