package com.zksy.base.alarm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.alarm.domain.AlarmData;
import com.zksy.base.alarm.mapper.AlarmDataMapper;
import com.zksy.base.alarm.service.AlarmDataService;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.mapper.EquipmentBaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AlarmDataServiceImpl extends ServiceImpl<AlarmDataMapper, AlarmData>
    implements AlarmDataService {

    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;

    @Override
    public Page<AlarmData> findByPage(long pageNum, long pageSize, String deviceCode,
                                        String warningType, String warningCode,
                                        Integer alarmStatus, String equipmentType) {
        Page<AlarmData> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AlarmData> queryWrapper = new LambdaQueryWrapper<>();

        // 当传入 equipmentType='drainage' 时，通过 equipment_base 关联查询排水类设备编码列表
        // alarm_data 表的 warning_type 字段含义不同于 early_warning 表，不能直接用 '2' 过滤
        if ("drainage".equals(equipmentType)) {
            LambdaQueryWrapper<EquipmentBase> eqQuery = new LambdaQueryWrapper<>();
            eqQuery.in(EquipmentBase::getEquipmentTypeId, "6", "7", "8", "9")
                   .select(EquipmentBase::getEquipmentCode);
            List<EquipmentBase> devices = equipmentBaseMapper.selectList(eqQuery);
            List<String> deviceCodes = devices.stream()
                    .map(EquipmentBase::getEquipmentCode)
                    .filter(code -> code != null && !code.isEmpty())
                    .collect(Collectors.toList());
            if (deviceCodes.isEmpty()) {
                // 没有排水类设备，直接返回空结果
                return new Page<>(pageNum, pageSize);
            }
            queryWrapper.in(AlarmData::getDeviceCode, deviceCodes);
        }

        queryWrapper.like(deviceCode != null, AlarmData::getDeviceCode, deviceCode)
                .like(warningType != null, AlarmData::getWarningType, warningType)
                .like(warningCode != null, AlarmData::getWarningCode, warningCode)
                .eq(alarmStatus != null, AlarmData::getAlarmStatus, alarmStatus)
                .orderByDesc(AlarmData::getAlarmTime);
        Page<AlarmData> result = this.page(page, queryWrapper);

        // 填充 deviceName/longitude/latitude：通过 device_code 从 equipment_base 表关联查询
        fillDeviceInfo(result.getRecords());

        return result;
    }

    /**
     * 根据 deviceCode 从 equipment_base 表批量填充 deviceName、longitude、latitude
     */
    private void fillDeviceInfo(List<AlarmData> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        // 收集所有非空的 deviceCode
        List<String> codes = records.stream()
                .map(AlarmData::getDeviceCode)
                .filter(code -> code != null && !code.isEmpty())
                .distinct()
                .collect(Collectors.toList());
        if (codes.isEmpty()) {
            return;
        }
        // 批量查询 equipment_base
        LambdaQueryWrapper<EquipmentBase> eqWrapper = new LambdaQueryWrapper<>();
        eqWrapper.in(EquipmentBase::getEquipmentCode, codes)
                 .select(EquipmentBase::getEquipmentCode, EquipmentBase::getEquipmentName,
                         EquipmentBase::getLongitude, EquipmentBase::getLatitude);
        List<EquipmentBase> equipmentList = equipmentBaseMapper.selectList(eqWrapper);
        // 构建 code -> EquipmentBase 映射
        java.util.Map<String, EquipmentBase> codeEquipMap = equipmentList.stream()
                .filter(e -> e.getEquipmentCode() != null)
                .collect(Collectors.toMap(EquipmentBase::getEquipmentCode, e -> e, (a, b) -> a));
        // 回填 deviceName、longitude、latitude
        for (AlarmData record : records) {
            if (record.getDeviceCode() != null) {
                EquipmentBase eq = codeEquipMap.get(record.getDeviceCode());
                if (eq != null) {
                    if (eq.getEquipmentName() != null) {
                        record.setDeviceName(eq.getEquipmentName());
                    }
                    if (eq.getLongitude() != null) {
                        record.setLongitude(eq.getLongitude().toPlainString());
                    }
                    if (eq.getLatitude() != null) {
                        record.setLatitude(eq.getLatitude().toPlainString());
                    }
                }
            }
        }
    }

    @Override
    public List<AlarmData> getAlarmDataList(String deviceCode,
                                              String warningType, String warningCode,
                                              Integer alarmStatus) {
        LambdaQueryWrapper<AlarmData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(deviceCode != null, AlarmData::getDeviceCode, deviceCode)
                .like(warningType != null, AlarmData::getWarningType, warningType)
                .like(warningCode != null, AlarmData::getWarningCode, warningCode)
                .eq(alarmStatus != null, AlarmData::getAlarmStatus, alarmStatus);
        queryWrapper.orderByDesc(AlarmData::getAlarmTime);
        return this.list(queryWrapper);
    }

    @Override
    public boolean saveAlarmData(AlarmData alarmData) {
        if (alarmData.getAlarmTime() == null) {
            alarmData.setAlarmTime(LocalDateTime.now());
        }
        if (alarmData.getCreateTime() == null) {
            alarmData.setCreateTime(LocalDateTime.now());
        }
        if (alarmData.getAlarmStatus() == null) {
            alarmData.setAlarmStatus(0);
        }
        return this.save(alarmData);
    }
}
