package com.huatek.busi.service.impl.report;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.ReportType;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.mapper.BusiGeneratorAmplMapper;
import com.huatek.busi.mapper.BusiGeneratorPdMapper;
import com.huatek.busi.mapper.BusiGeneratorPressureMapper;
import com.huatek.busi.service.BusiEqmWarningService;
import com.huatek.busi.service.BusiSubTreeService;
import com.huatek.busi.service.FailureRateService;
import com.huatek.busi.service.generatro.BusiOfflineGeneratorRepairService;
import com.huatek.busi.service.impl.report.helper.ReportImpl;
import com.huatek.busi.service.report.BusiCommonReportService;
import com.huatek.busi.vo.BusiGeneratorAmplVo2;
import com.huatek.busi.vo.BusiGeneratorPdVo;
import com.huatek.busi.vo.BusiGeneratorPressureVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

;

/**
 * @description BusiGeneratorMonthlyReportServiceImpl
 *
 * @author Kavon
 * @date 2023/12/7 13:25
 */
@ReportImpl(value = "BusiGeneratorMonthlyReportService", exportTypes = {
        ReportType.FDJ_ZD_MONTHLY_REPORT, 
        ReportType.FDJ_YL_MONTHLY_REPORT,
        ReportType.FDJ_JF_MONTHLY_REPORT
})
public class BusiGeneratorMonthlyReportServiceImpl implements BusiCommonReportService {

    @Autowired
    private BusiSubTreeService busiSubTreeService;

    @Autowired
    private BusiEqmWarningService busiEqmWarningService;

    @Autowired
    private BusiOfflineGeneratorRepairService busiOfflineGeneratorRepairService;

    @Autowired
    private FailureRateService failureRateService;

    @Autowired
    private BusiGeneratorAmplMapper busiGeneratorAmplMapper;

    @Autowired
    private BusiGeneratorPressureMapper busiGeneratorPressureMapper;

    @Autowired
    private BusiGeneratorPdMapper busiGeneratorPdMapper;




