package org.jeecg.modules.dataVue.controller;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.dataVue.service.IMasterService;
import org.jeecg.modules.dataVue.service.ITaskService;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/dataVue/task")
public class TaskUseController {
    @Autowired
    private IMasterService iMasterService;
    @Autowired
    ITaskService iTaskService;
    @Autowired
    private Scheduler scheduler;

    private static final String JOB_GROUP = "JTZNYJ_WELLHISTORY";

    @GetMapping("/startWarnHistory")
    public Result<?> startWarnHistory(String jh, String ltd) {
        QuartzJob quartzJob = new QuartzJob();
        quartzJob.setId("aaa");
        quartzJob.setCreateTime(new Date());
        quartzJob.setJobClassName("org.jeecg.modules.dataVue.task.WarnHistoryJob");
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        quartzJob.setParameter(jh + "," + ltd + "," + user.getId());

        String identity = JOB_GROUP + ";" + jh + ';' + quartzJob.getJobClassName();
        Boolean taskRunning = false;
        try {
            taskRunning = scheduler.checkExists(new JobKey(identity, null));
            JobDetail jobDetail = scheduler.getJobDetail(new JobKey(identity, null));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        if(taskRunning){
            return Result.ok("已开始");
        }


        if (quartzJob == null) {
            return Result.error("未找到对应实体");
        }
        try {
            execute(quartzJob, identity);
        } catch (Exception e) {
            return Result.error("执行失败!");
        }
        return Result.ok("已开始");
    }

    @GetMapping("/checkHistoryReady")
    public Result<?> checkHistoryReady(String jh) {
        String sql = " select count(*) from b_task where id = '%s' and status = 1";
        sql = String.format(sql, jh);
        int i = iMasterService.querySqlCount(sql, null);
        if (i > 0) {
            return Result.ok("ready");
        } else {
            return Result.ok("");
        }
    }

    @GetMapping("/recheckHistoryReady")
    public Result<?> recheckHistoryReady(String jh) {
        String sql = " select * from b_task where id = '%s' and status = 0";
        sql = String.format(sql, jh);
        List<Map<String, Object>> i = iMasterService.querySql(sql, null);
        if (i.size() > 0) {
            return Result.ok(i.get(0).get("DESCRIPTION"));
        } else {
            sql = " select count(*) from b_task where id = '%s' and status = 1";
            sql = String.format(sql, jh);
            int i2 = iMasterService.querySqlCount(sql, null);
            if (i2 > 0)
                return Result.ok("ready");
            else
                return Result.ok("");
        }
    }

    public Result<?> startWarnJh() {

        return Result.ok("已开始");
    }


    public void execute(QuartzJob quartzJob, String identity) throws Exception {
        String jobName = quartzJob.getJobClassName().trim();
        Date startDate = new Date();
        String ymd = DateUtils.date2Str(startDate, DateUtils.yyyymmddhhmmss.get());
//        String identity = jobName + ymd;
        //3秒后执行 只执行一次
        // update-begin--author:sunjianlei ---- date:20210511--- for：定时任务立即执行，延迟3秒改成0.1秒-------
        startDate.setTime(startDate.getTime() + 100L);
        // update-end--author:sunjianlei ---- date:20210511--- for：定时任务立即执行，延迟3秒改成0.1秒-------
        // 定义一个Trigger
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(identity, JOB_GROUP)
                .startAt(startDate)
                .build();
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(getClass(jobName).getClass())
                .withIdentity(identity)
                .usingJobData("parameter", quartzJob.getParameter())
                .build();
        // 将trigger和 jobDetail 加入这个调度
        scheduler.scheduleJob(jobDetail, trigger);
        // 启动scheduler
        scheduler.start();
    }

    private static Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job) class1.newInstance();
    }
}
