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

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.BusiOtherThresholdDao;
import com.huatek.busi.dto.cable.BusiOtherThresholdDto;
import com.huatek.busi.entity.BusiOtherThreshold;
import com.huatek.busi.entity.IecBydworkParam;
import com.huatek.busi.mapper.BusiEqmWarningMapper;
import com.huatek.busi.mapper.BusiOfflineOtherRepairMapper;
import com.huatek.busi.mapper.IecBydworkParamMapper;
import com.huatek.busi.mapper.cable.BusiOtherThresholdMapper;
import com.huatek.busi.service.BusiEquipmentRelationshipService;
import com.huatek.busi.service.cable.BusiOtherThresholdService;
import com.huatek.busi.util.CalcUtil;
import com.huatek.busi.vo.TransformerOilThresholdVo;
import com.huatek.busi.vo.TransformerTmpVo;
import com.huatek.busi.vo.cable.BusiOtherThresholdVo;
import com.huatek.busi.vo.cable.CableCirculationDataVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
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 java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 其他阈值接口实现
 *
 * @author Bobi_huo
 * @date 2020-09-16 13:19
 */
@Slf4j
@Component
@Service(interfaceClass = BusiOtherThresholdService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiOtherThresholdServiceImpl implements BusiOtherThresholdService {

    @Autowired
    private BusiOtherThresholdDao busiOtherThresholdDao;
    @Autowired
    private BusiEquipmentRelationshipService busiEquipmentRelationshipService;
    @Autowired
    private IecBydworkParamMapper iecBydworkParamMapper;
    @Autowired
    private BusiOtherThresholdMapper busiOtherThresholdMapper;

    @Autowired
    private BusiEqmWarningMapper busiEqmWarningMapper;

    @Autowired
    private BusiOfflineOtherRepairMapper busiOfflineOtherRepairMapper;

    @Override
    public Map<String, Object> findOtherVo(BusiOtherThresholdDto dto) {
        BusiOtherThresholdVo otherThresholdVo = busiOtherThresholdMapper.getOtherThresholdVo(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", otherThresholdVo);
    }

    @Override
    public Map<String, Object> getGrowthRate(BusiOtherThresholdDto dto) {
        BusiOtherThresholdVo otherThresholdVo = busiOtherThresholdMapper.getGrowthRate(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", otherThresholdVo);
    }

    @Override
    public Map<String, Object> deleteOtherThreshold(BusiOtherThresholdDto dto) {
        int otherThresholdVo = busiOtherThresholdMapper.deleteOtherThreshold(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", otherThresholdVo);
    }

    @Override
    public Map<String, Object> saveOtherThreshold(String token, BusiOtherThresholdDto dto) {
        int result = 0;
        BusiOtherThreshold entity = new BusiOtherThreshold();
        BeanUtils.copyPropertiesWithIgnoreNull(dto, entity);
        if (StringUtils.isNotEmpty(entity.getId())) {
            entity.setModifiedTime(LocalDateTime.now());
            result = busiOtherThresholdDao.updateLocal(entity);
        } else {
            entity.setId(Uuid.getUUID());
            entity.setCreatedTime(LocalDateTime.now());
            entity.setCreator("");
            entity.setModifiedTime(LocalDateTime.now());
            entity.setModifier("");
            result = busiOtherThresholdDao.add(entity);
        }
        //判断新增是否成功
        if (result > 0) {
            log.debug("addCable: {}", result);
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "新增或者编辑成功", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "新增失败", "");
    }

    @Override
    public int updateOtherThresholdBySensorCode(String oldSensorCode, String newSensorCode) {
        return busiOtherThresholdMapper.updateOtherThresholdBySensorCode(oldSensorCode, newSensorCode);
    }

    @Override
    public int deleteOtherThresholdBySensorCode(String sensorCode) {
        return busiOtherThresholdMapper.delOtherThresholdBySensorCode(sensorCode);
//        int result = busiOtherThresholdMapper.delOtherThresholdBySensorCode(sensorCode);
//        if (result > 0) {
//            log.debug("delCable: {}", result);
//            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "删除成功", "");
//        }
//        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "删除失败", "");
    }

    @Override
    public BusiOtherThreshold getOtherThreshold(String mainTreeId, String runState, String sensorCode) {
        return busiOtherThresholdMapper.getOtherThreshold(mainTreeId, runState, sensorCode);
    }

    @Override
    public CableCirculationDataVo getCableData(String sensorCode,String transformerId) {
        String status = "";
        int runStatus = 10 ;
        List<TransformerTmpVo> transformerList = busiEquipmentRelationshipService.getCurrentTransformerInfo(transformerId);
        if (CollectionUtils.isEmpty(transformerList)) {
            status="";
        }
        else {
            for(TransformerTmpVo transformer : transformerList) {
                IecBydworkParam iecBydworkParam = iecBydworkParamMapper.getIecType2(transformer.getTransformerId());
                if(iecBydworkParam == null || iecBydworkParam.getStype() == null) {
                    continue;
                }
                if(runStatus == 0) {
                    runStatus = iecBydworkParam.getStype();
                }else if(runStatus > iecBydworkParam.getStype().intValue()){
                    runStatus = iecBydworkParam.getStype();
                }
            }
            status = runStatus+"";
        }
        // 查询信息
        CableCirculationDataVo dataVos = busiOtherThresholdMapper.getCableData(sensorCode,status);
        if(dataVos!=null)
        {
            // 所有告警类型
            Integer count = busiEqmWarningMapper.getWarningCount(sensorCode, null,DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay());
            // 误报次数
            Integer warningCount = busiEqmWarningMapper.getWarningCount(sensorCode, "2",DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay());
            // 维修次数
            Map<String, Object> param = new HashMap<>();
            param.put("sensorCode", sensorCode);
            param.put("startTime", DateUtil.getHalfYearDate());
            param.put("endTime", DateUtil.getCurrentHourDate());
            // 获取前半年的维修次数
            Integer repairCount = busiOfflineOtherRepairMapper.getRepairCountForOther(param);
            if (warningCount != null && (count.compareTo(0) > 0 && warningCount.compareTo(0) >0) || count.equals(warningCount))
            {
//                dataVos.setAlarmRate(new BigDecimal(warningCount/count).setScale(2, BigDecimal.ROUND_HALF_UP));
                BigDecimal A = CalcUtil.calcRate(BigDecimal.valueOf(warningCount),BigDecimal.valueOf(count));
                dataVos.setAlarmRate(A);
            } else {
                dataVos.setAlarmRate(BigDecimal.valueOf(0));
            }
            dataVos.setMaintenanceCount(repairCount);
        }
        else
        {
             dataVos = new CableCirculationDataVo();
        }
        return dataVos;
    }

    @Override
    public CableCirculationDataVo getCableDataForCable(String sensorCode,String transformerId) {
        String status = "";
        int runStatus = 10 ;
        List<TransformerTmpVo> transformerList = busiEquipmentRelationshipService.getCurrentTransformerInfo(transformerId);
        if (CollectionUtils.isEmpty(transformerList)) {
            status="";
        }
        else {
            for(TransformerTmpVo transformer : transformerList) {
                IecBydworkParam iecBydworkParam = iecBydworkParamMapper.getIecType2(transformer.getTransformerId());
                if(iecBydworkParam == null || iecBydworkParam.getStype() == null) {
                    continue;
                }
                if(runStatus == 0) {
                    runStatus = iecBydworkParam.getStype();
                }else if(runStatus > iecBydworkParam.getStype().intValue()){
                    runStatus = iecBydworkParam.getStype();
                }
            }
            status = runStatus+"";
        }
        // 查询信息
        CableCirculationDataVo dataVos = busiOtherThresholdMapper.getCableDataForCable(sensorCode,status);
        if(dataVos!=null)
        {
            // 所有告警类型
            Integer count = busiEqmWarningMapper.getWarningCount(sensorCode, null,DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay());
            // 误报次数
            Integer warningCount = busiEqmWarningMapper.getWarningCount(sensorCode, "2",DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay());
            // 维修次数
            Map<String, Object> param = new HashMap<>();
            param.put("sensorCode", sensorCode);
            param.put("startTime", DateUtil.getHalfYearDate());
            param.put("endTime", DateUtil.getCurrentHourDate());
            // 获取前半年的维修次数
            Integer repairCount = busiOfflineOtherRepairMapper.getRepairCountForOther(param);
            if (warningCount != null && (count.compareTo(0) > 0 && warningCount.compareTo(0) >0) || count.equals(warningCount))
            {
//                dataVos.setAlarmRate(new BigDecimal(warningCount/count).setScale(2, BigDecimal.ROUND_HALF_UP));
                BigDecimal A = CalcUtil.calcRate(BigDecimal.valueOf(warningCount),BigDecimal.valueOf(count));
                dataVos.setAlarmRate(A);
            } else {
                dataVos.setAlarmRate(BigDecimal.valueOf(0));
            }
            dataVos.setMaintenanceCount(repairCount);
        }
        else
        {
            dataVos = new CableCirculationDataVo();
        }
        return dataVos;
    }

    @Override
    public BusiOtherThreshold getCableThreshold(String sensorCode) {
        return busiOtherThresholdMapper.getCableThreshold(sensorCode);
    }

    @Override
    public BusiOtherThresholdVo getBySensorCode(String sensorCode) {
        return busiOtherThresholdMapper.selectBySensorCode(sensorCode);
    }
}