    @Override
    public Map<String, Object> buildExportData(String exportType, List<String> sensors, String exportTime, String startTime, String endTime) {
        Map<String, Object> result = Maps.newLinkedHashMapWithExpectedSize(2);
        Map<String, Object> data = Maps.newLinkedHashMapWithExpectedSize(35);
        if(ReportType.FDJ_ZD_MONTHLY_REPORT.equals(exportType)){
            result.put("fileName", "发电机振动监测装置（月）报告");
        }else if (ReportType.FDJ_YL_MONTHLY_REPORT.equals(exportType)){
            result.put("fileName", "发电机压力监测装置（月）报告");
        }else if (ReportType.FDJ_JF_MONTHLY_REPORT.equals(exportType)){
            result.put("fileName", "发电机局放监测装置（月）报告");
        }
        
        result.put("data", data);
        String sensorCode = sensors.get(0);
        EquipmentInfoDto equipmentInfo = busiSubTreeService.findEquipmentInfo(sensorCode, SiteConstants.SiteTreeEnum.GEN_EQM.getValue());

        // 报告编号
        data.put("reportCode", "");
        // 报告日期
        data.put("reportDate", LocalDate.now());
        // 安装位置
        data.put("positionDes", "");
        // 投运日期
        data.put("useDate", "");
        // 检修周期（月）
        data.put("rpCycle", "");
        // 生产厂家
        data.put("manufacturer", "");
        // 报告评价
        data.put("reportDes", "");
        // 处理意见
        data.put("dealOpt", "");

        // 报告评价说明
        data.put("rpEvaDes", "");
        // 报告人
        data.put("reportPeople", "");
        // 签字
        data.put("sign", "");
        if (equipmentInfo != null) {
            // 投运日期
            data.put("useDate", equipmentInfo.getSensorUseDate() == null ? "" : equipmentInfo.getSensorUseDate());
            // 生产厂家
            data.put("manufacturer", equipmentInfo.getSensorManufactor() == null ? " " : equipmentInfo.getSensorManufactor());
            // 安装位置
            data.put("positionDes", equipmentInfo.getSensorPositionDes() == null ? " " : equipmentInfo.getSensorPositionDes());

            LocalDateTime startDateTime = DateUtil.atStartOfDay(LocalDate.now());
            LocalDateTime endDateTime = DateUtil.atEndOfDay(LocalDate.now());
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                startDateTime = DateUtil.atStartOfDay(LocalDate.parse(startTime, dateTimeFormatter));
                endDateTime = DateUtil.atEndOfDay(LocalDate.parse(endTime, dateTimeFormatter));
            }

            Map<String, Object> param = Maps.newHashMap();
            param.put("mainTreeId", equipmentInfo.getMainTreeId());
            param.put("startTime", startDateTime);
            param.put("endTime", endDateTime);
            param.put("sensorCode", sensorCode);
            // 告警次数
            BigDecimal totalCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(param));
            // 误报次数
            param.put("warningType", BusiConstant.WarningType.MISREPORT);
            BigDecimal wbCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(param));
            // 检修记录
            Integer repairCount = busiOfflineGeneratorRepairService.getRepairCount(param);

            // 数据缺失率
            String lossRate = failureRateService.getSensorLossRate(equipmentInfo.getSensorCode(), startDateTime,
                    endDateTime);
            lossRate = lossRate == null ? "" : lossRate;
            // 计算数据缺失率
            String falseAlarmRate = "0";
            if (BigDecimal.ZERO.compareTo(totalCount) != 0 && BigDecimal.ZERO.compareTo(wbCount) != 0) {
                // 转换成百分比
                DecimalFormat df = new DecimalFormat("0.00");// 设置保留位数
                falseAlarmRate = df.format(DecimalUtil.divide(wbCount.multiply(BigDecimal.valueOf(100)), totalCount, 2));
            }

            // 传感器
            data.put("sensorName", sensorCode);
            // 数据缺失率
            data.put("lossRate", lossRate);
            // 误报率
            data.put("falseRate", falseAlarmRate);
            // 误报次数
            data.put("warningCount", totalCount);
            // 检修次数
            data.put("repairCount", repairCount);
            // 数据列表
            if(ReportType.FDJ_ZD_MONTHLY_REPORT.equals(exportType)){
                List<BusiGeneratorAmplVo2> realTimeData = this.getZDRealTimeData(equipmentInfo.getSensorCode(), startDateTime, endDateTime);
                data.put("realTimeDataList", realTimeData);
            }else if (ReportType.FDJ_YL_MONTHLY_REPORT.equals(exportType)){
                List<BusiGeneratorPressureVo> realTimeData = this.getYLRealTimeData(equipmentInfo.getSensorCode(), startDateTime, endDateTime);
                data.put("realTimeDataList", realTimeData);
            }else if (ReportType.FDJ_JF_MONTHLY_REPORT.equals(exportType)){
                List<BusiGeneratorPdVo> realTimeData = this.getPDRealTimeData(equipmentInfo.getSensorCode(), startDateTime, endDateTime);
                data.put("realTimeDataList", realTimeData);
            }
   
        }
        return result;
    }

    private List<BusiGeneratorPdVo> getPDRealTimeData(String sensorCode, LocalDateTime startTime, LocalDateTime endTime) {
        List<BusiGeneratorPdVo> resultList = new ArrayList<>();
        List<BusiGeneratorPdVo> reportDataList = busiGeneratorPdMapper.findReportDataList(sensorCode,startTime, endTime);
        BusiGeneratorPdVo item;
        if (CollectionUtil.isNotEmpty(reportDataList)) {
            for (int i = 0; i < reportDataList.size(); i++) {
                item = reportDataList.get(i);
                item.setSeqNum(i + 1 + "");
                item.setTimestamp(item.getDTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                resultList.add(item);
            }
        }
        return resultList;
    }

    private List<BusiGeneratorPressureVo> getYLRealTimeData(String sensorCode, LocalDateTime startTime, LocalDateTime endTime) {
        List<BusiGeneratorPressureVo> resultList = new ArrayList<>();
        List<BusiGeneratorPressureVo> reportDataList = busiGeneratorPressureMapper.queryHistory(sensorCode,startTime, endTime);
        BusiGeneratorPressureVo item;
        if (CollectionUtil.isNotEmpty(reportDataList)) {
            for (int i = 0; i < reportDataList.size(); i++) {
                item = reportDataList.get(i);
                item.setSeqNum(i + 1 + "");
                item.setTimestamp(item.getDTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                resultList.add(item);
            }
        }
        return resultList;
    }

    private List<BusiGeneratorAmplVo2> getZDRealTimeData(String sensorCode, LocalDateTime startTime, LocalDateTime endTime) {
        List<BusiGeneratorAmplVo2> resultList = new ArrayList<>();
        List<BusiGeneratorAmplVo2> reportDataList = busiGeneratorAmplMapper.queryHistory(sensorCode, startTime, endTime);
        BusiGeneratorAmplVo2 item;
        if (CollectionUtil.isNotEmpty(reportDataList)) {
            for (int i = 0; i < reportDataList.size(); i++) {
                item = reportDataList.get(i);
                item.setSeqNum(i + 1 + "");
                item.setTimestamp(item.getDTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                resultList.add(item);
            }
        }
        return resultList;
    }

}
