package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.fuyuanshen.equipment.domain.bo.DeviceAlarmBo;
import com.fuyuanshen.equipment.domain.vo.AlarmStatisticsVo;
import com.fuyuanshen.equipment.domain.vo.DeviceAlarmVo;
import com.fuyuanshen.equipment.domain.vo.MonthlyAlarmStatisticsVo;
import com.fuyuanshen.equipment.domain.DeviceAlarm;
import com.fuyuanshen.equipment.mapper.DeviceAlarmMapper;
import com.fuyuanshen.equipment.service.IDeviceAlarmService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.HashMap;

/**
 * 设备告警Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-28
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DeviceAlarmServiceImpl implements IDeviceAlarmService {

    private final DeviceAlarmMapper baseMapper;


    /**
     * 查询设备告警
     *
     * @param id 主键
     * @return 设备告警
     */
    @Override
    public DeviceAlarmVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    /**
     * 分页查询设备告警列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备告警分页列表
     */
    @Override
    public TableDataInfo<DeviceAlarmVo> queryPageList(DeviceAlarmBo bo, PageQuery pageQuery) {
        // LambdaQueryWrapper<DeviceAlarm> lqw = buildQueryWrapper(bo);
        // Page<DeviceAlarmVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<DeviceAlarmVo> result = baseMapper.selectVoPage(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }


    /**
     * 查询符合条件的设备告警列表
     *
     * @param bo 查询条件
     * @return 设备告警列表
     */
    @Override
    public List<DeviceAlarmVo> queryList(DeviceAlarmBo bo) {
        LambdaQueryWrapper<DeviceAlarm> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DeviceAlarm> buildQueryWrapper(DeviceAlarmBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DeviceAlarm> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(DeviceAlarm::getId);
        lqw.eq(bo.getDeviceId() != null, DeviceAlarm::getDeviceId, bo.getDeviceId());
        // lqw.eq(StringUtils.isNotBlank(bo.getDeviceAction()), DeviceAlarm::getDeviceAction, bo.getDeviceAction());
        lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), DeviceAlarm::getDeviceName, bo.getDeviceName());
        lqw.eq(StringUtils.isNotBlank(bo.getDataSource()), DeviceAlarm::getDataSource, bo.getDataSource());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), DeviceAlarm::getContent, bo.getContent());
        lqw.eq(bo.getDeviceType() != null, DeviceAlarm::getDeviceType, bo.getDeviceType());
        lqw.eq(bo.getLongitude() != null, DeviceAlarm::getLongitude, bo.getLongitude());
        lqw.eq(bo.getLatitude() != null, DeviceAlarm::getLatitude, bo.getLatitude());
        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), DeviceAlarm::getLocation, bo.getLocation());
        lqw.eq(bo.getStartTime() != null, DeviceAlarm::getStartTime, bo.getStartTime());
        lqw.eq(bo.getFinishTime() != null, DeviceAlarm::getFinishTime, bo.getFinishTime());
        lqw.eq(bo.getDurationTime() != null, DeviceAlarm::getDurationTime, bo.getDurationTime());
        lqw.eq(bo.getTreatmentState() != null, DeviceAlarm::getTreatmentState, bo.getTreatmentState());
        return lqw;
    }

    /**
     * 新增设备告警
     *
     * @param bo 设备告警
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(DeviceAlarmBo bo) {
        DeviceAlarm deviceAlarm = new DeviceAlarm();
        // DeviceAlarm add = MapstructUtils.convert(bo, DeviceAlarm.class);
        BeanUtil.copyProperties(bo, deviceAlarm);
        validEntityBeforeSave(deviceAlarm);
        boolean flag = baseMapper.insert(deviceAlarm) > 0;
        if (flag) {
            bo.setId(deviceAlarm.getId());
        }
        return flag;
    }

    /**
     * 修改设备告警
     *
     * @param bo 设备告警
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(DeviceAlarmBo bo) {
        DeviceAlarm update = MapstructUtils.convert(bo, DeviceAlarm.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DeviceAlarm entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备告警信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    /**
     * 根据设备IMEI查询最新的一条告警数据
     *
     * @param deviceImei 设备IMEI
     * @return 设备告警
     */
    @Override
    public DeviceAlarmVo queryLatestByDeviceImei(String deviceImei) {
        return baseMapper.selectLatestByDeviceImei(deviceImei);
    }


    /**
     * 获取实时告警列表
     *
     * @return 设备告警列表
     */
    @Override
    public List<DeviceAlarmVo> getRealtimeAlarm() {
        return baseMapper.getRealtimeAlarm();
    }
    
    /**
     * 获取报警统计数据
     *
     * @return 报警统计数据
     */
    @Override
    public AlarmStatisticsVo getAlarmStatistics() {
        return baseMapper.getAlarmStatistics();
    }
    
    /**
     * 获取最近一年每月告警统计数据
     *
     * @return 每月告警统计数据
     */
    @Override
    public MonthlyAlarmStatisticsVo getMonthlyAlarmStatistics() {
        List<Map<String, Object>> result = baseMapper.getMonthlyAlarmStatistics();
        MonthlyAlarmStatisticsVo vo = new MonthlyAlarmStatisticsVo();
        
        if (result != null && !result.isEmpty()) {
            Map<String, Object> data = result.get(0);
            Map<String, Integer> monthlyStats = vo.getMonthlyStatistics();
            
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 将数据库查询结果转换为Integer类型
                Integer count = (value != null) ? Integer.valueOf(value.toString()) : 0;
                monthlyStats.put(key, count);
            }
        }
        
        return vo;
    }

}