package com.qmth.teachcloud.task.job.service.impl;

import com.qmth.boot.redis.uid.RedisMachineService;
import com.qmth.distributed.print.business.service.BasicMessageService;
import com.qmth.distributed.print.business.service.ExamTaskService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.bean.dto.MqDto;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.util.RedisUtil;
import com.qmth.teachcloud.task.job.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description: job service impl
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/31
 */
@Service
public class JobServiceImpl implements JobService {
    private final static Logger log = LoggerFactory.getLogger(JobServiceImpl.class);

    @Resource
    PrintCommonService printCommonService;

    @Resource
    ExamTaskService examTaskService;

    @Resource
    BasicMessageService basicMessageService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    RedisMachineService redisMachineService;

    /**
     * 重新生成pdf失败任务
     *
     * @throws IOException
     */
    @Override
    public void resetCreatePdfTask() throws IOException {
        printCommonService.resetCreatePdfTask();
    }

    @Override
    public void sendSmsExpireTask() {
        examTaskService.sendSmsExpireTask();
    }

    @Override
    public void sendSmsOverdueTask() {
        examTaskService.sendSmsOverdueTask();
    }

    @Override
    public void resendSmsTask() {
        basicMessageService.resendSmsTask();
    }

    @Override
    public void machineHeart() {
        redisUtil.set(SystemConstant.TASK_MACHINE_ID + redisMachineService.getMachineId(), redisMachineService.getMachineId(), 30, TimeUnit.SECONDS);
    }

    /**
     * 组装job
     *
     * @param redisKey
     */
    @Override
    public void assembleJob(String redisKey) {
        Long size = redisUtil.getHashSize(redisKey);
        if (Objects.nonNull(size) && size.longValue() > 0) {
            log.info("redisKey:{}缓冲区的消息数为:{}", redisKey, size);
            Map map = redisUtil.getHashEntries(redisKey);
            map.forEach((k, v) -> {
                MqDto mqDto = (MqDto) v;
                redisUtil.sendMessage(mqDto.getTopic(), mqDto);
            });
        }
    }
}
