package vip.xiaonuo.coldchain.core.alarm.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.coldchain.core.alarm.bean.SensorAlarm;
import vip.xiaonuo.coldchain.core.alarm.enums.SensorAlarmType;
import vip.xiaonuo.coldchain.core.alarm.mapper.SensorAlarmMapper;
import vip.xiaonuo.coldchain.modular.app.param.Message;
import vip.xiaonuo.coldchain.modular.app.param.MessagePageParam;
import vip.xiaonuo.coldchain.modular.app.param.MessageType;
import vip.xiaonuo.coldchain.modular.monitornotice.param.MonitorNoticePageParam;
import vip.xiaonuo.common.page.CommonPageRequest;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jackzhou
 * @version 1.0
 * @project jfcloud-coldchain
 * @description
 * @date 2024/11/27 16:55:56
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SensorAlarmServiceImpl extends ServiceImpl<SensorAlarmMapper, SensorAlarm> implements SensorAlarmService {

    /**
     * app接口
     *
     * @param messagePageParam
     * @return
     */
    @Override
    public Page<Message> getMessages(MessagePageParam messagePageParam) {
        Page<SensorAlarm> sensorAlarmPage = getSensorAlarmPage(messagePageParam);
        // 将查询结果转换成Message类型的分页对象
        Page<Message> resultPage = new Page<>();
        resultPage.setSize(messagePageParam.getSize());
        resultPage.setCurrent(messagePageParam.getCurrent());
        resultPage.setRecords(sensorAlarmPage.getRecords().stream().map(this::convertToMessage) // 转换为Message类型
                .collect(Collectors.toList()));
        resultPage.setTotal(sensorAlarmPage.getTotal()); // 设置总数
        return resultPage;
    }

    /**
     * pc接口
     *
     * @return
     */
    public Page<SensorAlarm> getMessages(MonitorNoticePageParam monitorNoticePageParam) {
        MessagePageParam messagePageParam = BeanUtil.copyProperties(monitorNoticePageParam, MessagePageParam.class);
        return getSensorAlarmPage(messagePageParam);
    }

    @Override
    public long countAlarms(String startDate, String endDate, String sensorCode, String sensorRoute,SensorAlarmType type) {
        if(Objects.isNull(type)){
            type=SensorAlarmType.DATA_ALARM;
        }
        QueryWrapper<SensorAlarm> queryWrapper = new QueryWrapper<>();
        // 获取当前登录用户ID
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
        // 创建组织ID条件
        queryWrapper.lambda().eq(SensorAlarm::getCreateOrg, orgId);
        queryWrapper.lambda().eq(SensorAlarm::getType, type.getDeviceCode());
        // 根据传入的 sensorCode 和 sensorRoute 条件查询
        if (sensorCode != null) {
            queryWrapper.lambda().eq(SensorAlarm::getSensorCode, sensorCode);
        }
        if (sensorRoute != null) {
            queryWrapper.lambda().eq(SensorAlarm::getSensorRoute, sensorRoute);
        }
        // 时间范围查询，确保传入的日期格式正确
        if (startDate != null && endDate != null) {
            queryWrapper.lambda().between(SensorAlarm::getCreateTime, startDate, endDate);
        }
        // 返回符合条件的记录数量
        return this.count(queryWrapper);
    }

    public Page<SensorAlarm> getSensorAlarmPage(MessagePageParam messagePageParam) {
        // 创建查询条件
        QueryWrapper<SensorAlarm> queryWrapper = new QueryWrapper<SensorAlarm>().checkSqlInjection();
        // 获取当前登录用户ID
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
        // 查询创建用户为当前用户的记录
        queryWrapper.lambda().eq(SensorAlarm::getCreateOrg, orgId);
        final String type = messagePageParam.getType();
        if(StrUtil.isNotBlank(type) && type.trim().equalsIgnoreCase("system")){
            queryWrapper.lambda().eq(SensorAlarm::getType, SensorAlarmType.SENSOR_OFFLINE.getDeviceCode());
        }else{
            queryWrapper.lambda().eq(SensorAlarm::getType, SensorAlarmType.DATA_ALARM.getDeviceCode());
        }
        if(StrUtil.isNotBlank(messagePageParam.getSensorCode())){
            queryWrapper.lambda().eq(SensorAlarm::getSensorCode, messagePageParam.getSensorCode());
        }
        if(Objects.nonNull(messagePageParam.getSensorRoute())){
            queryWrapper.lambda().eq(SensorAlarm::getSensorRoute, messagePageParam.getSensorRoute());
        }
        // 如果有关键词，进行模糊查询或者设备名等字段的精确查询
        if (ObjectUtil.isNotEmpty(messagePageParam.getKeyword())) {
            queryWrapper.lambda().and(q -> q.like(SensorAlarm::getMessage, messagePageParam.getKeyword()).or().like(SensorAlarm::getDeviceName, messagePageParam.getKeyword()));
        }
        // 时间查询
        if (StrUtil.isNotBlank(messagePageParam.getStartTime())) {
            queryWrapper.lambda().ge(SensorAlarm::getCreateTime, DateUtil.parse(messagePageParam.getStartTime(), "yyyy-MM-dd HH:mm:ss"));  // greater than or equal to start time
        }
        if (StrUtil.isNotBlank(messagePageParam.getStartTime())) {
            queryWrapper.lambda().le(SensorAlarm::getCreateTime, DateUtil.parse(messagePageParam.getEndTime(), "yyyy-MM-dd HH:mm:ss"));  // greater than or equal to start time
        }
        // 按创建时间降序排序
        queryWrapper.lambda().orderByDesc(SensorAlarm::getCreateTime);
        // 执行查询，传入分页对象
        Page<SensorAlarm> sensorAlarmPage = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        return sensorAlarmPage;
    }

    private Message convertToMessage(SensorAlarm sensorAlarm) {
        Message message = new Message();
        message.setType(MessageType.ALERT);
        // 假设Message和SensorAlarm有一些相似字段，进行转换
        message.setId(sensorAlarm.getId());
        message.setContent(sensorAlarm.getMessage());
        message.setRead(false);
        message.setTitle(sensorAlarm.getDeviceName() + ":" + sensorAlarm.getAlarmType());
        message.setCreatedDate(sensorAlarm.getCreateTime());
        return message;
    }
}

