package com.hdkj.lt.bf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.bf.entity.AlarmEvent;
import com.hdkj.lt.bf.entity.dto.AlarmIndicatorDTO;
import com.hdkj.lt.bf.entity.vo.AlarmFeederVO;
import com.hdkj.lt.bf.mapper.AlarmEventMapper;
import com.hdkj.lt.bf.service.AlarmEventService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 告警事件 Service 实现
 */
@Slf4j
@Service
public class AlarmEventServiceImpl extends ServiceImpl<AlarmEventMapper, AlarmEvent> implements AlarmEventService {

    /**
     * status → 中文
     */
    private static final Map<Integer, String> STATUS_LABELS = new LinkedHashMap<Integer, String>();
    static {
        STATUS_LABELS.put(0, "待处理");
        STATUS_LABELS.put(1, "重构中");
        STATUS_LABELS.put(2, "已完成");
        STATUS_LABELS.put(3, "已忽略");
    }

    @Override
    public List<AlarmFeederVO> getAlarmFeederList(LocalDate alarmDate) {
        List<AlarmEvent> list = baseMapper.selectAlarmListWithFeederName(alarmDate);
        List<AlarmFeederVO> result = new ArrayList<>(list.size());
        for (AlarmEvent event : list) {
            AlarmFeederVO vo = AlarmFeederVO.builder()
                    .id(event.getId())
                    .countyName(event.getCountyName())
                    .feederId(event.getFeederId())
                    .feederName(event.getFeederName())
                    .alarmLabels(convertAlarmLabels(event.getAlarmTypes()))
                    .alarmIndicators(buildAlarmIndicators(event))
                    .alarmCount(event.getAlarmCount())
                    .alarmDate(event.getAlarmDate())
                    .alarmTime(event.getAlarmTime())
                    .lastAlarmTime(event.getLastAlarmTime())
                    .statusName(convertStatus(event.getStatus()))
                    .indicatorResultId(event.getIndicatorResultId())
                    .maxLoadRatePct(event.getMaxLoadRatePct())
                    .healthScore(event.getHealthScore())
                    .build();
            result.add(vo);
        }
        return result;
    }

    /**
     * alarm_types 英文枚举 → 中文标签列表（去重），用于红色标签展示
     */
    private List<String> convertAlarmLabels(String alarmTypes) {
        List<String> labels = new ArrayList<String>();
        if (StringUtils.isBlank(alarmTypes)) {
            return labels;
        }
        Set<String> seen = new LinkedHashSet<String>();
        for (String type : alarmTypes.split(",")) {
            String trimmed = type.trim();
            String label = null;
            if ("load_rate".equals(trimmed)) {
                label = "线路重过载";
            } else if ("voltage_over".equals(trimmed) || "voltage_under".equals(trimmed)) {
                label = "电压越限";
            }
            if (label != null && seen.add(label)) {
                labels.add(label);
            }
        }
        return labels;
    }

    /**
     * 构建"异常指标"展示字符串列表
     * <p>
     * 根据 alarm_types 拼接中文标签 + 数值：
     * <ul>
     *   <li>load_rate    → "线路重过载 79.70%"</li>
     *   <li>voltage_over  → "电压越限 1.05pu"</li>
     *   <li>voltage_under → "电压越限 0.92pu"</li>
     * </ul>
     * voltage_over 和 voltage_under 都映射"电压越限"，但数值不同：
     * - voltage_over 取 maxVoltagePu（越上限，取最大值）
     * - voltage_under 取 minVoltagePu（越下限，取最小值）
     */
    private List<AlarmIndicatorDTO> buildAlarmIndicators(AlarmEvent event) {
        List<AlarmIndicatorDTO> result = new ArrayList<AlarmIndicatorDTO>();
        if (StringUtils.isBlank(event.getAlarmTypes())) {
            return result;
        }

        Set<String> seen = new LinkedHashSet<>();
        for (String type : event.getAlarmTypes().split(",")) {
            String trimmed = type.trim();
            if ("load_rate".equals(trimmed)) {
                String label = "线路重过载";
                if (seen.add(label)) {
                    BigDecimal val = event.getMaxLoadRatePct();
                    result.add(new AlarmIndicatorDTO(label, val));
                }
            } else if ("voltage_over".equals(trimmed)) {
                String label = "电压越限";
                if (seen.add(label)) {
                    BigDecimal val = event.getMaxVoltagePu();
                    result.add(new AlarmIndicatorDTO(label, val));
                }
            } else if ("voltage_under".equals(trimmed)) {
                String label = "电压越限";
                if (seen.add(label)) {
                    BigDecimal val = event.getMinVoltagePu();
                    result.add(new AlarmIndicatorDTO(label, val));
                }
            }
        }
        return result;
    }

    /**
     * status 数字 → 中文
     */
    private String convertStatus(Integer status) {
        if (status == null) {
            return null;
        }
        return STATUS_LABELS.get(status);
    }
}
