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

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

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.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huatek.busi.common.BusiConstant.Phase;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.PositionType;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dao.RptAretMonitorDao;
import com.huatek.busi.dto.RptAretMonitorDto;
import com.huatek.busi.entity.ArresterInsulationMonitorThreshold;
import com.huatek.busi.entity.LightningrodIm;
import com.huatek.busi.entity.RptAretMonitor;
import com.huatek.busi.mapper.RptAretMonitorMapper;
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.arrester.RptAretMonitorService;
import com.huatek.busi.service.threshold.ArresterInsulationMonitorThresholdService;
import com.huatek.busi.vo.BusiEquipmentVo;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.RptAretMonitorVo;
import com.huatek.busi.vo.monitor.BusiRptArresterMonitorDeailsVo;
import com.huatek.busi.vo.monitor.BusiRptArresterMonitorVo;

/**
 * 避雷器-界面实时监测基础信息 ServiceImpl
 *
 * @author anker_cheng
 * @date Jul 1, 2019 2:17:45 PM
 */
@Component
@Service(interfaceClass = RptAretMonitorService.class)
@Transactional(rollbackFor = Exception.class)
public class RptAretMonitorServiceImpl implements RptAretMonitorService {

    @Autowired
    private RptAretMonitorMapper rptAretMonitorMapper;
    @Autowired
    private RptAretMonitorDao rptAretMonitorDao;
    @Autowired
    private BusiSensorService busiSensorService;
    @Autowired
    private BusiCommonService busiCommonService;
    @Autowired
    private BusiEqmWarningService busiEqmWarningService;
    @Autowired
    private ArresterInsulationMonitorThresholdService arresterInsulationMonitorThresholdService;
    @Reference(check = false)
    private BusiExternalEquipmentService busiExternalEquipmentService;
    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;
    
    @Reference(check = false)
    private BusiStabilityService busiStabilityService;

    @Override
    public Page<RptAretMonitorVo> findRptAretMonitorPage(RptAretMonitorDto rptAretMonitorDto) {
        if (rptAretMonitorDto.getPage() != null && rptAretMonitorDto.getLimit() != null) {
            PageHelper.startPage(rptAretMonitorDto.getPage(), rptAretMonitorDto.getLimit());
        }
        Page<RptAretMonitorVo> rptAretMonitors = rptAretMonitorMapper.selectRptAretMonitorPage(rptAretMonitorDto);
        return rptAretMonitors;
    }

