package com.skr.mdm.quartz.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.skr.mdm.constant.JobConstant;
import com.skr.mdm.dao.MdmAppPushUserDao;
import com.skr.mdm.enums.StrategyEquipmentStateEnum;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.bean.bo.QuartzJobBO;
import com.skr.mdm.entity.MdmAppPushUserDO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

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

/**
 * @author nfq
 * @date 2022-12-26 11:53
 */
@Slf4j
@DisallowConcurrentExecution
public class AppPushJob extends QuartzJobBean {

    @Autowired
    private IssuedUserHandler issuedUserHandler;
    @Autowired
    private MdmAppPushUserDao appPushUserDao;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        String data = jobDataMap.getString(JobConstant.JOB_INFO_IN_JOB_DATA_MAP_KEY);
        QuartzJobBO quartzJobBO = JSONUtil.toBean(data, QuartzJobBO.class);
        log.info("quartz应用定时推送 时间：{} 数据：{}", DateUtil.date(), data);
        // 获取当前时间需要下发的设备
        List<Integer> equipmentIdList = new LambdaQueryChainWrapper<>(appPushUserDao)
                .eq(MdmAppPushUserDO::getAppPushId, quartzJobBO.getId())
                .eq(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .eq(MdmAppPushUserDO::getPushTime, quartzJobBO.getExecuteTime())
                .list()
                .stream()
                .map(MdmAppPushUserDO::getEquipmentId)
                .collect(Collectors.toList());
        issuedUserHandler.issuedUser(equipmentIdList, quartzJobBO.getCompanyId(), quartzJobBO.getCmd(), quartzJobBO.getMessage());
        // 更新下发状态
        new LambdaUpdateChainWrapper<>(appPushUserDao)
                .set(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
                .eq(MdmAppPushUserDO::getAppPushId, quartzJobBO.getId())
                .eq(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .eq(MdmAppPushUserDO::getPushTime, quartzJobBO.getExecuteTime())
                .update();
    }
}
