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

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.CacMonitorTypeCode;
import com.huatek.busi.common.DateUtils;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.SiteConstants.CableTreeEnum;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.common.util.Tools;
import com.huatek.busi.dao.*;
import com.huatek.busi.dto.*;
import com.huatek.busi.dto.curve.BaseCurveQueryDto;
import com.huatek.busi.dto.curve.PointItemDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.BusiGeneratorAmplMapper;
import com.huatek.busi.mapper.BusiGeneratorPressureMapper;
import com.huatek.busi.mapper.CwzzTemperatureMapper;
import com.huatek.busi.mapper.TransformerInfraredTemperatureMapper;
import com.huatek.busi.service.BusiGeneratorAmplService;
import com.huatek.busi.service.BusiGeneratorPressureService;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.IecBydworkParamService;
import com.huatek.busi.service.generatro.BusiGeneratorSensorService;
import com.huatek.busi.service.impl.cac.AbstractCacEtlService;
import com.huatek.busi.service.threshold.CwzzThresholdService;
import com.huatek.busi.service.threshold.GeneratorAmplThresholdService;
import com.huatek.busi.vo.*;
import com.huatek.busi.vo.curve.PointItemVo;
import com.huatek.busi.vo.monitor.BusiOnlineMonitorDataVo;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.WherePrams;
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 org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 压力装置
 */
