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

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant.WarningType;
import com.huatek.busi.common.ReportType;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.entity.IecBydworkParam;
import com.huatek.busi.mapper.CapacitanceEquipmentImMapper;
import com.huatek.busi.mapper.IecBydworkParamMapper;
import com.huatek.busi.mapper.LightningrodImMapper;
import com.huatek.busi.service.BusiEqmWarningService;
import com.huatek.busi.service.BusiEquipmentRelationshipService;
import com.huatek.busi.service.BusiStabilityService;
import com.huatek.busi.service.BusiSubTreeService;
import com.huatek.busi.service.FailureRateService;
import com.huatek.busi.service.impl.report.helper.ReportImpl;
import com.huatek.busi.service.report.BusiCommonReportService;
import com.huatek.busi.vo.CapacitanceEquipmentImVo;
import com.huatek.busi.vo.LightningrodImVo;
import com.huatek.busi.vo.TransformerTmpVo;

@ReportImpl(value = "busiArresterReportService",
    exportTypes = {ReportType.BLQ_MONTHLY_REPORT, ReportType.RX_MONTHLY_REPORT})
public class BusiArresterReportServiceImpl implements BusiCommonReportService {
    @Autowired
    private BusiSubTreeService busiSubTreeService;
    @Autowired
    private BusiEqmWarningService busiEqmWarningService;
    @Autowired
    private FailureRateService failureRateService;
    @Autowired
    private BusiStabilityService busiStabilityService;
    @Autowired
    private LightningrodImMapper lightningrodImMapper;
    @Autowired
    private CapacitanceEquipmentImMapper capacitanceEquipmentImMapper;
    @Autowired
	private IecBydworkParamMapper iecBydworkParamMapper;
	@Reference(check = false)
	private BusiEquipmentRelationshipService busiEquipmentRelationshipService;
    @Override
    public Map<String, Object> buildExportData(String exportType, List<String> sensors, String exportTime,String startTime, String endTime) {
        if (exportType.equals(ReportType.BLQ_MONTHLY_REPORT)) {
            return this.buildBLQExportData(sensors, exportTime,startTime,endTime);
        } else if (exportType.equals(ReportType.RX_MONTHLY_REPORT)) {
            return this.buildRXExportData(sensors, exportTime,startTime,endTime);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
	private Map<String, Object> buildBLQExportData(List<String> sernsors, String exportTime,String startTime, String endTime) {
        EquipmentInfoDto equipmentInfo = new EquipmentInfoDto();
        String sensorCode = sernsors.get(0);
        equipmentInfo = busiSubTreeService.findEquipmentInfo(sensorCode, SiteTreeEnum.BLQ.getValue());

        Map<String, Object> resultData = Maps.newLinkedHashMapWithExpectedSize(35);
        Map<String, Object> result = Maps.newHashMap();
        if (equipmentInfo != null) {
            String dataMissingRate = failureRateService.getSensorLossRate(sensorCode, DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay()); //缺失率
            
            LocalDateTime endExportTime = DateUtil.getMonthLastDay();
            LocalDateTime startExportTime = DateUtil.getMonthStartDay();
            Map<String, Object> params = Maps.newHashMap();
            params.put("mainTreeId", equipmentInfo.getMainTreeId());
            params.put("startTime", startExportTime);
            params.put("endTime", endExportTime);
            params.put("sensorCode", sensorCode);
            
            BigDecimal totalCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(params));
            params.put("warningType", WarningType.FAULT);
            BigDecimal gzCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(params));

            params.put("warningType", WarningType.MISREPORT);
            BigDecimal wbCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(params));

            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));
            }

            resultData.put("reportCode", "");
            resultData.put("reportDate", LocalDate.now());
            resultData.put("detectionDate", "");
            resultData.put("installLocation",
                equipmentInfo.getSensorPositionDes() == null ? "" : equipmentInfo.getSensorPositionDes());
            resultData.put("operationDate",
                equipmentInfo.getSubEquipmentUseDate() == null ? "" : equipmentInfo.getSubEquipmentUseDate());
            resultData.put("remark", "");

            Map<String, Object> map = busiStabilityService.findStabilityMapBySensorCode(sensorCode);
            if (map != null) {
                resultData.put("val1",
                    map.get("1") == null || "".equals(map.get("1")) ? ""
                        : "全电流(mA):" + ((Map<String, String>)map.get("1")).get("totalCurrent") + ", 阻性电流 (mA):"
                            + ((Map<String, String>)map.get("1")).get("resistiveCurrent"));
                resultData.put("val2",
                    map.get("2") == null || "".equals(map.get("2")) ? ""
                        : "全电流(mA):" + ((Map<String, String>)map.get("2")).get("totalCurrent") + ", 阻性电流 (mA):"
                            + ((Map<String, String>)map.get("2")).get("resistiveCurrent"));
                resultData.put("val3",
                    map.get("3") == null || "".equals(map.get("3")) ? ""
                        : "全电流(mA):" + ((Map<String, String>)map.get("3")).get("totalCurrent") + ", 阻性电流 (mA):"
                            + ((Map<String, String>)map.get("3")).get("resistiveCurrent"));
            } else {
                resultData.put("val1", "");
                resultData.put("val2", "");
                resultData.put("val3", "");
            }
            resultData.put("dataMissingRate", dataMissingRate == null ? "" : dataMissingRate);

            resultData.put("lastCheckTime", "");
            resultData.put("manufacturer",
                equipmentInfo.getSubEquipmentManufactor() == null ? "" : equipmentInfo.getSubEquipmentManufactor());
            resultData.put("checkFrequency", "");
            resultData.put("warningNumber", totalCount);
            resultData.put("falseWarningNumber", wbCount);
            resultData.put("lastOverhaulDate", "");
            resultData.put("reportEvaluation", "");
            resultData.put("processOpinions", "");

            List<Map<String, Object>> pdList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> item = Maps.newLinkedHashMapWithExpectedSize(7);
            item.put("falseAlarmRate", falseAlarmRate);
            item.put("totalCount", totalCount);
            item.put("gzCount", gzCount);
            pdList1.add(item);
            resultData.put("blqList", pdList1);
            resultData.put("reporter", "");
            resultData.put("signatory", "");
            resultData.put("reportDescription", "");
            List<Map<String, Object>> monthList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> mapParams = Maps.newLinkedHashMapWithExpectedSize(3);
            if (StringUtils.isNotEmpty(startTime)) {
            	mapParams.put("timeStamp", startTime);
            } else {
//            	mapParams.put("timeStamp", DateUtil.format(DateUtil.atStartOfDay(LocalDate.now())));
            }
            if (StringUtils.isNotEmpty(endTime)) {
            	mapParams.put("timeStampEnd", endTime);
            } else {
//            	mapParams.put("timeStampEnd", DateUtil.format(DateUtil.atEndOfDay(LocalDate.now())));
            }
            mapParams.put("sensorCode", sensorCode);
            List<LightningrodImVo> voList = lightningrodImMapper.exportCacMonitorData(mapParams);
            if (!voList.isEmpty()) {
                for (int i = 0; i < voList.size(); i++) {
                	LightningrodImVo lightningrodImVo = voList.get(i);
                    Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
                    if (lightningrodImVo != null) {
                        monthitem.put("serialNumber", i + 1); //序号
                        monthitem.put("sensorPosition", StringUtils.isNotEmpty(lightningrodImVo.getPhase()) ? lightningrodImVo.getPhase() : ""); //安装相位
                        monthitem.put("systemVoltage", StringUtils.isNotEmpty(lightningrodImVo.getSystemVoltage()) ? lightningrodImVo.getSystemVoltage() : ""); //系统电压 
                        monthitem.put("totalCurrent",  StringUtils.isNotEmpty(lightningrodImVo.getTotalCurrent()) ? lightningrodImVo.getTotalCurrent() : ""); //全电流 
                        monthitem.put("resistiveCurrent", StringUtils.isNotEmpty(lightningrodImVo.getResistiveCurrent()) ? lightningrodImVo.getResistiveCurrent() : ""); //阻性电流 (mA)
                        monthitem.put("capacitanceCurrent",StringUtils.isNotEmpty(lightningrodImVo.getCapacitanceCurrent()) ? lightningrodImVo.getCapacitanceCurrent() : ""); //容性电流 (mA) 
                        monthitem.put("timeStamp", DateUtil.format(lightningrodImVo.getTimeStamp()));
                        //获取关联变压器状态:
                        List<String> transformerIds = Lists.newArrayList();
                        Integer iecType = null;
                        List<TransformerTmpVo> transformerList = busiEquipmentRelationshipService.getCurrentTransformerInfo(lightningrodImVo.getMainTreeId());
                        if (CollectionUtils.isEmpty(transformerList)) {
                    		   monthitem.put("runStatus","");
                        }
                        else {
                        	 for(TransformerTmpVo transformer : transformerList) {
                             	IecBydworkParam iecBydworkParam = iecBydworkParamMapper.getIecType2(transformer.getTransformerId());
                                if(iecBydworkParam == null || iecBydworkParam.getStype() == null) {
                                    continue;
                                }
                                if(iecType == null) {
                                    iecType = iecBydworkParam.getStype();
                                }else if(iecType.intValue() > iecBydworkParam.getStype().intValue()){
                                    iecType = iecBydworkParam.getStype();
                                }
                             }
                        }
                        if(iecType==1)
                        {
                        	 monthitem.put("runStatus","发电");
                        }else if(iecType==2)
                        {
                        	 monthitem.put("runStatus","抽水");
                        }else if(iecType==3)
                        {
                        	 monthitem.put("runStatus","空闲");
                        }
                    }
                    monthList1.add(monthitem);
                }
            } else {
                Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
                monthitem.put("serialNumber", "");
                monthitem.put("sensorPosition", "");
                monthitem.put("systemVoltage", "");
                monthitem.put("totalCurrent", "");
                monthitem.put("resistiveCurrent", "");
                monthitem.put("capacitanceCurrent", "");
                monthitem.put("timeStamp", "");
                monthList1.add(monthitem);
            }
            resultData.put("blqMonthList", monthList1);
        } else {
            resultData.put("reportCode", "");
            resultData.put("reportDate", exportTime);
            resultData.put("detectionDate", "");
            resultData.put("installLocation", "");
            resultData.put("operationDate", "");
            resultData.put("remark", "");
            resultData.put("val1", "");
            resultData.put("val2", "");
            resultData.put("val3", "");
            resultData.put("dataMissingRate", "");
            resultData.put("lastCheckTime", "");
            resultData.put("manufacturer", "");
            resultData.put("checkFrequency", "");
            resultData.put("warningNumber", "");
            resultData.put("falseWarningNumber", "");
            resultData.put("lastOverhaulDate", "");
            resultData.put("reportEvaluation", "");
            resultData.put("processOpinions", "");
            List<Map<String, Object>> pdList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> item = Maps.newLinkedHashMapWithExpectedSize(7);
            item.put("falseAlarmRate", "");
            item.put("totalCount", "");
            item.put("gzCount", "");
            pdList1.add(item);
            resultData.put("blqList", pdList1);
            resultData.put("reporter", "");
            resultData.put("signatory", "");
            resultData.put("reportDescription", "");
            List<Map<String, Object>> monthList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
            monthitem.put("serialNumber", "");
            monthitem.put("sensorPosition", "");
            monthitem.put("systemVoltage", "");
            monthitem.put("totalCurrent", "");
            monthitem.put("resistiveCurrent", "");
            monthitem.put("capacitanceCurrent", "");
            monthitem.put("timeStamp", "");
            monthList1.add(monthitem);
            resultData.put("blqMonthList", monthList1);
        }
        result.put("fileName", "避雷器检测装置管理考核");
        result.put("data", resultData);
        return result;
    }

    @SuppressWarnings("unchecked")
	private Map<String, Object> buildRXExportData(List<String> sernsors, String exportTime, String startTime, String endTime) {
        EquipmentInfoDto equipmentInfo = new EquipmentInfoDto();
        String sensorCode = sernsors.get(0);
        equipmentInfo = busiSubTreeService.findEquipmentInfo(sensorCode, SiteTreeEnum.BLQ.getValue());

        Map<String, Object> resultData = Maps.newLinkedHashMapWithExpectedSize(35);
        Map<String, Object> result = Maps.newHashMap();
        if (equipmentInfo != null) {
            String dataMissingRate =
                failureRateService.getSensorLossRate(sensorCode, DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay());
            Map<String, Object> param = Maps.newHashMap();
            param.put("mainTreeId", equipmentInfo.getMainTreeId());
            param.put("sensorCode", sensorCode);
            param.put("startTime", startTime);
            param.put("endTime", endTime);

            BigDecimal totalCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(param));
            param.put("warningType", WarningType.FAULT);
            BigDecimal gzCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(param));

            param.put("warningType", WarningType.MISREPORT);
            BigDecimal wbCount = DecimalUtil.getVal(busiEqmWarningService.getBusiEqmWarningCount(param));

            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));
            }
            resultData.put("reportCode", "");
            resultData.put("reportDate", exportTime);
            resultData.put("detectionDate", "");
            resultData.put("installLocation",
                equipmentInfo.getSensorPositionDes() == null ? "" : equipmentInfo.getSensorPositionDes());
            resultData.put("operationDate",
                equipmentInfo.getSubEquipmentUseDate() == null ? "" : equipmentInfo.getSubEquipmentUseDate());
            resultData.put("remark", "");

            Map<String, Object> map = busiStabilityService.findStabilityMapBySensorCode(sensorCode);
            if (map != null) {
                resultData.put("val1",
                    map.get("1") == null || "".equals(map.get("1")) ? ""
                        : "电容量(pF):" + ((Map<String, String>)map.get("1")).get("capacitance") + ", 介质损耗因数:"
                            + ((Map<String, String>)map.get("1")).get("lossFactor"));
                resultData.put("val2",
                    map.get("2") == null || "".equals(map.get("2")) ? ""
                        : "电容量(pF):" + ((Map<String, String>)map.get("2")).get("capacitance") + ", 介质损耗因数:"
                            + ((Map<String, String>)map.get("2")).get("lossFactor"));
                resultData.put("val3",
                    map.get("3") == null || "".equals(map.get("3")) ? ""
                        : "电容量(pF):" + ((Map<String, String>)map.get("3")).get("capacitance") + ", 介质损耗因数:"
                            + ((Map<String, String>)map.get("3")).get("lossFactor"));

            } else {
                resultData.put("val1", "");
                resultData.put("val2", "");
                resultData.put("val3", "");
            }

            resultData.put("dataMissingRate", dataMissingRate == null ? "" : dataMissingRate);

            resultData.put("lastCheckTime", "");
            resultData.put("manufacturer",
                equipmentInfo.getSubEquipmentManufactor() == null ? "" : equipmentInfo.getSubEquipmentManufactor());
            resultData.put("checkFrequency", "");
            resultData.put("warningNumber", totalCount);
            resultData.put("falseWarningNumber", wbCount);
            resultData.put("lastOverhaulDate", "");
            resultData.put("reportEvaluation", "");
            resultData.put("processOpinions", "");

            List<Map<String, Object>> pdList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> item = Maps.newLinkedHashMapWithExpectedSize(7);

            item.put("falseAlarmRate", falseAlarmRate);
            item.put("totalCount", totalCount);
            item.put("gzCount", gzCount);
            pdList1.add(item);
            resultData.put("rxList", pdList1);

            resultData.put("reporter", "");
            resultData.put("signatory", "");
            resultData.put("reportDescription", "");

            List<Map<String, Object>> monthList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> mapParams = Maps.newLinkedHashMapWithExpectedSize(3);
            if (StringUtils.isNotEmpty(startTime)) {
            	mapParams.put("timeStamp", startTime);
            } else {
            	mapParams.put("timeStamp", DateUtil.format(DateUtil.atStartOfDay(LocalDate.now())));
            }
            if (StringUtils.isNotEmpty(endTime)) {
            	mapParams.put("timeStampEnd", endTime);
            } else {
            	mapParams.put("timeStampEnd", DateUtil.format(DateUtil.atEndOfDay(LocalDate.now())));
            }
            mapParams.put("sensorCode", sensorCode);
            List<CapacitanceEquipmentImVo> voList = capacitanceEquipmentImMapper.exportArresterCacMonitorData(mapParams);
            if (!voList.isEmpty()) {
                for (int i = 0; i < voList.size(); i++) {
                    Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
                    CapacitanceEquipmentImVo capacitanceEquipmentImVo = voList.get(i);
                    if (capacitanceEquipmentImVo != null) {
                        monthitem.put("serialNumber", i + 1);
                        monthitem.put("phase", capacitanceEquipmentImVo.getPhase());  //相位
                        monthitem.put("capacitance", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getCapacitance()) ? capacitanceEquipmentImVo.getCapacitance() : "");  //电容量
                        monthitem.put("lossFactor", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getLossFactor()) ? capacitanceEquipmentImVo.getLossFactor() : ""); //介质损耗因素
                        monthitem.put("unbalanceCurrent", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getUnbalanceCurrent()) ? capacitanceEquipmentImVo.getUnbalanceCurrent() : "");
                        monthitem.put("unbalanceVoltage", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getUnbalanceVoltage()) ? capacitanceEquipmentImVo.getUnbalanceVoltage() : "");
                        monthitem.put("totalCurrent", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getTotalCurrent()) ? capacitanceEquipmentImVo.getTotalCurrent() : "");
                        monthitem.put("systemVoltage", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getSystemVoltage()) ? capacitanceEquipmentImVo.getSystemVoltage() : ""); //系统电压
                        monthitem.put("state", StringUtils.isNotEmpty(capacitanceEquipmentImVo.getTotalCurrent()) ? capacitanceEquipmentImVo.getTotalCurrent() : ""); //运行状态
                        monthitem.put("timeStamp", capacitanceEquipmentImVo.getTimeStamp()); //采集时间  
                    }
                    monthList1.add(monthitem);
                }
            } else {
                Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
                monthitem.put("serialNumber", "");
                monthitem.put("phase", "");
                monthitem.put("capacitance", "");
                monthitem.put("lossFactor", "");
                monthitem.put("unbalanceCurrent", "");
                monthitem.put("unbalanceVoltage", "");
                monthitem.put("totalCurrent", "");
                monthitem.put("systemVoltage", "");
                monthitem.put("state", "");
                monthitem.put("timeStamp", "");
                monthList1.add(monthitem);
            }
            resultData.put("rxMonthList", monthList1);
        } else {
            resultData.put("reportCode", "");
            resultData.put("reportDate", exportTime);
            resultData.put("detectionDate", "");
            resultData.put("installLocation", "");
            resultData.put("operationDate", "");
            resultData.put("remark", "");
            resultData.put("val1", "");
            resultData.put("val2", "");
            resultData.put("val3", "");
            resultData.put("dataMissingRate", "");
            resultData.put("lastCheckTime", "");
            resultData.put("manufacturer", "");
            resultData.put("checkFrequency", "");
            resultData.put("warningNumber", "");
            resultData.put("falseWarningNumber", "");
            resultData.put("lastOverhaulDate", "");
            resultData.put("reportEvaluation", "");
            resultData.put("processOpinions", "");
            List<Map<String, Object>> pdList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> item = Maps.newLinkedHashMapWithExpectedSize(7);
            item.put("falseAlarmRate", "");
            item.put("totalCount", "");
            item.put("gzCount", "");
            pdList1.add(item);
            resultData.put("rxList", pdList1);
            resultData.put("reporter", "");
            resultData.put("signatory", "");
            resultData.put("reportDescription", "");
            List<Map<String, Object>> monthList1 = Lists.newArrayListWithCapacity(10);
            Map<String, Object> monthitem = Maps.newLinkedHashMapWithExpectedSize(8);
            monthitem.put("serialNumber", "");
            monthitem.put("phase", "");
            monthitem.put("capacitance", "");
            monthitem.put("lossFactor", "");
            monthitem.put("unbalanceCurrent", "");
            monthitem.put("unbalanceVoltage", "");
            monthitem.put("totalCurrent", "");
            monthitem.put("systemVoltage", "");
            monthitem.put("state", "");
            monthitem.put("timeStamp", "");
            monthList1.add(monthitem);
            resultData.put("rxMonthList", monthList1);
        }
        result.put("fileName", "容性设备检测装置管理考核");
        result.put("data", resultData);
        return result;

    }
}
