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

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

import com.huatek.busi.dto.EquipmentInfoDto;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.common.util.FieldUtil;
import com.huatek.busi.dao.CapacitanceEquipmentImCacheDao;
import com.huatek.busi.dto.CapacitanceEquipmentImCacheDto;
import com.huatek.busi.entity.BusiExternalEquipment;
import com.huatek.busi.entity.CapacitanceEquipmentIm;
import com.huatek.busi.entity.CapacitanceEquipmentImCache;
import com.huatek.busi.entity.CapacitanceEquipmentInsulationMonitorThreshold;
import com.huatek.busi.mapper.CapacitanceEquipmentImCacheMapper;
import com.huatek.busi.service.BusiCommonService;
import com.huatek.busi.service.BusiEqmWarningService;
import com.huatek.busi.service.BusiExternalEquipmentService;
import com.huatek.busi.service.BusiSensorService;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.BusiStabilityService;
import com.huatek.busi.service.capacitance.CapacitanceEquipmentImCacheService;
import com.huatek.busi.service.threshold.CapacitanceEquipmentInsulationMonitorThresholdService;
import com.huatek.busi.vo.BusiEquipmentVo;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.CapacitanceEquipmentImCacheVo;
import com.huatek.busi.vo.warning.BusiCapaItemVo;
import com.huatek.busi.vo.warning.BusiCapaItemVo.BusiCapaItemVoBuilder;
import com.huatek.busi.vo.warning.BusiCapaVo;

/**
 * 电容型设备——绝缘监测：022001实时数据表 ServiceImpl
 *
 * @author anker_cheng
 * @date Oct 28, 2019 7:02:05 PM
 */
@Component
@Service(interfaceClass = CapacitanceEquipmentImCacheService.class)
@Transactional(rollbackFor = Exception.class)
public class CapacitanceEquipmentImCacheServiceImpl implements CapacitanceEquipmentImCacheService {

    @Autowired
    private CapacitanceEquipmentImCacheMapper capacitanceEquipmentImCacheMapper;
    @Autowired
    private CapacitanceEquipmentImCacheDao capacitanceEquipmentImCacheDao;
    @Autowired
    private BusiCommonService busiCommonService;
    @Autowired
    private BusiEqmWarningService busiEqmWarningService;
    @Reference(check = false)
    private BusiExternalEquipmentService busiExternalEquipmentService;
    @Autowired
    protected BusiStabilityService busiStabilityService;
    @Reference(check = false)
    private BusiSensorService busiSensorService;
    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;
    @Reference(check = false)
    private CapacitanceEquipmentInsulationMonitorThresholdService capacitanceEquipmentInsulationMonitorThresholdService;

    @Override
    public synchronized int saveCapacitanceEquipmentImCache(CapacitanceEquipmentIm cacEntity, EquipmentInfoDto equipmentInfo) {
        CapacitanceEquipmentImCache entity = capacitanceEquipmentImCacheMapper
            .getCapacitanceEquipmentImCache(cacEntity.getSubTreeId(), cacEntity.getSensorId());
        if (entity == null) {
            entity = new CapacitanceEquipmentImCache();
            entity.setSubTreeId(cacEntity.getSubTreeId());
            entity.setSensorId(cacEntity.getSensorId());
        }
        entity.setPhase(cacEntity.getPhase());
        entity.setCacMonitorTypeCode(cacEntity.getCacMonitorTypeCode());
        entity.setSiteId(cacEntity.getSiteId());
        entity.setMainTreeId(cacEntity.getMainTreeId());
        entity.setMainEquipmentId(cacEntity.getMainEquipmentId());
        entity.setSubEquipmentId(cacEntity.getSubEquipmentId());
        entity.setTimeStamp(cacEntity.getTimeStamp());
        entity.setCapacitance(cacEntity.getCapacitance());
        entity.setLossFactor(cacEntity.getLossFactor());
        entity.setUnbalanceCurrent(cacEntity.getUnbalanceCurrent());
        entity.setUnbalanceVoltage(cacEntity.getUnbalanceVoltage());
        entity.setTotalCurrent(cacEntity.getTotalCurrent());
        entity.setSystemVoltage(cacEntity.getSystemVoltage());
        entity.setRunState(cacEntity.getRunState());
        entity.setType(cacEntity.getType());
        entity.setCreateTime(LocalDateTime.now());
        return capacitanceEquipmentImCacheDao.saveOrUpdate(entity);
    }
    
