package com.zksy.base.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zksy.base.alarm.domain.AlarmData;
import com.zksy.base.alarm.service.AlarmDataService;
import com.zksy.base.service.DrillAlarmSyncService;
import com.zksy.base.service.DrillSimulationService;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentType;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.EquipmentTypeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DrillSimulationServiceImpl implements DrillSimulationService {

    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;
    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;
    @Autowired
    private AlarmDataService alarmDataService;
    @Autowired
    private DrillAlarmSyncService drillAlarmSyncService;

    @Override
    public Map<String, Object> triggerAlarm(String category) {
        EquipmentType topType = equipmentTypeMapper.selectOne(
                new LambdaQueryWrapper<EquipmentType>()
                        .eq(EquipmentType::getTypeName, category)
                        .eq(EquipmentType::getParentTypeId, "0"));
        if (topType == null) {
            throw new IllegalArgumentException("未找到项目类型对应的设备分类：" + category);
        }
        List<String> typeIds = new ArrayList<>();
        typeIds.add(topType.getId());
        collectChildTypeIds(topType.getId(), typeIds);

        List<EquipmentBase> equipments = equipmentBaseMapper.selectList(
                new LambdaQueryWrapper<EquipmentBase>()
                        .in(EquipmentBase::getEquipmentTypeId, typeIds));
        if (CollUtil.isEmpty(equipments)) {
            throw new IllegalArgumentException("未找到" + category + "类型下的设备");
        }
        Map<String, String> typeNameMap = equipmentTypeMapper.selectBatchIds(typeIds).stream()
                .collect(Collectors.toMap(EquipmentType::getId, EquipmentType::getTypeName, (a, b) -> a));

        int successCount = 0, failCount = 0;
        LocalDateTime now = LocalDateTime.now();
        for (EquipmentBase eq : equipments) {
            try {
                AlarmData alarm = new AlarmData();
                alarm.setDeviceCode(eq.getEquipmentCode());
                alarm.setWarningType(typeNameMap.getOrDefault(eq.getEquipmentTypeId(), "未知类型") + "模拟告警");
                alarm.setWarningCode("DRILL-" + System.currentTimeMillis());
                alarm.setMinValue(new BigDecimal("0"));
                alarm.setMaxValue(new BigDecimal("100"));
                alarm.setActualValue(new BigDecimal("150"));
                alarm.setAlarmLevel(1);
                alarm.setAlarmStatus(0);
                alarm.setAlarmTime(now);
                alarm.setDeviationRatio(new BigDecimal("50"));
                alarm.setRemark("演练模拟告警-" + category);
                alarm.setCreateTime(now);
                boolean saved = alarmDataService.saveAlarmData(alarm);
                if (saved) {
                    drillAlarmSyncService.syncCreateCaseAndWorkOrder(alarm);
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("模拟告警失败, equipmentId={}", eq.getEquipmentId(), e);
                failCount++;
            }
        }
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("category", category);
        result.put("total", equipments.size());
        result.put("success", successCount);
        result.put("fail", failCount);
        return result;
    }

    private void collectChildTypeIds(String parentId, List<String> typeIds) {
        List<EquipmentType> children = equipmentTypeMapper.selectList(
                new LambdaQueryWrapper<EquipmentType>()
                        .eq(EquipmentType::getParentTypeId, parentId));
        for (EquipmentType child : children) {
            typeIds.add(child.getId());
            collectChildTypeIds(child.getId(), typeIds);
        }
    }
}
