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.ContentInformUserDao;
import com.skr.mdm.enums.StrategyEquipmentStateEnum;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.bean.bo.QuartzJobBO;
import com.skr.mdm.entity.ContentInformUserDO;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nfq
 * @date 2021/4/23 18:36
 */
@Slf4j
@DisallowConcurrentExecution
public class InformJob extends QuartzJobBean {

    @Autowired
    private IssuedUserHandler issuedUserHandler;
    @Autowired
    private ContentInformUserDao contentInformUserDao;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        String data = jobDataMap.getString(JobConstant.JOB_INFO_IN_JOB_DATA_MAP_KEY);
        log.info("quartz通知定时执行 时间：{} 数据：{}", DateUtil.date(), data);
        QuartzJobBO quartzJobBO = JSONUtil.toBean(data, QuartzJobBO.class);
        // 获取待下发的设备
        List<Integer> equipmentIdList = new LambdaQueryChainWrapper<>(contentInformUserDao)
                .eq(ContentInformUserDO::getInformId, quartzJobBO.getId())
                .eq(ContentInformUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .list()
                .stream()
                .map(ContentInformUserDO::getEquipmentId)
                .collect(Collectors.toList());
        issuedUserHandler.issuedUser(equipmentIdList, quartzJobBO.getCompanyId(), quartzJobBO.getCmd(), quartzJobBO.getMessage());
        // 更新下发状态
        new LambdaUpdateChainWrapper<>(contentInformUserDao)
                .set(ContentInformUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
                .set(ContentInformUserDO::getIssuedTime, new Date())
                .eq(ContentInformUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .eq(ContentInformUserDO::getInformId, quartzJobBO.getId())
                .update();
    }
}
