<template>
  <div class="card-container">
    <el-card class="card-heard">
    <el-form :inline="true" ref="queryForm">
      <el-form-item label="任务描述">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入定时任务描述"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="文件全名">
        <el-input
          v-model="queryParams.jobClassName"
          placeholder="请输入文件全名"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    </el-card>
    <el-card class="card-body">
      <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:quartz:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:quartz:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:quartz:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-table
      v-loading="loading"
      :data="quartzList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="编号" type="index" align="center" />
      <el-table-column label="任务描述" align="center" prop="description" show-overflow-tooltip />
      <el-table-column label="文件全名" align="center" prop="jobClassName" />
      <el-table-column label="Cron表达式" align="center" prop="cronExpression" />
      <el-table-column label="启用状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.triggerState"
            active-value="1"
            inactive-value="0"
            @change="handleStateChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="triggerStateName">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.triggerStateName === '等待'"> 等待</el-tag>
          <el-tag v-if="scope.row.triggerStateName === '正常'" type="success"> 正常</el-tag>
          <el-tag v-if="scope.row.triggerStateName === '暂停'" type="info"> 暂停</el-tag>
          <el-tag v-if="scope.row.triggerStateName === '阻塞'" type="warning"> 阻塞</el-tag>
          <el-tag v-if="scope.row.triggerStateName === '错误'" type="danger"> 错误</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上次运行时间" align="center" prop="prevFireTime" />
      <el-table-column label="下次运行时间" align="center" prop="nextFireTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="startOnce(scope.row)"
            v-hasPermi="['system:quartz:startOnce']"
            >立即执行
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:quartz:edit']"
            >修改
            </el-button>
          <el-button
            v-if="scope.row.userId !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:quartz:remove']"
            >删除
            </el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-card>
    <!-- 添加或修改 定时任务 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务描述" prop="description">
              <el-input
                v-model="form.description"
                placeholder="请输入任务描述"
                maxlength="250"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件路径" prop="jobClassName">
              <el-input
                v-model="form.jobClassName"
                placeholder="请输入文件路径"
                maxlength="250"
                :disabled="isDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="表达式" prop="cronExpression">
              <el-input
                v-model="form.cronExpression"
                placeholder="请输入Cron表达式"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryQuartz,
  getQuartz,
  insert,
  update,
  delQuartz,
  startOnce,
  pauseJob,
  resumeJob,
} from "@/api/system/quartz";

