package com.wms_main.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms_main.dao.ITAppJobsService;
import com.wms_main.mapper.AppJobsMapper;
import com.wms_main.model.po.TAppJobs;
import com.wms_main.quartz.config.JobBean;
import com.wms_main.repository.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * Jobs服务实现
 */
@Service
@Slf4j
public class TAppJobsServiceImpl extends ServiceImpl<AppJobsMapper, TAppJobs> implements ITAppJobsService {
    /**
     * 实现
     * @param jobQuery 查询条件
     * @return 结果
     */
    @Override
    public List<JobBean> getJobs(TAppJobs jobQuery) {
        List<TAppJobs> jobs;
        if (jobQuery == null) {
            // 无查询条件，视为查询所有。
            jobs = list();
        } else {
            LambdaQueryWrapper<TAppJobs> jobsQueryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotEmpty(jobQuery.getJobName())) {
                // jobName
                jobsQueryWrapper.eq(TAppJobs::getJobName, jobQuery.getJobName());
            }
            if (StringUtils.isNotEmpty(jobQuery.getJobClass())) {
                // JobClass
                jobsQueryWrapper.eq(TAppJobs::getJobClass, jobQuery.getJobClass());
            }
            if (jobQuery.getJobStatus() != null) {
                // JobStatus
                jobsQueryWrapper.eq(TAppJobs::getJobStatus, jobQuery.getJobStatus());
            }
            jobs = list(jobsQueryWrapper);
        }
        if (jobs != null && !jobs.isEmpty()) {
            List<JobBean> jobsBeans = new java.util.ArrayList<>();
            for (TAppJobs job : jobs) {
                try {
                    Class<?> jobClass = Class.forName(job.getJobClass());
                    if (Job.class.isAssignableFrom(jobClass)) {
                        jobsBeans.add(new JobBean(job.getJobName(), jobClass.asSubclass(Job.class), job.getCronExpression(), job.getTimer(), job.getTimerType(), job.getJobStatus()));
                    } else {
                        log.error("类{}不是Job子类。", job.getJobClass());
                    }
                } catch (ClassNotFoundException e) {
                    log.error("类未找到：{}。", job.getJobClass());
                } catch (ClassCastException e) {
                    log.error("类型转换错误：{}。", job.getJobClass());
                }
            }
            return jobsBeans;
        }
        return Collections.emptyList();
    }
}
