<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增</el-button>
        <el-button type="danger"
                   size="mini"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删除
        </el-button>
        <el-button
            type="info"
            plain
            icon="el-icon-s-operation"
            size="mini"
            @click="handleJobLog"
        >日志</el-button>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
        >任务详细</el-button>
        <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
        >修改</el-button>

        <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
          <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="handleRun" icon="el-icon-caret-right"
                              >执行一次</el-dropdown-item>
            <el-dropdown-item command="handleJobLog" icon="el-icon-s-operation"
                              >调度日志</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>

    </avue-crud>


    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择任务分组">
                <el-option
                    v-for="dict in sys_job_group"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="invokeTarget">
              <span slot="label">
                调用方法
                <el-tooltip placement="top">
                  <div slot="content">
                    Bean调用示例：ryTask.ryParams('ry')
                    <br />Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                    <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="form.invokeTarget" placeholder="请输入调用目标字符串" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式">
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy" size="small">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent" size="small">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in sys_job_status"
                    :key="dict.value"
                    :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </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>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

    <!-- 任务日志详细 -->
    <el-dialog title="任务详细" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：">{{ form.id }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
            <el-form-item label="创建时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{ form.nextValidTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">
              <div v-if="form.status == 0">正常</div>
              <div v-else-if="form.status == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="form.concurrent == 0">允许</div>
              <div v-else-if="form.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="form.misfirePolicy == 0">默认策略</div>
              <div v-else-if="form.misfirePolicy == 1">立即执行</div>
              <div v-else-if="form.misfirePolicy == 2">执行一次</div>
              <div v-else-if="form.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>

  </basic-container>

</template>

<script>
  import {getList, getDetail, add, update, remove, runJob} from "@/api/quartz/job";
  import {mapGetters} from "vuex";
  import Crontab from '@/components/Crontab'

  var jobState = [{
    value: '0',
    label: '正常'
  },{
    value: '1',
    label: '暂停'
  }];

  export default {
    components: { Crontab },
    data() {
      return {
        sys_job_group: [{
          value: 'DEFAULT',
          label: '默认'
        },{
          value: 'SYSTEM',
          label: '系统'
        }],
        sys_job_status: [{
          value: '0',
          label: '正常'
        },{
          value: '1',
          label: '暂停'
        }],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示详细弹出层
        openView: false,
        openCron: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "任务名称",
              prop: "jobName",
              search: true,
              rules: [{
                required: true,
                message: "请输入任务名称",
                trigger: "blur"
              }]
            },
            {
              label: "任务组名",
              search: true,
              prop: "jobGroup",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=task_group_name",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "调用目标字符串",
              prop: "invokeTarget",
              rules: [{
                required: true,
                message: "请输入调用目标字符串",
                trigger: "blur"
              }]
            },
            {
              label: "cron执行表达式",
              prop: "cronExpression",
              rules: [{
                required: true,
                message: "请输入cron执行表达式",
                trigger: "blur"
              }]
            },
            {
              label: "计划执行错误策略（1立即执行 2执行一次 3放弃执行）",
              prop: "misfirePolicy",
              hide: true,
              rules: [{
                required: true,
                message: "请输入计划执行错误策略（1立即执行 2执行一次 3放弃执行）",
                trigger: "blur"
              }]
            },
            {
              label: "是否并发执行（0允许 1禁止）",
              prop: "concurrent",
              hide: true,
              rules: [{
                required: true,
                message: "请输入是否并发执行（0允许 1禁止）",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "status",
              search: true,
              rules: [{
                required: true,
                message: "请输入状态",
                trigger: "blur"
              }],
              type: "select",
              dicData: jobState,
              dataType: "number",
            },
            {
              label: "备注信息",
              prop: "remark",
              hide: true,
              rules: [{
                required: true,
                message: "请输入备注信息",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.job_add, false),
          viewBtn: this.vaildData(this.permission.job_view, false),
          delBtn: this.vaildData(this.permission.job_delete, false),
          editBtn: this.vaildData(this.permission.job_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加任务";
      },
      reset() {
        this.form = {
          jobId: undefined,
          jobName: undefined,
          jobGroup: undefined,
          invokeTarget: undefined,
          cronExpression: undefined,
          misfirePolicy: 1,
          concurrent: 1,
          status: "0"
        };
      },
      /** cron表达式按钮操作 */
      handleShowCron() {
        this.expression = this.form.cronExpression;
        this.openCron = true;
      },
      /** 确定后回传值 */
      crontabFill(value) {
        this.form.cronExpression = value;
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              update(this.form).then(response => {
                this.$message({
                  type: "success",
                  message: "修改成功!"
                });
                this.open = false;
                this.onLoad(this.page);
              });
            } else {
              add(this.form).then(response => {
                this.$message({
                  type: "success",
                  message: "新增成功!"
                });
                this.open = false;
                this.onLoad(this.page);
              });
            }
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const jobId = row.id;
        getDetail(jobId).then(response => {
          this.form = response.data.data;
          this.open = true;
          this.title = "修改任务";
        });
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleRun":
            this.handleRun(row);
            break;
          case "handleView":
            this.handleView(row);
            break;
          case "handleJobLog":
            this.handleJobLog(row);
            break;
          default:
            break;
        }
      },
      /* 立即执行一次 */
      handleRun(row) {
        this.$confirm('确认要立即执行一次"' + row.jobName + '"任务吗？').then(function() {
          return runJob(row);
        }).then(() => {
          this.$message({
            type: "success",
            message: "执行成功!"
          });
        }).catch(() => {});
      },
      /** 任务详细信息 */
      handleView(row) {
        getDetail(row.id).then(response => {
          this.form = response.data.data;
          this.openView = true;
        });
      },
      /** 任务日志列表查询 */
      handleJobLog(row) {
        console.log(row)
        const jobId = row.id || 0;
        // this.$router.push('/quartz/joblog/' + jobId);
        this.$router.push({
          path: '/quartz/joblog/',
          query: {
            jobId: jobId,
            jobName: row.jobName,
            jobGroup: row.jobGroup
          }
        })

        // this.$router.push({
        //   path: '/quartz/joblog/',
        //   query: {
        //     bartenderId: JSON.stringify(jobId),
        //   }
        // })
      },
    }
  };
</script>

<style>
</style>