export default {
  name: "Quartz",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      jobClassNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 列表List
      quartzList: [],
      // 新增编辑控制
      open: false,
      // 新增编辑弹框标题
      title: "",
      // 判断是新增还是编辑
      isInsert: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobClassName: undefined,
        description: undefined,
      },
      // 表单参数
      form: {},
      // 是否禁止修改
      isDisabled: false,
      // 表单校验
      rules: {
        description: [
          { required: true, message: "任务描述不能为空", trigger: "blur" },
        ],
        jobClassName: [
          { required: true, message: "文件路径不能为空", trigger: "blur" },
        ],
        cronExpression: [
          { required: true, message: "请输入Cron表达式", trigger: "blur" },
          // {
          //   pattern:
          //     "^\\s*($|#|\\w+\\s*=|(\\?|\\*|(?:[0-5]?\\d)(?:(?:-|\\/|\\,)(?:[0-5]?\\d))?(?:,(?:[0-5]?\\d)(?:(?:-|\\/|\\,)(?:[0-5]?\\d))?)*)\\s+(\\?|\\*|(?:[0-5]?\\d)(?:(?:-|\\/|\\,)(?:[0-5]?\\d))?(?:,(?:[0-5]?\\d)(?:(?:-|\\/|\\,)(?:[0-5]?\\d))?)*)\\s+(\\?|\\*|(?:[01]?\\d|2[0-3])(?:(?:-|\\/|\\,)(?:[01]?\\d|2[0-3]))?(?:,(?:[01]?\\d|2[0-3])(?:(?:-|\\/|\\,)(?:[01]?\\d|2[0-3]))?)*)\\s+(\\?|\\*|(?:0?[1-9]|[12]\\d|3[01])(?:(?:-|\\/|\\,)(?:0?[1-9]|[12]\\d|3[01]))?(?:,(?:0?[1-9]|[12]\\d|3[01])(?:(?:-|\\/|\\,)(?:0?[1-9]|[12]\\d|3[01]))?)*)\\s+(\\?|\\*|(?:[1-9]|1[012])(?:(?:-|\\/|\\,)(?:[1-9]|1[012]))?(?:L|W)?(?:,(?:[1-9]|1[012])(?:(?:-|\\/|\\,)(?:[1-9]|1[012]))?(?:L|W)?)*|\\?|\\*|(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?(?:,(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)*)\\s+(\\?|\\*|(?:[0-6])(?:(?:-|\\/|\\,|#)(?:[0-6]))?(?:L)?(?:,(?:[0-6])(?:(?:-|\\/|\\,|#)(?:[0-6]))?(?:L)?)*|\\?|\\*|(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?(?:,(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?)*)(|\\s)+(\\?|\\*|(?:|\\d{4})(?:(?:-|\\/|\\,)(?:|\\d{4}))?(?:,(?:|\\d{4})(?:(?:-|\\/|\\,)(?:|\\d{4}))?)*))$",
          //   message: "请输入正确的Cron表达式",
          // },
        ],
      },
    };
  },
  created() {
    this.query();
  },
  methods: {
    /** 查询 Quartz定时任务 列表 */
    query() {
      this.loading = true;
      queryQuartz(this.queryParams)
        .then((response) => {
          console.log(response);
          this.quartzList = response.records;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.query();
    },
    /** 重置查询操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        jobClassName: undefined,
        description: undefined,
      };
      this.resetForm("queryForm");
      this.query();
    },
    // 表单重置
    reset() {
      this.form = {
        description: undefined,
        jobClassName: undefined,
        cronExpression: undefined,
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.jobClassNames = selection.map((item) => item.jobClassName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.isInsert = "1";
      this.title = "添加定时任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const jobClassName = row.jobClassName || this.jobClassNames;
      this.reset();
      getQuartz(jobClassName).then((response) => {
        this.form = response.result;
        this.open = true;
        this.isInsert = "2";
        this.isDisabled = true;
        this.title = "修改定时任务";
      });
    },
    /** 立即执行一次按钮操作 */
    startOnce(row) {
      this.$confirm(
        '是否确认立即执行一次任务描述为"' + row.description + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return startOnce(row.jobClassName);
        })
        .then(() => {
          this.msgSuccess("执行成功");
        })
        .catch(function () {});
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.isInsert === "1") {
            insert(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.isInsert = "";
                this.isDisabled = false;
                this.query();
              } else {
                this.msgSuccess(response.msg);
              }
            });
          } else if (this.isInsert === "2") {
            update(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.isInsert = "";
                this.isDisabled = false;
                this.query();
              } else {
                this.msgSuccess(response.msg);
              }
            });
          }
        }
      });
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false;
      this.isInsert = "";
      this.isDisabled = false;
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobClassName = row.jobClassName || this.jobClassNames;
      this.$confirm(
        '是否确认删除任务描述为"' + row.description + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delQuartz(jobClassName);
        })
        .then(() => {
          this.query();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 修改定时任务状态按钮操作 */
    handleStateChange(row) {
      console.log(row);
      let text = row.triggerState === "1" ? "恢复" : "暂停";
      this.$confirm(
        '确认要"' + text + '""' + row.description + '"定时任务吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          if (row.triggerState === "1") {
            return resumeJob(row.jobClassName);
          } else if (row.triggerState === "0") {
            return pauseJob(row.jobClassName);
          }
        })
        .then(() => {
          this.query();
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.triggerState = row.triggerState === "0" ? "1" : "0";
        });
    },
  },
};
</script>
