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.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

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.IcgeType;
import com.huatek.busi.common.SiteConstants.IecTypeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dto.BusiEqmWarningDto;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.service.BusiEqmWarningService;
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.service.transformer.BusiOfflineTransformerRepairService;
import com.huatek.busi.service.transformer.TransformerIcgeService;
import com.huatek.busi.util.CalcUtil;

@ReportImpl(value = "busiTXJJReportService", exportTypes = { ReportType.TX_MONTHLY_REPORT,
		ReportType.JJ_MONTHLY_REPORT })
public class BusiTXJJReportServiceImpl implements BusiCommonReportService {
	@Autowired
	private BusiSubTreeService busiSubTreeService;
	@Autowired
	private BusiEqmWarningService busiEqmWarningService;
	@Autowired
	private FailureRateService failureRateService;
	@Autowired
	private BusiStabilityService busiStabilityService;
	@Autowired
	private BusiOfflineTransformerRepairService busiOfflineTransformerRepairService;
	@Autowired
	private TransformerIcgeService transformerIcgeService;

	@Override
	public Map<String, Object> buildExportData(String exportType, List<String> sensors, String exportTime,
			String startTime, String endTime) {
		Map<String, Object> result = Maps.newLinkedHashMapWithExpectedSize(2);
		IcgeType iecgeType = null;
		if (exportType.equals(ReportType.TX_MONTHLY_REPORT)) {
			iecgeType = IcgeType.TX;
			result.put("fileName", "铁芯检测装置管理考核");
		} else if (exportType.equals(ReportType.JJ_MONTHLY_REPORT)) {
			iecgeType = IcgeType.JJ;
			result.put("fileName", "夹件检测装置管理考核");
		} else {
			return null;
		}
		String sensorCode = sensors.get(0);
		EquipmentInfoDto equipmentInfo = busiSubTreeService.findEquipmentInfo(sensorCode, SiteTreeEnum.BYQ.getValue());
		if (equipmentInfo == null) {
			return null;
		}
		result.put("data", buildExportData(iecgeType, equipmentInfo, exportTime, startTime, endTime));
		return result;
	}