    /**
     * 获取容性设备实时数据
     */
	@Override
	public BusiCapaVo getUptoDateCapacitanceMonitor(CapacitanceEquipmentImCacheDto cacheDto) {
		// TODO Auto-generated method stub
        BusiCapaVo busiCapaVo = new BusiCapaVo();
		CapacitanceEquipmentImCacheVo  cacEntity = capacitanceEquipmentImCacheMapper.getUptoDateCapacitanceMonitor(cacheDto);
		if (ObjectUtils.isNotEmpty(cacEntity)) {
			String sensorId = cacheDto.getSensorId();
			String runState = cacEntity.getRunState();
	        CapacitanceEquipmentInsulationMonitorThreshold thresholdInfo =
	            capacitanceEquipmentInsulationMonitorThresholdService.getCapacitanceEquipmentInsulationMonitorThreshold(
	            		null, runState, sensorId);
			BusiExternalEquipment equipmentInfo = busiExternalEquipmentService.findBySensorCode(sensorId, ExternalTypeEnum.BLQ.getValue());
			if (ObjectUtils.isNotEmpty(equipmentInfo)) {
				String sensorPhase = cacEntity.getPhase();
		        Map<String, Object> stabilityMap= busiStabilityService.getStabilityBySensorCodeAndStatus(sensorId, runState);
		        String leakageCurrentThreshold = StringUtils.EMPTY;
		        String capacitanceThreshold = StringUtils.EMPTY;
		        String lossFactorThreshold = StringUtils.EMPTY;
		        String leakageCurrentWarning = StringUtils.EMPTY;
		        String capacitanceWarning = StringUtils.EMPTY;
		        String lossFactorWarning = StringUtils.EMPTY;
				if (ObjectUtils.isNotEmpty(thresholdInfo)) {
			        // 泄漏电流、电容量、介质损耗因数的预警值、阈值
			        leakageCurrentThreshold = getThresholdVal(thresholdInfo,sensorPhase, "LeakageCurrent");
			        capacitanceThreshold = getThresholdVal(thresholdInfo, sensorPhase, "Capacitance");
			        lossFactorThreshold = getThresholdVal(thresholdInfo, sensorPhase, "LossFactor");
			        leakageCurrentWarning = getWarningVal(thresholdInfo, sensorPhase, "LeakageCurrent");
			        capacitanceWarning = getWarningVal(thresholdInfo, sensorPhase, "Capacitance");
			        lossFactorWarning = getWarningVal(thresholdInfo, sensorPhase, "LossFactor"); 
				}
				// 泄漏电流
		        BusiCapaItemVoBuilder builder1 = BusiCapaItemVo.builder().phase(cacEntity.getPhase()).name("泄漏电流（mA）")
		            .collectValue(cacEntity.getTotalCurrent()).thresholdValue(leakageCurrentThreshold)
		            .equipmentStatus(cacEntity.getRunState()).warningValue(leakageCurrentWarning);
		        // 电容量
		        BusiCapaItemVoBuilder builder2 = BusiCapaItemVo.builder().phase(cacEntity.getPhase()).name("电容（pF）")
		            .collectValue(cacEntity.getCapacitance()).equipmentStatus(cacEntity.getRunState())
		            .thresholdValue(capacitanceThreshold).warningValue(capacitanceWarning);
		        if (gt(capacitanceThreshold, cacEntity.getCapacitance())) {
		            builder2.alarmValue(cacEntity.getCapacitance());
		        }
		        // 介质损耗因数
		        BusiCapaItemVoBuilder builder3 = BusiCapaItemVo.builder().phase(cacEntity.getPhase()).name("介损（tgθ）")
		            .collectValue(cacEntity.getLossFactor()).equipmentStatus(cacEntity.getRunState())
		            .thresholdValue(lossFactorThreshold).warningValue(lossFactorWarning);
		        //  稳定性指标
		        builder3.stabilityIndex(getString(stabilityMap, "lossFactor", "--"));
		        busiCapaVo.setList(Arrays.asList(builder1.build(),builder2.build(),builder3.build()));
		        busiCapaVo.setEquipmentName(equipmentInfo.getEquipmentName());
		        busiCapaVo.setCollectDate(cacEntity.getTimeStamp());
				busiCapaVo.setExternalType(equipmentInfo.getExternalType());
				
		        //监测装置名称
		        BusiEquipmentVo equipmentVo = busiSiteTreeService.findBySensorCode(sensorId, ExternalTypeEnum.BLQ.getValue());
		        busiCapaVo.setEquipmentName(equipmentVo.getEquipmentName());
		        busiCapaVo.setMainEquipmentName(equipmentVo.getMainEquipmentName());
		        BusiSensorVo busiSensorVo = busiSensorService.getBusiSensorVo(ExternalTypeEnum.BLQ, sensorId);
		        if (ObjectUtils.isNotEmpty(busiSensorVo)) {
			        //标牌
		        	busiCapaVo.setBrand(busiSensorVo.getSensorBrand());
			        //生产厂家
		        	busiCapaVo.setManufactor(busiSensorVo.getManufactor());
			        //安装位置
		        	busiCapaVo.setInstallLocation(busiSensorVo.getPositionDes());
		        	busiCapaVo.setPhase(busiSensorVo.getPosition());
			        //投运时间
		        	busiCapaVo.setUseDate(busiSensorVo.getUseDate());
		        }
				
//		        //设备名称
//				busiCapaVo.setEquipmentName(equipmentInfo.getEquipmentName());
//		        //标牌
//				busiCapaVo.setBrand(equipmentInfo.getEquipmentBrand());
//		        //生产厂家
//				busiCapaVo.setManufactor(equipmentInfo.getManufactor());
//		        //安装位置
//				busiCapaVo.setInstallLocation(equipmentInfo.getInstallLocation());
//		        //投运时间
//				busiCapaVo.setUseDate(equipmentInfo.getUseDate());
				//维修次数
				busiCapaVo.setRepairCount(busiCommonService.getEquipHalfYearRepairCount(ExternalTypeEnum.BLQ, cacheDto.getSubEquipmentId()));
		        //误报率
				busiCapaVo.setFalseAlarmRate(busiEqmWarningService.getFalseAlarmRateBySensor(sensorId, DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay()));						
			}
		}
		return busiCapaVo;
	}
	