@Component
@Service(interfaceClass = BusiGeneratorPressureService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiGeneratorPressureServiceImpl extends AbstractCacEtlService<BusiGeneratorPressure> implements BusiGeneratorPressureService {

    @Autowired
    private CwzzThresholdService cwzzThresholdService;

    @Reference(check = false)
    private IecBydworkParamService iecBydworkParamService;

    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;

    @Autowired
    private BusiGeneratorSensorDao busiGeneratorSensorDao;

    @Autowired
    private BusiGeneratorSubTreeDao busiGeneratorSubTreeDao;

    @Autowired
    private BusiGeneratorPressureDao busiGeneratorPressureDao;

    @Autowired
    private GeneratorAmplThresholdDao generatorAmplThresholdDao;

    @Autowired
    private GeneratorAmplThresholdService generatorAmplThresholdService;
//
//    @Reference(check = false)
//    private TransformerInfraredMonitoringCacheService transformerInfraredMonitoringCacheService;
//
//    @Reference(check = false)
//    private BusiEqmWarningPictureService busiEqmWarningPictureService;

//    @Value("${warningpicture.base.path}")
//    private String pictureBasePath;
//
//    @Value("${warningpicture.base.num}")
//    private Integer pictureBaseNum;
//
//    @Value("${warningpicture.base.suffix}")
//    private String suffix;
//
//    @Value("${warningpicture.base.startTime}")
//    private String startTime;
//
//    @Value("${warningpicture.base.endTime}")
//    private String endTime;
//
//    @Value("${nginx.video.capture}")
//    private String videoCapture;

    @Autowired
    private TransformerInfraredTemperatureMapper transformerInfraredTemperatureMapper;

    @Autowired
    private CwzzTemperatureMapper cwzzTemperatureMapper;

    @Autowired
    private BusiGeneratorAmplMapper busiGeneratorAmplMapper;

    @Autowired
    private BusiGeneratorPressureMapper busiGeneratorPressureMapper;

    @Autowired
    private CwzzTemperatureDao cwzzTemperatureDao;

    @Autowired
    private BusiTransformerSensorDao busiTransformerSensorDao;


    @Autowired
    private BusiOnlineMonitorDataDao busiOnlineMonitorDataDao;

    @Autowired
    private CwzzThresholdDao cwzzThresholdDao;

    @Reference(check = false)
    private BusiGeneratorSensorService busiGeneratorSensorService;
//
//    @Autowired
//    private BusiVideoMapper busiVideoMapper;


    // √
    @Override
    public void saveHistoryData(BusiGeneratorPressure cacEntity, EquipmentInfoDto equipmentInfo) {
//        // 设备状态
//        String state = iecBydworkParamService.getIecType(cacEntity.getMainTreeId(), cacEntity.getTimeStamp());
//        if (StringUtils.isEmpty(state)) {
//            logger.warn("IecType is empty! eqmCode: {}, timeStamp: {}", cacEntity.getEquipmentCode(),
//                    cacEntity.getTimeStamp());
//        }
//        cacEntity.setRunState(state);
//        // 设置rowkey，导入hbase使用
//        cacEntity.setHbaseRowkey(Tools.strReverse(TimeUtil.getTimeStr(cacEntity.getTimeStamp())) + "_"
//                + cacEntity.getSensorId() + "_" + TimeUtil.getTimeStr(cacEntity.getTimeStamp()) + "_"
//                + cacEntity.getCacMonitorTypeCode() + "_" + cacEntity.getMainTreeId());
//
//        // 保存
//        super.saveHistoryData(cacEntity, equipmentInfo);
    }

    @Override
    public List<BusiGeneratorPressureVo> queryHistory(String sensorCode, LocalDateTime startTime, LocalDateTime endTime) {
        return busiGeneratorPressureMapper.queryHistory(sensorCode,startTime,endTime);
    }

    @Override
    public HomeActualVo queryActual(HomeSearchDto param) {
        HomeActualVo homeActualVo=new HomeActualVo();
        List<BusiGeneratorSensor> busiGeneratorSensors = busiGeneratorSensorDao.list(new WherePrams()
                .where("sensor_code", param.getSensorCode()));
        if(ObjectUtils.isEmpty(busiGeneratorSensors)){
            return homeActualVo;
        }
        HomeActualInfoVo homeActualInfoVo =new HomeActualInfoVo();
        BusiGeneratorSensor busiGeneratorSensor = busiGeneratorSensors.get(0);
        String mainTreeId=busiGeneratorSubTreeDao.get(busiGeneratorSensor.getEquipmentId()).getEquipmentId();
        homeActualInfoVo = build(homeActualInfoVo, busiGeneratorSensor,mainTreeId);
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -1));
//        BusiOnlineMonitorData busiOnlineMonitorData = busiOnlineMonitorDataDao.get(new WherePrams()
//                .where("sensor_code", param.getSensorCode())
//                .and("day","like",date));
//        //组装各种率
//        if(!ObjectUtils.isEmpty(busiOnlineMonitorData)){
//            homeActualInfoVo.setRunState(busiOnlineMonitorData.getRunState());
//            homeActualInfoVo.setFalseAlarmRate(busiOnlineMonitorData.getFalseAlarmRate());
//            homeActualInfoVo.setLossRate(busiOnlineMonitorData.getLossRate());
//            homeActualInfoVo.setRepairCount(busiOnlineMonitorData.getRepairCount());
//            homeActualInfoVo.setDTime(busiOnlineMonitorData.getCreatedTime());
//        }
        homeActualVo.setHomeActualInfoVo(homeActualInfoVo);
        List<BusiGeneratorPressure> list = busiGeneratorPressureDao.list(new WherePrams()
                .where("sensor_id", param.getSensorCode())
                .orderBy("d_time desc limit 1"));

        List<HomeActualDataVo> homeActualDataVos=new ArrayList<>();

        if(CollectionUtils.isEmpty(list)){

            return homeActualVo;
        }

        BusiGeneratorPressure busiGeneratorPressure = list.get(0);
        GeneratorAmplThreshold generatorAmplThreshold = new GeneratorAmplThreshold();
        if (!ObjectUtils.isEmpty(busiGeneratorPressure.getRunState())) {
            generatorAmplThreshold = generatorAmplThresholdDao.get(new WherePrams()
                    .where("sensor_code", param.getSensorCode()).and("work_status", busiGeneratorPressure.getRunState()));
        } else {
            generatorAmplThreshold = null;
        }

        HomeActualDataVo homeActualDataVo1 = new HomeActualDataVo();
        HomeActualDataVo homeActualDataVo2 = new HomeActualDataVo();

        homeActualDataVo1.setName("压力1");
        homeActualDataVo1.setValue(busiGeneratorPressure.getPvA());
        String thresholdValue1="";
        if(!ObjectUtils.isEmpty(generatorAmplThreshold)){
            thresholdValue1=generatorAmplThreshold.getPvAThreshold();
        }
        homeActualDataVo1.setThresholdValue(thresholdValue1);
        homeActualDataVo1.setDTime(busiGeneratorPressure.getDTime());

        homeActualDataVo2.setName("压力2");
        homeActualDataVo2.setValue(busiGeneratorPressure.getPvB());
        String thresholdValue2="";
        if(!ObjectUtils.isEmpty(generatorAmplThreshold)){
            thresholdValue2=generatorAmplThreshold.getPvBThreshold();
        }
        homeActualDataVo2.setThresholdValue(thresholdValue2);
        homeActualDataVo2.setDTime(busiGeneratorPressure.getDTime());

        homeActualDataVos.add(homeActualDataVo1);
        homeActualDataVos.add(homeActualDataVo2);

        homeActualVo.setHomeActualDataVos(homeActualDataVos);
        return homeActualVo;
    }

    public  HomeActualInfoVo build(HomeActualInfoVo homeActualInfoVo,BusiGeneratorSensor busiGeneratorSensor,String mainTreeId){
        homeActualInfoVo.setEquipmentBrand(busiGeneratorSensor.getSensorBrand());
        homeActualInfoVo.setEquipmentName(busiGeneratorSensor.getSensorName());
        homeActualInfoVo.setInstallLocation(busiGeneratorSensor.getPositionDes());
        homeActualInfoVo.setEqmId(busiGeneratorSensor.getEquipmentId());
        homeActualInfoVo.setPhase(busiGeneratorSensor.getPosition());
        homeActualInfoVo.setManufactor(busiGeneratorSensor.getManufactor());
        homeActualInfoVo.setSensorBrand(busiGeneratorSensor.getSensorBrand());
        homeActualInfoVo.setUseDate(busiGeneratorSensor.getUseDate());
        homeActualInfoVo.setSensorId(busiGeneratorSensor.getSensorCode());
        homeActualInfoVo.setSensorName(busiGeneratorSensor.getSensorName());
        homeActualInfoVo.setMainTreeId(mainTreeId);
        return homeActualInfoVo;
    }

    // √
    @Override
    protected void saveBusiWarning(BusiGeneratorPressure cacEntity, String cacMonitorTypeCode, String sensorId,
                                   EquipmentInfoDto equipmentInfo) {
//        equipmentInfo.setSensorCode(sensorId);
//        CacMonitorTypeCode type = CacMonitorTypeCode.from(cacMonitorTypeCode);
//        if (StringUtils.isEmpty(cacEntity.getTmp())) {
//            logger.debug("变压器测温装置温度为空不生成告警");
//            return;
//        }
//        String tmp = cacEntity.getTmp();
//        // 阈值
//        CwzzThresholdVo threshold = cwzzThresholdService.queryCwzzThreshold(cacEntity.getSensorId(), cacEntity.getRunState());
//        if (threshold == null || StringUtils.isEmpty(threshold.getRegionThreshold())) {
//            logger.warn("变压器测温阈值未匹配，sensorCode: {}, runState: {}", cacEntity.getSensorId(), cacEntity.getRunState());
//            return;
//        }
//        // 告警
//        if (isThreshold(tmp, threshold.getRegionThreshold())) {
//            String eqType = "";
//            // 变压器告警
//            if (CacMonitorTypeCode.TRANSFORMER_CW.isThis(cacEntity.getCacMonitorTypeCode())) {
//                eqType = EqType.EQ_TYPE1;
//            }
//            // 电缆告警
//            else if (CacMonitorTypeCode.DL_CW.isThis(cacEntity.getCacMonitorTypeCode())) {
//                eqType = EqType.EQ_TYPE7;
//            }
//            else {
//                logger.warn("未找到匹配的对象");
//                return;
//            }
//            // 保存告警
//            BusiEqmWarning busiEqmWarning = newEw(eqType, GzType.GZ_TYPE21, formateCwWarningMsg(cacEntity),
//                    cacEntity.getCacMonitorTypeCode(),"1");
//            busiEqmWarning.setWarningTime(cacEntity.getTimeStamp());
//            busiEqmWarning.setRunState(cacEntity.getRunState());
//            busiEqmWarning.setWarningFlag("1");
//            busiEqmWarning = this.buildWarning(busiEqmWarning, equipmentInfo);
//            // 保存告警详情
//            BusiWcgVo vo = new BusiWcgVo();
//            vo.setEquipmentName(equipmentInfo.getSubEquipmentName());
//            vo.setCollectValue(cacEntity.getTmp());
//            vo.setAlarmValue(cacEntity.getTmp());
//            vo.setThresholdValue(threshold.getRegionThreshold());
//            vo.setEquipmentStatus(cacEntity.getRunState());
//            vo.setCollectDate(cacEntity.getTimeStamp());
//            vo.setDayIncreaseRate("");
//            vo.setMonthIncreaseRate("");
//            vo.setPhase(cacEntity.getPhase());
//            this.buildWarningInfo(busiEqmWarning, JSON.toJSONString(vo));
//        }
    }

    /**
     * 判断告警
     */
    private static boolean isThreshold(String aVal, String bVal) {
        if (StringUtils.isEmpty(aVal)) {
            return false;
        }
        if (StringUtils.isEmpty(bVal)) {
            return false;
        }
        return DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) > 0;
    }

    private String formateCwWarningMsg(CwzzTemperature cacEntity) {
        return format("{}测温装置：{}℃温度超标", cacEntity.getPhase(), cacEntity.getTmp());
    }

    @Override
    public void updateCurrentData(BusiGeneratorPressure cacEntity, EquipmentInfoDto equipmentInfo) {
        // todo 测温暂时不保存到缓存
//        transformerInfraredMonitoringCacheService.saveTransformerInfraredMonitoringCache(cacEntity);
    }

    private String msg(TransformerInfraredTemperature cacEntity) {
        return format("温度:{}℃超标", cacEntity.getMaxTmp());
    }

    /**
     * 原始数据查询
     */
    @Override
    public Map<String, Object> findCACPageData(Map<String, Object> params) {
        if (params.get("page") != null && params.get("limit") != null) {
            PageHelper.startPage(page(params), limit(params));
        }
        Page<Map<String, Object>> page = busiGeneratorPressureMapper.findCACPageData(params);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "", page.getResult());
    }

    @Override
    public Map<String, Object> exportCacMonitorData(Map<String, Object> mapParams) {
        Map<String, Object> returnMap = new HashMap<>();
        if (mapParams.containsKey("mainTreeId") && StringUtils.isNotEmpty(mapParams.get("mainTreeId") + "")) {
            BusiSiteTree busiSiteTree = busiSiteTreeService.findByPK(mapParams.get("mainTreeId") + "");
            List<BusiGeneratorPressureVo> busiGeneratorPressureVoList =
                    busiGeneratorPressureMapper.exportCacMonitorData(mapParams);
            if (busiGeneratorPressureVoList.isEmpty()) {
                busiGeneratorPressureVoList = new ArrayList<>();
                busiGeneratorPressureVoList.add(new BusiGeneratorPressureVo());
            }
            returnMap.put("data", busiGeneratorPressureVoList);
            String replaceRegex = "[\\\\n`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
            String treeName = busiSiteTree.getName().replaceAll(replaceRegex, "-");
            returnMap.put("fileName", String.format("%s%s", treeName, "压力数据"));
            returnMap.put("title", String.format("%s%s", treeName, "压力数据"));
        } else {
            throw new RuntimeException("主设备编码不正确");
        }
        return returnMap;
    }

    @Override
    public List<BaseCurveQueryDto> findSensorCodeList(LocalDate day) {
//        return transformerInfraredTemperatureMapper.findSensorCodeList(day.atStartOfDay(),
//                day.plusDays(1).atStartOfDay());
        return busiGeneratorPressureMapper.findSensorCodeList(day.atStartOfDay(),
                day.plusDays(1).atStartOfDay());
    }

    @Override
    public List<PointItemVo> findDaylyPointList(BaseCurveQueryDto sensorCode, LocalDate day, String subType) {
//        return transformerInfraredTemperatureMapper.findDaylyPointList(sensorCode, subType, day.atStartOfDay(),
//                day.plusDays(1).atStartOfDay());
        return busiGeneratorPressureMapper.findDaylyPointList(sensorCode, subType, day.atStartOfDay(),
                day.plusDays(1).atStartOfDay());
    }

    @Override
    public PointItemDto getDaylyPointStatistics(BaseCurveQueryDto param) {
//        return transformerInfraredTemperatureMapper.getDaylyPointStatistics(param);
        return busiGeneratorPressureMapper.getDaylyPointStatistics(param);
    }

    @Override
    protected List<Map<String, Object>> queryMonitorDataList(LocalDateTime startTime, LocalDateTime endTime) {
//        return transformerInfraredTemperatureMapper.queryMonitorDataList(startTime, endTime);
        return busiGeneratorPressureMapper.queryMonitorDataList(startTime, endTime);
    }

    // 保存监测数据
    @Override
    protected void saveBusiOnlineMonitorData(BusiOnlineMonitorData busiOnlineMonitorData, Map<String, Object> item) {
//        String cacMonitorTypeCode = popString(item, "cacMonitorTypeCode");
//        // 变压器测温
//        if (CacMonitorTypeCode.TRANSFORMER_CW.isThis(cacMonitorTypeCode)) {
//            busiOnlineMonitorData.setSubEquipmentType(TransfromerTreeEnum.CW_EQM.getValue());
//            busiOnlineMonitorData.setExtType(ExternalTypeEnum.BYQ.getValue());
//            busiOnlineMonitorData.setEquipmentType(SiteTreeEnum.BYQ_EQM.getValue());
//        }
//        // 电缆测温
//        else if (CacMonitorTypeCode.DL_CW.isThis(cacMonitorTypeCode)) {
//            busiOnlineMonitorData.setSubEquipmentType(CableTreeEnum.CW_EQM.getValue());
//            busiOnlineMonitorData.setExtType(ExternalTypeEnum.DL.getValue());
//            busiOnlineMonitorData.setEquipmentType(SiteTreeEnum.DL_EQM.getValue());
//        }
//        else {
//            throw new OwlException(format("数据错误，sensorCode: {}", busiOnlineMonitorData.getSensorCode()));
//        }
        busiOnlineMonitorData.setSubEquipmentType(SiteConstants.GeneratorTreeEnum.YL_EQM.getValue());
        busiOnlineMonitorData.setExtType(ExternalTypeEnum.GEN.getValue());
        busiOnlineMonitorData.setEquipmentType(SiteTreeEnum.GEN_EQM.getValue());
        // 这里将保存的任务交给父类方法完成，子类只需要修改指定几个字段就可以了
        super.saveBusiOnlineMonitorData(busiOnlineMonitorData, item);
    }

    @Override
    protected Map<String, Object> thresholdDataMap(BusiOnlineMonitorDataVo vo) {
        GeneratorAmplThresholdVo thresholdVo =
                generatorAmplThresholdService.queryGeneratorAmplThreshold(vo.getSensorCode(), vo.getRunState());
        return Tools.beanToMap(thresholdVo, "id");
    }