	private Map<String, Object> buildExportData(IcgeType iecgeType, EquipmentInfoDto equipmentInfo, String exportTime,
			String start, String end) {
		Map<String, Object> resultData = Maps.newLinkedHashMap();
		// 报告编号
		resultData.put("reportCode", "");
		// 报告日期
		resultData.put("reportDate", LocalDate.now());
		// 设备投运日期
		resultData.put("useDate", getVal(equipmentInfo.getSensorUseDate()));
		// 生产厂家
		resultData.put("manufacturer", getVal(equipmentInfo.getSensorManufactor()));
		// 数据缺失率
		resultData.put("lossRate", "");
		// 稳定性
		resultData.put("totalCurrent1", "");
		resultData.put("totalCurrent2", "");
		resultData.put("totalCurrent3", "");
		// 检修次数
		resultData.put("repairCount", "");
		// 检修率
//        resultData.put("repairRate", "");
		// 报警次数
		resultData.put("warningCount", "");
		// 误报率
		resultData.put("falseRate", "");
		// 故障次数
		resultData.put("gzCount", "");
		// 报告人
		resultData.put("reportPeople", "");
		// 签字
		resultData.put("sign", "");
		// 报告评价说明
		resultData.put("reportDes", "");
		// 数据列表:item.val1-item.val7:序号、类型、告警信息、处理状态、工作状态、报警时间、备注
		resultData.put("warningList", Lists.newArrayList());
		DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		
		Map<String, LocalDateTime> mapDate = CalcUtil.getcurrentMonthDateMap();
		Map<String, Object> param = Maps.newHashMap();
		param.put("mainTreeId", equipmentInfo.getMainTreeId());
		param.put("sensorCode", equipmentInfo.getSensorCode());
		param.put("startTime", mapDate.get("startTime"));
		param.put("endTime", mapDate.get("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));

		Integer repairCount = busiOfflineTransformerRepairService.getTransformerRepairCount(param);
		repairCount = repairCount == null ? 0 : repairCount;

		// 数据缺失率
		String lossRate = failureRateService.getSensorLossRate(equipmentInfo.getSensorCode(), mapDate.get("startTime"),
				mapDate.get("endTime"));
		resultData.put("lossRate", getVal(lossRate));

		resultData.put("warningCount", totalCount);
		resultData.put("falseRate", calRate(wbCount, totalCount));
		resultData.put("gzCount", gzCount);
		resultData.put("repairCount", repairCount);
		resultData.put("repairRate", calRate(new BigDecimal(repairCount), totalCount));

		Map<String, Object> stabilityMap = busiStabilityService
				.findStabilityMapBySensorCode(equipmentInfo.getSensorCode());
		resultData.put("totalCurrent1",
				getVal(totalCurrentMap(stabilityMap, IecTypeEnum.FD.getValue()).get("totalCurrent")));
		resultData.put("totalCurrent2",
				getVal(totalCurrentMap(stabilityMap, IecTypeEnum.CS.getValue()).get("totalCurrent")));
		resultData.put("totalCurrent3",
				getVal(totalCurrentMap(stabilityMap, IecTypeEnum.KX.getValue()).get("totalCurrent")));

		
		LocalDateTime startTime = null;
		LocalDateTime endTime = null;
		
		if(start != null && !"".equals(start))
    	{
	        startTime = LocalDateTime.parse(start + " 00:00:00", dateTimeFormater);
	        endTime = LocalDateTime.parse(end + " 23:59:59", dateTimeFormater);
    	}
    	else
    	{
    		startTime = LocalDateTime.parse(LocalDate.now()+" 00:00:00",dateTimeFormater);
			endTime = LocalDateTime.parse( LocalDate.now().plusDays(1)+" 00:00:00",dateTimeFormater);
    	}
		
		List<Map<String,Object>> voList = transformerIcgeService.queryHistory(equipmentInfo.getSensorCode(),startTime,endTime);

//		List<BusiEqmWarningVo>  = busiEqmWarningService.findBusiEqmWarningList(busiEqmWarningDto);
		if (CollectionUtils.isEmpty(voList)) {
			return resultData;
		}
		List<Map<String, Object>> warningList = Lists.newArrayList();
		for (int i = 0; i < voList.size(); i++) {
			Map<String,Object> map = voList.get(i);
			Map<String, Object> item = Maps.newLinkedHashMapWithExpectedSize(8);
			item.put("val1", i + 1);
			item.put("val2", map.get("totalCoreCurrent"));
			
			String workState = map.get("runState").toString();
          	if("1".equals(workState))
        	{
          		item.put("val3", "发电");
        	}
        	if("2".equals(workState))
        	{
        		item.put("val3", "抽水");
        	}
        	if("3".equals(workState))
        	{
        		item.put("val3", "空闲");
        	}else 
        	{
        		item.put("val3", "");
        	}
			item.put("val4", map.get("timeStamp").toString());
			warningList.add(item);
		}
		resultData.put("warningList", warningList);
		return resultData;
	}

//	private static String getDealStatusName(String detalStatus) {
//		if (DealStatus.TO_DEAL.equals(detalStatus)) {
//			return "未处理";
//		}
//		if (DealStatus.DEALED.equals(detalStatus)) {
//			return "已处理";
//		}
//		return "";
//	}

	@SuppressWarnings("unchecked")
	private static Map<String, Object> totalCurrentMap(Map<String, Object> stabilityMap, String runStatus) {
		Object map = stabilityMap.get(runStatus);
		if (map == null || "".equals(map.toString().trim())) {
			return Maps.newLinkedHashMap();
		}
		return (Map<String, Object>) map;
	}

	/**
	 * 计算百分率， a / b * 100
	 * 
	 * @param a 被除数
	 * @param b 除数
	 * @return 百分比，保留4位小数
	 */
	private static String calRate(BigDecimal a, BigDecimal b) {
		BigDecimal rate = CalcUtil.calcRate(a, b);
		// 转换成百分比
		DecimalFormat df = new DecimalFormat("0.00##");
		return df.format(rate.multiply(BigDecimal.valueOf(100)));
	}

	private static String getVal(Object val) {
		return val == null ? "" : val.toString();
	}
}