<template>
  <div>
    <div class="nav-title">任务管理</div>
    <div class="search">
      <el-form
        class="search-form"
        :model="form"
        ref="form"
        :inline="true"
        size="mini"
      >
        <el-form-item label="执行器：">
          <el-select v-model="form.jobGroup" placeholder="请选择">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="form.triggerStatus" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述：">
          <el-input
            v-model="form.jobDesc"
            placeholder="请输入任务描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="JobHandler：">
          <el-input
            v-model="form.executorHandler"
            placeholder="请输入JobHandler"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人：">
          <el-input v-model="form.author" placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="toSearch">查询</el-button>
          <el-button type="primary" @click="handleEdit">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{ background: '#EAF1FE', color: '#666666' }"
      >
        <el-table-column prop="id" label="任务ID" align="center" />
        <el-table-column prop="jobDesc" label="任务描述" align="center" />
        <el-table-column prop="scheduleConf" label="调度类型" align="center" />
        <el-table-column prop="alarmType" label="运行模式" align="center">
          <template slot-scope="scope">
            {{ scope.row.glueType }}:{{ scope.row.executorHandler }}
          </template>
        </el-table-column>
        <el-table-column prop="author" label="负责人" align="center" />
        <el-table-column prop="triggerStatus" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.triggerStatus === 1 ? 'success' : 'warning'"
              >{{ scope.row.triggerStatus === 1 ? "运行中" : "已停止" }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ name: 'a', data: scope.row }"
                  >执行一次</el-dropdown-item
                >
                <el-dropdown-item>查询日志</el-dropdown-item>
                <el-dropdown-item :command="{ name: 'c', data: scope.row }"
                  >注册节点</el-dropdown-item
                >
                <el-dropdown-item :command="{ name: 'd', data: scope.row }"
                  >下次执行时间</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  v-if="scope.row.triggerStatus == 0"
                  :command="{ name: 'e', data: scope.row }"
                  >启动</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  v-if="scope.row.triggerStatus == 1"
                  :command="{ name: 'e', data: scope.row }"
                  >停止</el-dropdown-item
                >
                <el-dropdown-item>编辑</el-dropdown-item>
                <el-dropdown-item :command="{ name: 'g', data: scope.row }"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item>复制</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :limit="params.size"
        :page="params.current"
        :total="total"
        class="pagination"
        @pagination="handlePageChange"
      />
    </div>
    <el-dialog
      title="执行一次"
      :visible.sync="aDialogVisible"
      width="600px"
      @close="handleClose"
      center
    >
      <el-form :model="manageFrom" ref="form" size="mini">
        <el-form-item label="任务参数：">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入任务参数"
            v-model="manageFrom.executorParam"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="机器地址：">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入本次执行的机器地址，为空则从执行器获取"
            v-model="manageFrom.addressList"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTriggerJobinfo"
            >确定</el-button
          >
          <el-button @click="handleClose()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="注册节点"
      :visible.sync="cDialogVisible"
      width="600px"
      @close="handleClose"
      center
    >
      <div
        style="margin: 8px"
        v-for="(item, index) in showData && showData.registryList"
        :key="index"
      >
        {{ index + 1 }}. {{ item }}
      </div>
    </el-dialog>
    <el-dialog
      title="任务"
      :visible.sync="addDialogVisible"
      width="800px"
      @close="handleClose"
      center
    >
      <el-form class="add-form" :inline="true" :model="addFrom" ref="form">
        <div class="mini-title">基础配置</div>
        <el-form-item label="执行器" class="both">
          <el-select v-model="addFrom.jobGroup" placeholder="请选择">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" class="both">
          <el-input placeholder="请输入任务描述" v-model="addFrom.jobDesc">
          </el-input>
        </el-form-item>
        <el-form-item label="负责人" class="both">
          <el-input placeholder="请输入负责人" v-model="addFrom.author">
          </el-input>
        </el-form-item>
        <el-form-item label="报警邮件" class="both">
          <el-input
            placeholder="请输入报警邮件，多个邮件地址则逗号分隔"
            v-model="addFrom.alarmEmail"
          >
          </el-input>
        </el-form-item>
        <div class="mini-title">调度配置</div>
        <el-form-item label="调度类型" class="both">
          <!-- scheduleType 空：NONE 固定速度：FIX_RATE   CRON:CRON -->

          <el-select v-model="addFrom.scheduleType" placeholder="请选择">
            <el-option
              v-for="item in scheduleType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addFrom.scheduleType == 'FIX_RATE'"
          label="固定速度"
          class="both"
        >
          <!-- scheduleConf 固定速度的值  cronGen_display-->
          <!-- schedule_conf_FIX_RATE 还有个这个 -->
          <el-input
            placeholder="请输入 （ Second ）"
            v-model="addFrom.scheduleConf"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="addFrom.scheduleType == 'CRON'"
          label="CRON"
          class="both"
        >
          <!-- scheduleConf 固定速度的值 -->
          <!-- schedule_conf_FIX_RATE 还有个这个 -->
          <el-popover
            placement="bottom"
            width="448"
            trigger="manual"
            v-model="visible"
          >
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
              <el-tab-pane label="秒" name="1">用户管理</el-tab-pane>
              <el-tab-pane label="分钟" name="2">配置管理</el-tab-pane>
              <el-tab-pane label="小时" name="3">角色管理</el-tab-pane>
              <el-tab-pane label="日" name="4">定时任务补偿</el-tab-pane>
              <el-tab-pane label="月" name="5">配置管理</el-tab-pane>
              <el-tab-pane label="周" name="6">角色管理</el-tab-pane>
              <el-tab-pane label="年" name="7">定时任务补偿</el-tab-pane>
            </el-tabs>
            <el-input
              slot="reference"
              placeholder="请输入 CRON"
              v-model="addFrom.scheduleConf"
            >
              <i
                slot="suffix"
                style="cursor: pointer"
                @click="visible = !visible"
                class="el-input__icon el-icon-date"
              ></i>
            </el-input>
          </el-popover>
        </el-form-item>
        <div class="mini-title">任务配置</div>

        <el-form-item label="运行模式" class="both">
          <!-- 运行模式 BEAN -->
          <el-select v-model="addFrom.glueType" placeholder="请选择">
            <el-option
              v-for="item in glueType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="JobHandler" class="both">
          <el-input
            placeholder="请输入负责人"
            :disabled="addFrom.glueType != 'BEAN'"
            v-model="addFrom.executorHandler"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="任务参数" class="one">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入本次执行的机器地址，为空则从执行器获取"
            v-model="addFrom.executorParam"
          >
          </el-input>
        </el-form-item>
        <div class="mini-title">高级配置</div>
        <el-form-item label="路由策略" class="both">
          <el-select
            v-model="addFrom.executorRouteStrategy"
            placeholder="请选择"
          >
            <el-option
              v-for="item in executorRouteStrategy"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子任务ID" class="both">
          <el-input
            placeholder="请输入子任务的任务ID,如存在多个则逗号分隔"
            v-model="addFrom.childJobId"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="调度过期策略" class="both">
          <el-select v-model="addFrom.misfireStrategy" placeholder="请选择">
            <el-option
              v-for="item in misfireStrategy"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阻塞处理策略" class="both">
          <el-select
            v-model="addFrom.executorBlockStrategy"
            placeholder="请选择"
          >
            <el-option
              v-for="item in executorBlockStrategy"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务超时时间" class="both">
          <el-input
            placeholder="任务超时时间，单位秒，大于零时生效"
            v-model="addFrom.executorTimeout"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="失败重试次数" class="both">
          <el-input
            placeholder="失败重试次数，大于零时生效"
            v-model="addFrom.executorFailRetryCount"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">确定</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  jobinfoList,
  triggerJobinfo,
  loadByIdJobinfo,
  jobgroupList,
  nextTriggerTime,
  start,
  stop,
  remove,
  add,
} from "@/api/job.js";
import { successAlert, warningAlert } from "@/utils/alert";
export default {
  data() {
    return {
      visible: false,
      scheduleType: [
        {
          value: "NONE",
          label: "空",
        },
        {
          value: "FIX_RATE",
          label: "固定速度",
        },
        {
          value: "CRON",
          label: "CRON",
        },
      ],
      glueType: [
        {
          value: "BEAN",
          label: "BEAN",
        },
        {
          value: "GLUE_GROOVY",
          label: "GLUE(Java)",
        },
        {
          value: "GLUE_SHELL",
          label: "GLUE(Shell)",
        },
        {
          value: "GLUE_PYTHON",
          label: "GLUE(Python)",
        },
        {
          value: "GLUE_PHP",
          label: "GLUE(PHP)",
        },
        {
          value: "GLUE_NODEJS",
          label: "GLUE(Nodejs)",
        },
        {
          value: "GLUE_POWERSHELL",
          label: "GLUE(PowerShell)",
        },
      ],
      executorRouteStrategy: [
        {
          value: "FIRST",
          label: "第一个",
        },
        {
          value: "LAST",
          label: "最后一个",
        },
        {
          value: "ROUND",
          label: "轮询",
        },
        {
          value: "RANDOM",
          label: "随机",
        },
        {
          value: "CONSISTENT_HASH",
          label: "一致性HASH",
        },
        {
          value: "LEAST_FREQUENTLY_USED",
          label: "最不经常使用",
        },
        {
          value: "LEAST_RECENTLY_USED",
          label: "最近最久未使用",
        },
        {
          value: "FAILOVER",
          label: "故障转移",
        },
        {
          value: "BUSYOVER",
          label: "忙碌转移",
        },
        {
          value: "SHARDING_BROADCAST",
          label: "分片广播",
        },
      ],
      misfireStrategy: [
        {
          value: "DO_NOTHING",
          label: "忽略",
        },
        {
          value: "FIRE_ONCE_NOW",
          label: "立即执行一次",
        },
      ],
      executorBlockStrategy: [
        {
          value: "SERIAL_EXECUTION",
          label: "单机串行",
        },
        {
          value: "DISCARD_LATER",
          label: "丢弃后续调度",
        },
        {
          value: "COVER_EARLY",
          label: "覆盖之前调度",
        },
      ],
      manageFrom: {},
      tableData: [],
      groupList: [],
      showData: {
        timeList: [],
      },
      addDialogVisible: false,
      aDialogVisible: false,
      cDialogVisible: false,
      dDialogVisible: false,
      form: {
        jobGroup: "",
        triggerStatus: -1,
        jobDesc: "",
        executorHandler: "",
        author: "",
      },
      addFrom: {},
      params: {
        current: 1,
        size: 10,
      },
      total: 0,
      options: [
        {
          id: -1,
          label: "全部",
        },
        {
          id: 1,
          label: "启动",
        },
        {
          id: 0,
          label: "停止",
        },
      ],
    };
  },
  mounted() {
    this.handleJobGroupList();
  },
  methods: {
    async handleAdd() {
      console.log(this.addFrom);
      let data = {
        ...this.addFrom,
      };
      const params = new URLSearchParams(data).toString();
      let res = await add(params);
      if (res.code == 200) {
        successAlert("操作成功");
        this.addDialogVisible = false;
        this.handleJobinfoList();
      }
    },
    handleRemove() {
      let data = {
        id: this.manageFrom.id,
      };
      const queryParams = new URLSearchParams(data).toString();
      this.$confirm("继续操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          remove(queryParams).then((res) => {
            this.$message.success("操作成功！");
            this.handleJobGroupList();
          });
        })
        .catch(() => {});
    },
    async handleStop() {
      let data = {
        id: this.manageFrom.id,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await stop(queryParams);
      if (res.code == 200) {
        successAlert("操作成功");
        this.handleJobinfoList();
      }
    },
    async handleStart() {
      let data = {
        id: this.manageFrom.id,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await start(queryParams);
      if (res.code == 200) {
        successAlert("操作成功");
        this.handleJobinfoList();
      }
    },
    async handleNextTriggerTime() {
      let data = {
        scheduleType: this.manageFrom.scheduleType,
        scheduleConf: this.manageFrom.scheduleConf,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await nextTriggerTime(queryParams);
      this.showData.timeList = res.content;
      this.dDialogVisible = true;
    },
    // 查询节点
    async handleLoadByIdJobinfo() {
      let data = {
        id: this.manageFrom.jobGroup,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await loadByIdJobinfo(queryParams);
      this.showData = res.content;
      this.cDialogVisible = true;
    },
    handleClose() {
      this.manageFrom = {};
      this.aDialogVisible = false;
      this.cDialogVisible = false;
      this.addDialogVisible = false;
    },
    // 执行一次
    async handleTriggerJobinfo() {
      let data = {
        id: this.manageFrom.id,
        executorParam: this.manageFrom.executorParam,
        addressList: this.manageFrom.addressList,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await triggerJobinfo(queryParams);
      if (res.code == 200) {
        successAlert("操作成功");
        this.handleClose();
      }
    },
    handleCommand(e) {
      this.manageFrom = e.data;
      // jobgroup/loadById
      // /jobinfo/nextTriggerTime
      switch (e.name) {
        case "a":
          this.aDialogVisible = true;
          break;
        case "c":
          this.handleLoadByIdJobinfo();
          break;
        case "d":
          this.handleNextTriggerTime();
          break;
        case "e":
          if (e.data.triggerStatus == 0) {
            this.handleStart();
          } else {
            this.handleStop();
          }

          break;
        case "g":
          this.handleRemove();
          break;
        // loadByIdJobinfo;
        default:
          break;
      }
      console.log(e);
    },
    handlePageChange(pageData) {
      this.params.size = pageData.size;
      this.params.current = pageData.page;
      this.handleJobinfoList();
    },
    async handleJobinfoList() {
      let data = {
        jobGroup: this.form.jobGroup,
        triggerStatus: this.form.triggerStatus,
        jobDesc: this.form.jobDesc,
        executorHandler: this.form.executorHandler,
        author: this.form.author,
        start: (this.params.current - 1) * this.params.size,
        length: this.params.size,
      };
      const queryParams = new URLSearchParams(data).toString();
      let res = await jobinfoList(queryParams);
      this.tableData = res.data;
      this.total = res.recordsTotal;
    },
    toSearch() {
      this.handleJobinfoList();
    },
    handleEdit(e) {
      this.addDialogVisible = true;
    },

    async handleJobGroupList() {
      let data = {
        start: 0,
        length: 999,
      };
      const queryParams = new URLSearchParams(data).toString();
      const res = await jobgroupList(queryParams);
      this.groupList = res.data;
      this.form.jobGroup = res.data[0].id;
      this.handleJobinfoList();
    },
  },
};
</script>

<style lang="scss" scoped>
.nav-title {
  color: #02a7f0;
  font-size: 20px;
  position: relative;
  padding-left: 16px;
  font-weight: bold;
  line-height: 28px;
}
.nav-title::before {
  content: "";
  position: absolute;
  left: 0px;
  top: 1px;
  width: 5px;
  height: 100%;
  background-color: #02a7f0;
  border-radius: 4px;
}
.search {
  margin: 16px 0;
  .search-form {
    padding: 10px;
    background-color: #eaf1fe;
    margin-bottom: 20px;
    border-radius: 8px;
    .el-form-item--mini.el-form-item,
    .el-form-item--small.el-form-item {
      margin-bottom: 0;
    }
  }
}
.el-dropdown-menu {
  background: #fff;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.add-form {
  .mini-title {
    color: #02a7f0;
    font-size: 16px;
    position: relative;
    padding-left: 12px;
    font-weight: bold;
    line-height: 28px;
  }
  .mini-title::before {
    content: "";
    position: absolute;
    left: 0px;
    top: 1px;
    width: 3px;
    height: 90%;
    background-color: #02a7f0;
    border-radius: 4px;
  }

  .both {
    width: 360px;
  }
  .one {
    width: 730px;
  }
  ::v-deep .el-form-item__content {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>