package com.yida.data.attendance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.attendance.mapper.EduUserStrategyMapper;
import com.yida.data.attendance.service.EduAttendanceDeviceService;
import com.yida.data.attendance.service.EduUserStrategyService;
import com.yida.data.attendance.utils.MqttUtil;
import com.yida.data.common.core.entity.attendance.EduAttendanceDevice;
import com.yida.data.common.core.entity.attendance.EduUserStrategy;
import com.yida.data.common.core.entity.attendance.enums.DeviceStateEnum;
import com.yida.data.common.core.entity.constant.hq.HaiqingConstant;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.enums.DeviceType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 人员策略信息 Service实现
 *
 * @author ZYJ
 * @date 2023-11-07 11:40:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduUserStrategyServiceImpl extends ServiceImpl
        <EduUserStrategyMapper, EduUserStrategy> implements EduUserStrategyService {

    private final MqttUtil mqttUtil;
    private final EduAttendanceDeviceService eduAttendanceDeviceService;

    @Override
    public void checkOverTimeUserStrategy() {
        // 查询超时请假策略
        List<EduUserStrategy> list = list(Wrappers.lambdaQuery(new EduUserStrategy())
                .lt(EduUserStrategy::getEndTime, LocalDateTime.now()));
        if (CollUtil.isNotEmpty(list)) {
            // 分组
            Map<Long, List<EduUserStrategy>> userStrategyMap = list.stream()
                    .collect(Collectors.groupingBy(EduUserStrategy::getDeptId));
            userStrategyMap.forEach((deptId, userStrategy) -> {
                // 设置删除策略信息
                JSONObject params = JSONUtil.createObj()
                        .set("operator", HaiqingConstant.DEL_ACCESS_STRATEGY)
                        .set("messageId", StrUtil.uuid().replace("-", ""));
                // 策略id集合
                JSONArray array = JSONUtil.createArray();
                list.forEach(strategy -> array.add(strategy.getStrategyId()));

                // 查询学校校门的设备
                List<EduAttendanceDevice> deviceList = eduAttendanceDeviceService.list(Wrappers.lambdaQuery(new EduAttendanceDevice())
                        .eq(EduAttendanceDevice::getSchoolId, deptId)
                        .eq(EduAttendanceDevice::getDeviceType, DeviceType.HAIQING.getValue())
                        .eq(EduAttendanceDevice::getState, DeviceStateEnum.ONLINE_STATUS.getStatus())
                        // 校门类型
                        .eq(EduAttendanceDevice::getType, 0)
                );

                if (CollUtil.isNotEmpty(deviceList) && CollUtil.isNotEmpty(array)) {
                    params.set("info", JSONUtil.createObj().set("strategyID", array));
                    for (EduAttendanceDevice device : deviceList) {
                        log.info("定时任务推送的删除策略消息=================sn: {}, params: {}", device.getSn(), params);
                        // 删除策略消息
                        mqttUtil.publish(params.toString(), "mqtt/face/" + device.getSn());
                    }
                }
            });

            remove(Wrappers.lambdaQuery(new EduUserStrategy()).in(EduUserStrategy::getStrategyId, list.stream()
                    .map(EduUserStrategy::getStrategyId).collect(Collectors.toList())));
        }
    }
}