    @Override
    public synchronized int saveRptAretMonitor(LightningrodIm cacEntity) {
        RptAretMonitor rptAretMonitor = rptAretMonitorMapper.getRptAretMonitor(cacEntity.getSubTreeId());
        if (rptAretMonitor == null) {
            rptAretMonitor = new RptAretMonitor();
        }
        Phase phase = Phase.fromName(cacEntity.getPhase());
        switch (phase) {
            case A:
                rptAretMonitor.setASensorId(cacEntity.getSensorId());
                rptAretMonitor.setAFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setAHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                rptAretMonitor.setACpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                break;
            case B:
                rptAretMonitor.setBSensorId(cacEntity.getSensorId());
                rptAretMonitor.setBFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setBHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                rptAretMonitor.setBCpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                break;
            case C:
                rptAretMonitor.setCSensorId(cacEntity.getSensorId());
                rptAretMonitor.setCFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setCHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                rptAretMonitor.setCCpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                break;
            case O:
                rptAretMonitor.setASensorId(cacEntity.getSensorId());
                rptAretMonitor.setAFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setAHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                rptAretMonitor.setBSensorId(cacEntity.getSensorId());
                rptAretMonitor.setBFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setBHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                rptAretMonitor.setCSensorId(cacEntity.getSensorId());
                rptAretMonitor.setCFullAlc(DecimalUtil.getVal(cacEntity.getTotalCurrent()));
                rptAretMonitor.setCHindranceAlc(DecimalUtil.getVal(cacEntity.getResistiveCurrent()));
                
                rptAretMonitor.setACpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                rptAretMonitor.setBCpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                rptAretMonitor.setCCpacitanceAlc(DecimalUtil.getVal(cacEntity.getCapacitanceCurrent()));
                
                break;
            default:
                break;

        }
        // 累计落雷次数
        BigDecimal actionCount = DecimalUtil.getVal(cacEntity.getActionCount());
        rptAretMonitor.setArresterCount(DecimalUtil.getVal(rptAretMonitor.getArresterCount()).add(actionCount));
        // 在实时表中保存避雷器春夏秋冬落雷次数
        int season = getSeason(cacEntity.getTimeStamp());
        if (season == 1) {
            rptAretMonitor.setSpringCount(DecimalUtil.getVal(rptAretMonitor.getSpringCount()).add(actionCount));
        } else if (season == 2) {
            rptAretMonitor.setSummerCount(DecimalUtil.getVal(rptAretMonitor.getSummerCount()).add(actionCount));
        } else if (season == 3) {
            rptAretMonitor.setAutumnCount(DecimalUtil.getVal(rptAretMonitor.getAutumnCount()).add(actionCount));
        } else if (season == 4) {
            rptAretMonitor.setWinterCount(DecimalUtil.getVal(rptAretMonitor.getWinterCount()).add(actionCount));
        }
        rptAretMonitor.setCacMonitorTypeCode(cacEntity.getCacMonitorTypeCode());
        rptAretMonitor.setSiteId(cacEntity.getSiteId());
        rptAretMonitor.setMainTreeId(cacEntity.getMainTreeId());
        rptAretMonitor.setMainEquipmentId(cacEntity.getMainEquipmentId());
        rptAretMonitor.setSubTreeId(cacEntity.getSubTreeId());
        rptAretMonitor.setSubEquipmentId(cacEntity.getSubEquipmentId());
        rptAretMonitor.setCreateTime(LocalDateTime.now());
        
        String lastActionTime = cacEntity.getLastActionTime();
        if(lastActionTime.contains("."))
        {
        	rptAretMonitor.setLastTime(LocalDateTime.parse(lastActionTime.split("\\.")[0],
    	            DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE_TIME)));
        }else
        {
	        rptAretMonitor.setLastTime(LocalDateTime.parse(cacEntity.getLastActionTime(),
	            DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE_TIME)));
        }
        rptAretMonitor.setRunState(cacEntity.getRunState());
        return rptAretMonitorDao.saveOrUpdate(rptAretMonitor);
    }

    /**
     * 返回四季的数字表示
     * 
     * @param date
     * @return 1、2、3、4分别表示春、夏、秋、冬
     */
    private static int getSeason(LocalDateTime date) {
        return (date.getMonthValue() - 1) % 4 + 1;
    }
    
    /**
     * 获取避雷器实时数据
     */
	@Override
	public BusiRptArresterMonitorVo getUptoDateRptAretMonitor(RptAretMonitorDto rptAretMonitorDto) {
		// TODO Auto-generated method stub
		BusiRptArresterMonitorVo busiRptArresterMonitorInfo = new BusiRptArresterMonitorVo();
		RptAretMonitorVo  rptAretMonitorVoInfo = rptAretMonitorMapper.getUptoDateRptAretMonitor(rptAretMonitorDto);
		//获取传感器基本信息，根据相位判断
		BusiSensorVo sensorInfo = busiSensorService.getBusiSensorVo(ExternalTypeEnum.BLQ, rptAretMonitorDto.getSensorId());
		boolean flag = ObjectUtils.isNotEmpty(rptAretMonitorVoInfo);
		if (ObjectUtils.isNotEmpty(sensorInfo)) {
			busiRptArresterMonitorInfo.setBrand(sensorInfo.getSensorBrand());
			busiRptArresterMonitorInfo.setManufactor(sensorInfo.getSensorBrand());
			busiRptArresterMonitorInfo.setInstallLocation(sensorInfo.getPositionDes());
			busiRptArresterMonitorInfo.setUseDate(sensorInfo.getUseDate());
			
			String arresterCount="0";
			String runState = "3";
			if(flag)
			{
				 arresterCount = rptAretMonitorVoInfo.getArresterCount()+"";
				 runState = rptAretMonitorVoInfo.getRunState() == null ? "":rptAretMonitorVoInfo.getRunState();
				 busiRptArresterMonitorInfo.setCollectDate(rptAretMonitorVoInfo.getCreateTime());
			}
//			String runState = rptAretMonitorVoInfo.getRunState() == null ? "":rptAretMonitorVoInfo.getRunState();
			
			busiRptArresterMonitorInfo.setTotalActionCount(flag ? arresterCount : "-");
			busiRptArresterMonitorInfo.setPhase(sensorInfo.getPosition());
			//维修次数
			busiRptArresterMonitorInfo.setRepairCount(flag ? busiCommonService.getEquipHalfYearRepairCount(ExternalTypeEnum.BLQ, rptAretMonitorVoInfo.getSubEquipmentId()) : 0);
	        //误报率
			busiRptArresterMonitorInfo.setFalseAlarmRate(busiEqmWarningService.getFalseAlarmRateBySensor(sensorInfo.getSensorCode(), DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay()));			
			String fullAlc = StringUtils.EMPTY;//实时数据
			String  capacitanceAlc = StringUtils.EMPTY;  //容性电流(mA)
			String resistiveAlc  = StringUtils.EMPTY;  //阻性电流(mA)
			
			String fullAlarmValue = StringUtils.EMPTY;//全电流告警值
			String fullThresholdValue = StringUtils.EMPTY;//全电流阈值
			
			String capacitanceCurrentWarning= StringUtils.EMPTY; //容性电流告警值
			String capacitanceCurrentThreshold = StringUtils.EMPTY;//容性电流阈值
			
			String resistiveCurrentWarning =  StringUtils.EMPTY;//阻性电流阈值
			String resistiveCurrentThreshold =  StringUtils.EMPTY;//阻性电流预警值
			
			ArresterInsulationMonitorThreshold  arresterInsulationMonitorThresholdInfo = flag ? arresterInsulationMonitorThresholdService.getArresterInsulationMonitorThreshold(rptAretMonitorVoInfo.getMainTreeId(), runState, rptAretMonitorDto.getSensorId()) : null;
//			ArresterInsulationMonitorThreshold  arresterInsulationMonitorThresholdInfo = arresterInsulationMonitorThresholdService.getArresterInsulationMonitorThreshold(rptAretMonitorVoInfo.getMainTreeId(), runState,rptAretMonitorDto.getSensorId());
			
			if (ObjectUtils.isNotEmpty(arresterInsulationMonitorThresholdInfo)) {
				if (sensorInfo.getPosition().equals(PositionType.AX.getValue())) {
					fullAlarmValue = arresterInsulationMonitorThresholdInfo.getAFullCurrentWarning(); 
					fullThresholdValue = arresterInsulationMonitorThresholdInfo.getAFullCurrentThreshold();
					
					capacitanceCurrentWarning = arresterInsulationMonitorThresholdInfo.getACapacitanceCurrentWarning();
					capacitanceCurrentThreshold = arresterInsulationMonitorThresholdInfo.getACapacitanceCurrentThreshold();
					
					resistiveCurrentWarning = arresterInsulationMonitorThresholdInfo.getAResistiveCurrentWarning();
					resistiveCurrentThreshold = arresterInsulationMonitorThresholdInfo.getAResistiveCurrentThreshold();
				} else if (sensorInfo.getPosition().equals(PositionType.BX.getValue())) {
					fullAlarmValue = arresterInsulationMonitorThresholdInfo.getBFullCurrentWarning(); 
					fullThresholdValue = arresterInsulationMonitorThresholdInfo.getBFullCurrentThreshold();
					
					capacitanceCurrentWarning =arresterInsulationMonitorThresholdInfo.getBCapacitanceCurrentWarning();; 
					capacitanceCurrentThreshold = arresterInsulationMonitorThresholdInfo.getBCapacitanceCurrentThreshold();
					
					resistiveCurrentWarning = arresterInsulationMonitorThresholdInfo.getBResistiveCurrentWarning();
					resistiveCurrentThreshold = arresterInsulationMonitorThresholdInfo.getBResistiveCurrentThreshold();
					
				} else {
					fullAlarmValue = arresterInsulationMonitorThresholdInfo.getCFullCurrentWarning(); //报警值
					fullThresholdValue = arresterInsulationMonitorThresholdInfo.getCFullCurrentThreshold();
					
					capacitanceCurrentWarning =arresterInsulationMonitorThresholdInfo.getCCapacitanceCurrentWarning();
					capacitanceCurrentThreshold = arresterInsulationMonitorThresholdInfo.getCCapacitanceCurrentThreshold();
					
					resistiveCurrentWarning = arresterInsulationMonitorThresholdInfo.getCResistiveCurrentWarning();
					resistiveCurrentThreshold = arresterInsulationMonitorThresholdInfo.getCResistiveCurrentThreshold();
				}
			}
			if(flag){
				if (sensorInfo.getPosition().equals(PositionType.AX.getValue())) {
					fullAlc =  rptAretMonitorVoInfo.getAFullAlc()!= null ? rptAretMonitorVoInfo.getAFullAlc().toString() : StringUtils.EMPTY;  
					resistiveAlc =  rptAretMonitorVoInfo.getAHindranceAlc()!= null ?  rptAretMonitorVoInfo.getAHindranceAlc().toString() :  StringUtils.EMPTY;
					capacitanceAlc =rptAretMonitorVoInfo.getACpacitanceAlc()!= null ? rptAretMonitorVoInfo.getACpacitanceAlc().toString() :  StringUtils.EMPTY;
				} else if (sensorInfo.getPosition().equals(PositionType.BX.getValue())) {
					fullAlc = rptAretMonitorVoInfo.getBFullAlc()!= null ? rptAretMonitorVoInfo.getBFullAlc().toString() : StringUtils.EMPTY;  
					resistiveAlc =rptAretMonitorVoInfo.getBHindranceAlc()!= null ?  rptAretMonitorVoInfo.getBHindranceAlc().toString() :  StringUtils.EMPTY; 
					capacitanceAlc = rptAretMonitorVoInfo.getBCpacitanceAlc()!= null ? rptAretMonitorVoInfo.getBCpacitanceAlc().toString() :  StringUtils.EMPTY;;
				} else {
					fullAlc = rptAretMonitorVoInfo.getCFullAlc()!= null ? rptAretMonitorVoInfo.getCFullAlc().toString() : StringUtils.EMPTY;
					resistiveAlc =  rptAretMonitorVoInfo.getCHindranceAlc()!= null ?  rptAretMonitorVoInfo.getCHindranceAlc().toString() :  StringUtils.EMPTY;
					capacitanceAlc = rptAretMonitorVoInfo.getCCpacitanceAlc()!= null ? rptAretMonitorVoInfo.getCCpacitanceAlc().toString() :  StringUtils.EMPTY;;
				}
			}
			
			BusiRptArresterMonitorDeailsVo vo1 = this.buildDeatil("全电流(mA)", fullAlc, fullThresholdValue, fullAlarmValue);
			BusiRptArresterMonitorDeailsVo vo2 =this.buildDeatil("阻性电流(mA)", resistiveAlc, resistiveCurrentThreshold, resistiveCurrentWarning);
//			BusiRptArresterMonitorDeailsVo vo3 =this.buildDeatil("容性电流(mA)", capacitanceAlc, capacitanceCurrentThreshold, capacitanceCurrentWarning);
			
			vo1.setTotalActionCount(arresterCount);
			vo2.setTotalActionCount(arresterCount);
//			vo3.setTotalActionCount(arresterCount);
			
			vo1.setEquipmentStatus(runState);
			vo2.setEquipmentStatus(runState);
//			vo3.setEquipmentStatus(runState);
			
			Map<String, Object> map = busiStabilityService.getStabilityBySensorCodeAndStatus(rptAretMonitorDto.getSensorId(), runState);
			if(null != map ){
				if(map.containsKey("totalCurrent")){
					vo1.setStabilityIndex(map.get("totalCurrent")!=null ? map.get("totalCurrent").toString() : "");
				}
				if(map.containsKey("resistiveCurrent")){
					vo2.setStabilityIndex(map.get("resistiveCurrent")!=null ? map.get("resistiveCurrent").toString() : "");
				}
				if(map.containsKey("capacitanceCurrent")){
//					vo3.setStabilityIndex(map.get("capacitanceCurrent")!=null ? map.get("capacitanceCurrent").toString() : "");
				}
			}
			List<BusiRptArresterMonitorDeailsVo> list = new ArrayList<>();
			list.add(vo1);
			list.add(vo2);
//			list.add(vo3);
			busiRptArresterMonitorInfo.setList(list);
		/*	busiRptArresterMonitorInfo.setFullAlc(fullAlc); 
			busiRptArresterMonitorInfo.setFullAlarmValue(fullAlarmValue);
			busiRptArresterMonitorInfo.setFullThresholdValue(fullThresholdValue);
			busiRptArresterMonitorInfo.setHindranceAlc(hindranceAlc);
			busiRptArresterMonitorInfo.setHindranceAlarmValue(hindranceAlarmValue);
			busiRptArresterMonitorInfo.setHindranceThresholdValue(hindranceThresholdValue);*/
		}
		//监测装置名称
        BusiEquipmentVo equipmentVo = busiSiteTreeService.findBySensorCode(sensorInfo.getSensorCode(), ExternalTypeEnum.BLQ.getValue());
        busiRptArresterMonitorInfo.setEquipmentName(equipmentVo.getEquipmentName());
        busiRptArresterMonitorInfo.setMainEquipmentName(equipmentVo.getMainEquipmentName());

		return busiRptArresterMonitorInfo;
	}
	
	
	public BusiRptArresterMonitorDeailsVo buildDeatil (String name, String collectValue, String thresholdValue, String warningValue){
		return new BusiRptArresterMonitorDeailsVo(name, collectValue, thresholdValue, warningValue);
	}
}