package com.dxhy.core.job.thread;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.core.job.dao.ScheduleJobDao;
import com.dxhy.core.job.entity.ScheduleJobEntity;
import com.dxhy.core.job.service.ScheduleJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.util.List;
import java.util.Map;

@Slf4j
public class DoScheJobByBeanNameMethodHandle implements Runnable {

    private ScheduleJobDao scheduleJobDao;

    private List<Map<String, String>> jobNames ;

    private ScheduleJobService scheduleJobService;

    public DoScheJobByBeanNameMethodHandle(ScheduleJobDao scheduleJobDao, ScheduleJobService scheduleJobService, List<Map<String, String>> jobNames) {
        this.scheduleJobDao = scheduleJobDao;
        this.scheduleJobService = scheduleJobService;
        this.jobNames = jobNames;
    }

    @Override
    public void run() {
        try {
            List<Map<String, String>> jobNames = this.jobNames;
            for (int i = 0; i < jobNames.size(); i++) {
                Map<String, String> stringStringMap = jobNames.get(i);
                String beanName = stringStringMap.get("beanName");
                String methodName = stringStringMap.get("methodName");
                ScheduleJobEntity scheduleJobEntity = scheduleJobDao.selectOne(new LambdaQueryWrapper<ScheduleJobEntity>()
                        .eq(ScheduleJobEntity::getBeanName, beanName)
                        .eq(ScheduleJobEntity::getMethodName, methodName)
                );
                if(ObjectUtils.isNotEmpty(scheduleJobEntity)){
                    log.info("执行定时任务:{}",scheduleJobEntity.getRemark());
                    scheduleJobService.run(scheduleJobEntity.getJobId());
                    if(i+1<jobNames.size()){
                        log.info("{}调用完成，如有队列，等待15秒执行下一个",scheduleJobEntity.getRemark());
                        Thread.sleep(15000);
                    }
                }
            }
        } catch (Exception e) {
            log.error("调任务队列出错:{}",e);
        }
    }
}
