package com.yeejoin.equipmanage.service.impl;

import com.yeejoin.equipmanage.common.entity.dto.FireResourceStatsDTO;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.service.IFireResourceSupervisionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Map;

@Slf4j
@Service
public class IFireResourceSupervisionServiceImpl implements IFireResourceSupervisionService {
    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    /**
     * 消防系统信息
     *
     * @param bizOrgCode 机构编码
     */
    @Override
    public FireResourceStatsDTO getFireSystemStats(String bizOrgCode) {
        Map<String, Object> resultMap = fireFightingSystemMapper.selectFireFightingSystemStats(bizOrgCode);
        return buildFireResourceStatsDTO(resultMap);
    }

    /**
     * 监测部件
     *
     * @param bizOrgCode 机构编码
     */
    @Override
    public FireResourceStatsDTO getMonitorComponentStats(String bizOrgCode) {
        Map<String, Object> resultMap = fireFightingSystemMapper.selectEquipmentSpecificStats(bizOrgCode);
        return buildFireResourceStatsDTO(resultMap);
    }

    /**
     * 消防车辆
     *
     * @param bizOrgCode 机构编码
     */
    @Override
    public FireResourceStatsDTO getFireCarStats(String bizOrgCode) {
        Map<String, Object> resultMap = fireFightingSystemMapper.selectCarStats(bizOrgCode);
        return buildFireResourceStatsDTO(resultMap);
    }

    private FireResourceStatsDTO buildFireResourceStatsDTO(Map<String, Object> resultMap) {
        FireResourceStatsDTO fireResourceStats = new FireResourceStatsDTO();
        fireResourceStats.setTotalCounts(Long.valueOf(resultMap.get("totalCount").toString()));
        fireResourceStats.setYellowCounts(Long.valueOf(resultMap.get("yellowCodeCount").toString()) );
        fireResourceStats.setRedCounts(Long.valueOf(resultMap.get("redCodeCount").toString()));

        long expCount = fireResourceStats.getYellowCounts() + fireResourceStats.getRedCounts();
        double abnormalRatio = 0;
        if (fireResourceStats.getTotalCounts() != 0 && expCount != 0) {
            abnormalRatio = (double) expCount / fireResourceStats.getTotalCounts() * 100;
        }

        if (abnormalRatio == 0) {
            fireResourceStats.setAbnormalRatio(0);
        } else {
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
            String formattedRatio = decimalFormat.format(abnormalRatio);
            fireResourceStats.setAbnormalRatio(Double.parseDouble(formattedRatio));
        }

        return fireResourceStats;
    }

}