    private String getWarningVal(CapacitanceEquipmentInsulationMonitorThreshold threshold, String phase, String name) {
        return (String)FieldUtil.getFieldValue(threshold, phase(phase) + name + "Warning");
    }
    /**
     * 返回 aVal.compareTo(bVal)>0的结果，判断aVal是否大于bVal
     * 
     * @param aVal
     * @param bVal
     * @return
     */
    private static boolean gt(String aVal, String bVal) {
        return DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) > 0;
    }
    private String getThresholdVal(CapacitanceEquipmentInsulationMonitorThreshold threshold, String phase,
        String name) {
        return (String)FieldUtil.getFieldValue(threshold, phase(phase) + name + "Threshold");
    }
    private static String phase(String phase) {
        if (phase == null) {
            return "";
        }
        return phase.replace("相", "").toLowerCase();
    }
    /**
     * 字符串格式化</br>
     * 区别于String.format
     * 
     * @param format
     *            格式化PATTERN使用{}作为占位符
     * @param argArray
     *            参数数组
     * @return 格式化后的字符串
     */

    protected String getString(Map<String, Object> map, String key, String defaultVal) {
        if(map == null) {
            return null;
        }
        String val = (String)map.get(key);
        if(StringUtils.isEmpty(val)) {
            return defaultVal;
        }
        return val;
    }

}