package com.huatek.busi.service.impl;

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.dto.cable.BusiCableThresholdDto;
import com.huatek.busi.entity.BusiCableThreshold;
import com.huatek.busi.entity.IecBydworkParam;
import com.huatek.busi.mapper.BusiCableThresholdMapper;
import com.huatek.busi.mapper.BusiEqmWarningMapper;
import com.huatek.busi.mapper.BusiOfflineCableRepairMapper;
import com.huatek.busi.mapper.IecBydworkParamMapper;
import com.huatek.busi.service.BusiEquipmentRelationshipService;
import com.huatek.busi.service.IBusiCableThresholdService;
import com.huatek.busi.util.CalcUtil;
import com.huatek.busi.vo.TransformerTmpVo;
import com.huatek.busi.vo.cable.BusiCableThresholdVo;
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.sql.dao.impl.BaseDao;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@Service(interfaceClass = IBusiCableThresholdService.class)
@Transactional(rollbackFor = Exception.class)
public class IBusiCableThresholdServiceImpl extends BaseDao<BusiCableThreshold, String> implements IBusiCableThresholdService {

    @Resource
    private BusiCableThresholdMapper busiCableThresholdMapper;

    @Autowired
    private BusiEquipmentRelationshipService busiEquipmentRelationshipService;
    @Autowired
    private IecBydworkParamMapper iecBydworkParamMapper;

    @Autowired
    private BusiEqmWarningMapper busiEqmWarningMapper;

    @Autowired
    private BusiOfflineCableRepairMapper busiOfflineCableRepairMapper;

    @Override
    public int deleteCableThresholdBySensorCode(String sensorCode) {
        return busiCableThresholdMapper.deleteCableThresholdBySensorCode(sensorCode);
    }

    @Override
    public int updateCableThresholdBySensorCode(String oldSensorCode, String newSensorCode) {
        return busiCableThresholdMapper.updateCableThresholdBySensorCode(oldSensorCode, newSensorCode);
    }

    @Override
    public Map<String, Object> findCableVo(BusiCableThresholdDto dto) {
        BusiCableThresholdVo CableThresholdVo = busiCableThresholdMapper.getCableThresholdVo(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", CableThresholdVo);
    }

    @Override
    public Map<String, Object> getGrowthRate(BusiCableThresholdDto dto) {
        BusiCableThresholdVo CableThresholdVo = busiCableThresholdMapper.getGrowthRate(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", CableThresholdVo);
    }

    @Override
    public Map<String, Object> deleteCableThreshold(BusiCableThresholdDto dto) {
        int CableThresholdVo = busiCableThresholdMapper.deleteCableThreshold(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", CableThresholdVo);
    }

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

    @Override
    public BusiCableThreshold getCableThreshold(String mainTreeId, String runState, String sensorCode) {
        return busiCableThresholdMapper.getCableThreshold(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 = busiCableThresholdMapper.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 = busiOfflineCableRepairMapper.getRepairCountForCable(param);
            if (warningCount != null && (count.compareTo(0) > 0 && warningCount.compareTo(0) >0) || count.equals(warningCount))
            {
                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 BusiCableThreshold getCableBySensorCodeThreshold(String sensorCode) {
        return busiCableThresholdMapper.getCableBySensorCodeThreshold(sensorCode);
    }
}