//    @Override
//    public CwzzTemperatureStatisticsVo getListEquInfo(String cacMonitorTypeCode, LocalDate day, String sensorCode) {
//        CwzzTemperatureStatisticsDto param = new CwzzTemperatureStatisticsDto();
//        param.setStartTime(day.atStartOfDay());
//        param.setEndTime(day.plusDays(1).atStartOfDay());
//        param.setCacMonitorTypeCode(cacMonitorTypeCode);
//        param.setSensorCode(sensorCode);
//        List<CwzzTemperatureStatisticsVo> list = cwzzTemperatureMapper.getListEquInfo(param);
//        if (CollectionUtils.isEmpty(list)) {
//            return null;
//        }
//        return list.get(0);
//    }

    @Override
    public GeneratorPressureStatisticsVo getListEquInfo(LocalDate day, String sensorCode) {
        GeneratorPressureStatisticsDto param = new GeneratorPressureStatisticsDto();
        param.setStartTime(day.atStartOfDay());
        param.setEndTime(day.plusDays(1).atStartOfDay());
        param.setSensorCode(sensorCode);
        List<GeneratorPressureStatisticsVo> list = busiGeneratorPressureMapper.getListEquInfo(param);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<HomeActualVo> queryActuals() {
        List<HomeActualVo> homeActualVos=new ArrayList<>();
        List<String> equipmentTypeList=new ArrayList<>();
        equipmentTypeList.add(SiteConstants.GeneratorTreeEnum.YL_EQM.getValue());
        BusiSensorQueryParamDto param =new BusiSensorQueryParamDto();
        param.setEquipmentTypeList(equipmentTypeList);
        List<BusiSensorVo> sensorList =  busiGeneratorSensorService.findSensorList(param);
        if(CollectionUtils.isEmpty(sensorList)){
            return homeActualVos;
        }
        for (BusiSensorVo busiSensorVo:sensorList) {
            HomeSearchDto homeSearchDto= new HomeSearchDto();
            homeSearchDto.setSensorCode(busiSensorVo.getSensorCode());
            HomeActualVo homeActualVo = this.queryActual(homeSearchDto);
            homeActualVo.setName(busiSensorVo.getMainEquipmentName());
            homeActualVos.add(homeActualVo);
        }
        return homeActualVos;
    }
}
