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

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

import com.huatek.busi.common.DateUtils;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.dao.BusiGeneratorPdDao;
import com.huatek.busi.dao.BusiGeneratorSensorDao;
import com.huatek.busi.dao.BusiGeneratorSubTreeDao;
import com.huatek.busi.dto.*;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.BusiGeneratorPdMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.service.generatro.BusiGeneratorSensorService;
import com.huatek.busi.service.transformer.*;
import com.huatek.busi.vo.*;
import com.huatek.busi.vo.monitor.GeneratorPdVo;
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 com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.huatek.busi.common.BusiConstant.EqType;
import com.huatek.busi.common.BusiConstant.GzType;
import com.huatek.busi.common.BusiConstant.WarningStatus;
import com.huatek.busi.common.CacMonitorTypeCode;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.GisTreeEnum;
import com.huatek.busi.common.SiteConstants.OtherTreeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.CableTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.TimeUtil;
import com.huatek.busi.common.util.Tools;
import com.huatek.busi.mapper.TransformerPdMapper;
import com.huatek.busi.service.Other.OtherPdCacheService;
import com.huatek.busi.service.gis.BusiGisSensorService;
import com.huatek.busi.service.gis.GisPdCacheService;
import com.huatek.busi.service.impl.cac.AbstractCacEtlService;
import com.huatek.busi.vo.datainput.TransformerInputPdVo;
import com.huatek.busi.vo.monitor.TransformerPdVo;
import com.huatek.busi.vo.warning.BusiPdVo;
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.util.uuid.Uuid;
import org.springframework.util.CollectionUtils;

/**
 * 发电机局放
 */
@Component
@Service(interfaceClass = BusiGeneratorPdService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiGeneratorPdServiceImpl extends AbstractCacEtlService<BusiGeneratorPd> implements BusiGeneratorPdService {

    @Autowired
    private TransformerPdMapper transformerPdMapper;
    @Autowired
    private BusiGeneratorPdMapper busiGeneratorPdMapper;
    @Autowired
    private BusiCommonService busiCommonService;
    @Reference(check = false)
    private TransformerPdCacheService transformerPdCacheService;
    @Reference(check = false)
    private GisPdCacheService gisPdCacheService;
    @Reference(check = false)
    private TransformerPdRecordService transformerPdRecordService;
    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;
    @Reference(check = false)
    private BusiEqmWarningService busiEqmWarningService;
    @Autowired
    private BusiGeneratorSensorDao busiGeneratorSensorDao;

    @Autowired
    private BusiGeneratorSubTreeDao busiGeneratorSubTreeDao;
    @Autowired
    private BusiGeneratorPdDao busiGeneratorPdDao;

    @Reference(check = false)
    private BusiGeneratorSensorService busiGeneratorSensorService;

    @Override
    protected void saveBusiWarning(BusiGeneratorPd cacEntity, String cacMonitorTypeCode, String sensorId,
        EquipmentInfoDto equipmentInfo) {
    }

    @Override
    protected void saveHistoryData(BusiGeneratorPd cacEntity, EquipmentInfoDto equipmentInfo) {
    }

    /**
     * @Title: getDischargeCount
     * @Description: 获取放电次数
     * @createDate: Aug 12, 2019 7:20:14 PM
     * @param sensorCode
     * @param type
     * @return Integer
     */
    private Long getDischargeCount(String sensorCode, String type) {
        Long count = this.transformerPdRecordService.getCountBySensorCode(sensorCode);
        if (null != count) {
            return count + 1;
        }
        return 1L;
    }

    /**
     * @Title: formateJfWarningMsg
     * @Description: 告警信息
     * @createDate: Aug 12, 2019 7:18:43 PM
     * @param
     * @return String
     */
    private String formateJfWarningMsg(TransformerPd cacEntity, String eqTypeInfo) {
        return format("{}局放电量:{}超标", eqTypeInfo, cacEntity.getDischargeCapacity());
    }

    @Override
    public void updateCurrentData(BusiGeneratorPd cacEntity, EquipmentInfoDto equipmentInfo) {
    }

    @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>> pageInfo = busiGeneratorPdMapper.findCACPageData(params);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.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<BusiGeneratorPdVo> busiGeneratorPdVoList = busiGeneratorPdMapper.exportCacMonitorData(mapParams);
            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, "局放监测数据"));
            if (busiGeneratorPdVoList.isEmpty()) {
                busiGeneratorPdVoList = new ArrayList<>();
                busiGeneratorPdVoList.add(new BusiGeneratorPdVo());
            }
            returnMap.put("data", busiGeneratorPdVoList);
        } else {
            throw new RuntimeException("主设备编码不正确");
        }
        return returnMap;
    }

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

    @Override
    protected void saveBusiOnlineMonitorData(BusiOnlineMonitorData busiOnlineMonitorData, Map<String, Object> item) {
        busiOnlineMonitorData.setSubEquipmentType(SiteConstants.GeneratorTreeEnum.JF_EQM.getValue());
        busiOnlineMonitorData.setExtType(ExternalTypeEnum.GEN.getValue());
        busiOnlineMonitorData.setEquipmentType(SiteTreeEnum.GEN_EQM.getValue());
        // 这里将保存的任务交给父类方法完成，子类只需要修改指定几个字段就可以了
        super.saveBusiOnlineMonitorData(busiOnlineMonitorData, item);
    }

    @Override
    public List<BusiGeneratorPdVo> findReportDataList(String sensorCode, LocalDateTime startTime,
                                                      LocalDateTime endTime) {
    	return busiGeneratorPdMapper.findReportDataList(sensorCode, startTime, endTime);
    }
    

	@Override
	public List<Map<String, Object>> findReportDataListByFirstData(String sensorCode) {
		// TODO Auto-generated method stub
		return busiGeneratorPdMapper.findReportDataListByFirstData(sensorCode);
	}

