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.DecimalUtil;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.mapper.cable.BusiCableCirculationMapper;
import com.huatek.busi.mapper.report.BusiYspReportMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.service.Other.BusiOfflineOtherRepairService;
import com.huatek.busi.service.impl.report.helper.ReportImpl;
import com.huatek.busi.service.report.BusiCommonReportService;
import com.huatek.busi.util.CalcUtil;
import com.huatek.busi.vo.monitor.BusiMonitorCableDataVo;
import com.huatek.busi.vo.report.BusiYspMonitorDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Bobi_huo
 * @date 2020-12-18 13:48
 */
@ReportImpl(value = "busiCableCirculationReportService", exportTypes = {ReportType.DLHL_MONTHLY_REPORT})
public class BusiCableCirculationReportServiceImpl implements BusiCommonReportService {

    @Autowired
    private BusiSubTreeService busiSubTreeService;

    @Autowired
    private BusiEqmWarningService busiEqmWarningService;

    @Autowired
    private BusiOfflineOtherRepairService busiOfflineOtherRepairService;

    @Autowired
    private FailureRateService failureRateService;

    @Autowired
    private BusiCableCirculationMapper busiCableCirculationMapper;

    @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);
        result.put("fileName", "电缆环流检测装置管理考核");
        result.put("data", data);
        String sensorCode = sensors.get(0);
        EquipmentInfoDto equipmentInfo = busiSubTreeService.findEquipmentInfo(sensorCode, SiteConstants.SiteTreeEnum.OTHER.getValue());

        // 报告编号
        data.put("reportCode", "");
        // 报告日期
        data.put("reportDate", LocalDate.now());
        // 安装位置
        data.put("positionDes", "");
        // 投运日期
        data.put("useDate", "");
        // 检修周期（月）
        data.put("rpCycle", "6");
        // 生产厂家
        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());

            Map<String, LocalDateTime> mapDate = CalcUtil.getcurrentMonthDateMap();
            Map<String, Object> param = Maps.newHashMap();
            param.put("mainTreeId", equipmentInfo.getMainTreeId());
            param.put("startTime", mapDate.get("startTime"));
            param.put("endTime", mapDate.get("endTime"));
            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 = busiOfflineOtherRepairService.getRepairCount(param);

            // 数据缺失率
            String lossRate = failureRateService.getSensorLossRate(equipmentInfo.getSensorCode(), mapDate.get("startTime"),
                    mapDate.get("endTime"));
            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));
            }
            List<BusiMonitorCableDataVo> caclist = this.getCacDatas(equipmentInfo.getSensorCode(), mapDate.get("startTime"), mapDate.get("endTime"));
            // 传感器
            data.put("sensorName", sensorCode);
            // 数据缺失率
            data.put("lossRate", lossRate);
            // 误报率
            data.put("falseRate", falseAlarmRate);
            // 误报次数
            data.put("warningCount", totalCount);
            // 检修次数
            data.put("repairCount", repairCount);
            // 数据列表
            data.put("cacList", caclist);
        }
        return result;
    }

    private List<BusiMonitorCableDataVo> getCacDatas(String sensorCode, LocalDateTime startTime, LocalDateTime endTime) {
        List<BusiMonitorCableDataVo> resultlist = new ArrayList<>();
//		Calendar c = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
//			Date dtime = format.parse(exportTime);
//			c.setTime(dtime);
//			int month = c.get(Calendar.MONTH) + 1;
//			String start = getFirstDayOfMonth(month);
//			String end = getLastDayOfMonth(month);
            Date startDate = format.parse(String.valueOf(startTime));
            Date endDate = format.parse(String.valueOf(endTime));
            List<BusiMonitorCableDataVo> list = busiCableCirculationMapper.getDaliyReportData(sensorCode, startDate, endDate);
            if (CollectionUtil.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setIndex((i + 1) + "");
                    if(list.get(i) != null)
                    {
                        resultlist.add(list.get(i));
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultlist;
    }

}
