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.ContentDocumentUserDao;
import com.skr.mdm.enums.StrategyEquipmentStateEnum;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.bean.bo.QuartzJobBO;
import com.skr.mdm.entity.ContentDocumentUserDO;
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 2022-12-26 11:53
 */
@Slf4j
@DisallowConcurrentExecution
public class ContentJob extends QuartzJobBean {

	@Autowired
	private IssuedUserHandler issuedUserHandler;
	@Autowired
	private ContentDocumentUserDao contentDocumentUserDao;

	@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<>(contentDocumentUserDao)
				.eq(ContentDocumentUserDO::getFileId, quartzJobBO.getId())
				.eq(ContentDocumentUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
				.eq(ContentDocumentUserDO::getSendPushTime, quartzJobBO.getExecuteTime())
				.list()
				.stream()
				.map(ContentDocumentUserDO::getEquipmentId)
				.collect(Collectors.toList());
		issuedUserHandler.issuedUser(equipmentIdList, quartzJobBO.getCompanyId(), quartzJobBO.getCmd(), quartzJobBO.getMessage());
		// 更新下发状态
		new LambdaUpdateChainWrapper<>(contentDocumentUserDao)
				.set(ContentDocumentUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
				.set(ContentDocumentUserDO::getIssuedTime, new Date())
				.eq(ContentDocumentUserDO::getFileId, quartzJobBO.getId())
				.eq(ContentDocumentUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
				.eq(ContentDocumentUserDO::getSendPushTime, quartzJobBO.getExecuteTime())
				.update();
	}
}