//    @Override
//    public List<TransformerPdCountVo> getListEquInfo(String cacMonitorTypeCode, LocalDate day) {
//        BusiGeneratorPdCountDto param = new BusiGeneratorPdCountDto();
//        param.setCacMonitorTypeCode(cacMonitorTypeCode);
//        param.setStartTime(day.atStartOfDay());
//        param.setEndTime(day.plusDays(1).atStartOfDay());
//        return busiGeneratorPdMapper.getListEquInfo(param);
//    }

    @Override
    public PageInfo<Map<String, Object>> findGeneratorPdPage(TransformerPdDto dto) {
        PageInfo<Map<String, Object>> pageInfo =
            PageHelper.startPage(dto.getPage(), dto.getLimit())
                .doSelectPageInfo(() -> busiGeneratorPdMapper.findPdPage(dto));
        pageInfo.getList().stream().forEach(map -> {
            // 维修次数
//            map.put("repairCount", busiCommonService.getEquipHalfYearRepairCount(ExternalTypeEnum.GEN,
//                map.get("subEquipmentId").toString()));
//            // 误报率2
//            map.put("falseAlarmRate", busiEqmWarningService.getFalseAlarmRateBySensor(map.get("sensorId").toString(),
//                DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay()));
            
//            map.put("dschType",  BusiConstant.getDschTypeDescribe(map.get("dschType").toString()));
            
//            t.dsch_type AS dschType,
//	        t.pa_dsch_alm AS paDschAlm,
            
        });
        return pageInfo;
    }

    @Override
    public List<Object> exportGeneratorPdPage(TransformerPdDto transformerPdDto) {
        List<Object> exportMonitorData = Lists.newArrayList();
        List<GeneratorPdVo> pdList = busiGeneratorPdMapper.exportGeneratorPdPage(transformerPdDto);
        pdList.stream().forEach(pd -> {
            exportMonitorData.add(pd);
        });
        return exportMonitorData;
    }


    @Override
    public List<HomeActualVo> queryActuals() {
        List<HomeActualVo> homeActualVos=new ArrayList<>();
        List<String> equipmentTypeList=new ArrayList<>();
        equipmentTypeList.add(SiteConstants.GeneratorTreeEnum.JF_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;
    }

    @Override
    public List<GeneratorPdCountVo> getListEquInfo(LocalDate day) {
        BusiGeneratorPdCountDto param = new BusiGeneratorPdCountDto();
        param.setStartTime(day.atStartOfDay());
        param.setEndTime(day.plusDays(1).atStartOfDay());
        return busiGeneratorPdMapper.getListEquInfo(param);
    }

    @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"));

        List<BusiGeneratorPd> list = busiGeneratorPdDao.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;
        }

        BusiGeneratorPd busiGeneratorPd = list.get(0);

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

        homeActualDataVo1.setName("放电量");
        homeActualDataVo1.setValue(busiGeneratorPd.getDischargeCapacity());
        homeActualDataVo1.setDTime(busiGeneratorPd.getDTime());

        homeActualDataVo2.setName("放电位置");
        homeActualDataVo2.setValue(busiGeneratorPd.getDischargePosition());
        homeActualDataVo2.setDTime(busiGeneratorPd.getDTime());

        homeActualDataVo3.setName("放电次数");
        homeActualDataVo3.setValue(busiGeneratorPd.getPulseCount());
        homeActualDataVo3.setDTime(busiGeneratorPd.getDTime());

        homeActualDataVo4.setName("放电类型");
        homeActualDataVo4.setValue(busiGeneratorPd.getDschType());
        homeActualDataVo4.setDTime(busiGeneratorPd.getDTime());

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

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