<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      row-key="id"
      :page.sync="page"
      :total="total"
      :action-buttons="tableAction"
      :mega-extend="{
        rowAction: {
          width: 144,
        },
      }"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
    >
      <template slot="executorRouteStrategy" slot-scope="text, record">
        <span>{{
          formatData(executorRouteStrategyList, record.executorRouteStrategy)
        }}</span>
      </template>
      <template slot="lastHandleCode" slot-scope="text, record">
        <span>{{ formatData(lastHandleCodeList, record.lastHandleCode) }}</span>
      </template>
      <template slot="triggerStatus" slot-scope="text, record">
        <span v-if="record.triggerStatus === 1" class="text-success normal">{{
          formatData(queryFormItem.triggerStatus.options, record.triggerStatus)
        }}</span>
        <span v-if="record.triggerStatus === 0" class="text-error disabled">{{
          formatData(queryFormItem.triggerStatus.options, record.triggerStatus)
        }}</span>
      </template>
      <template slot="address" slot-scope="text, record">
        <a-popover width="600" placement="top" trigger="click">
          <a slot="content">
            <mega-base-table
              :columns="gridColumns"
              :data-source="gridData"
              :mega-extend="{ rowAction: false }"
            >
            </mega-base-table>
          </a>
          <a-button
            class="showDetail"
            type="primary"
            @click="showDetail(record, 'address')"
          >
            {{ $t("VIEW") }}
          </a-button>
        </a-popover>
      </template>
      <template slot="nextTriggerTime" slot-scope="text, record">
        <a-popover width="300" trigger="click">
          <a slot="content">
            <mega-base-table
              :columns="triggerColumns"
              :data-source="triggerTimes"
              :mega-extend="{ rowAction: false }"
            >
            </mega-base-table>
          </a>
          <a-button
            class="showDetail"
            type="primary"
            @click="showDetail(record, 'nextTriggerTime')"
          >
            {{ $t("VIEW") }}
          </a-button>
        </a-popover>
      </template>
      <template slot="toolbar">
        <a-button v-if="hasAuth('TASK_MANAGEMENT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('TASK_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </template>
    </MomTable>
  </div>
</template>

<script>
import { Icon } from "@mega-design/ui-vue";

export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { Icon },
  data() {
    return {
      tableData: [],
      page: 1, // 页码
      total: 20, // 每页个数
      queryForm: {
        glueType: "", // 	任务类型
        jobDesc: "", // 任务名称
        triggerStatus: "", // 调度状态：0-停止，1-运行
      },
      // 查询sort
      sortParams: null,
      gridData: [],
      triggerTimes: [],
      dialogFormVisible: false,
      executorRouteStrategyList: [],
      lastHandleCodeList: [],
      isEdit: false,
      tableAction: [
        this.hasAuth("TASK_MANAGEMENT:EDIT") && "edit",
        (h, { record }, a, b) => {
          if ([1, "1"].includes(record.triggerStatus)) {
            return (
              <a-icon
                type="pause-circle"
                onClick={() =>
                  this.triggerStatusChange(
                    record,
                    this.$t("CONFIRM_STOP"),
                    this.$t("CONFIRM"),
                    this.$t("STOP_SUCCESS")
                  )
                }
                class="text-success"
                title={this.$t("STOP")}
              />
            );
          }
          return (
            <a-icon
              type="play-circle"
              onClick={() =>
                this.triggerStatusChange(
                  record,
                  this.$t("CONFIRM_RUN"),
                  this.$t("CONFIRM"),
                  this.$t("RUN_SUCCESS")
                )
              }
              class="text-success"
              title={this.$t("RUN")}
            />
          );
        },
        this.hasAuth("TASK_MANAGEMENT:DELETE") && "delete",
        (h, { record }) => (
          <span
            class="text-primary"
            title={this.$t("RUN_ONE_TIME")}
            onClick={() => this.command(record, "trigger")}>
            <Icon
              type="icon-cur-implement"
              size={16}
              title={this.$t("RUN_ONE_TIME")}
            />
          </span>
        ),
        (h, { record }) => (
          <span
            class="text-primary"
            title={this.$t("QUERY_LOG")}
            onClick={() => this.command(record, "querylog")}>
            <Icon
              type="icon-cur-a-filesearch"
              size={16}
              title={this.$t("QUERY_LOG")}
            />
          </span>
        ),
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 查询的表单的配置项
    queryFormItem() {
      return this.$observable("queryFormItem", {
        glueType: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("TASK_TYPE"), // 	任务类型
        },
        jobDesc: {
          label: () => this.$t("TASK_NAME"), // 任务名称
        },
        triggerStatus: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("TRIGGER_STATUS"), // 调度状态
        },
      });
    },
    moreOptions() {
      return [
        {
          command: "trigger",
          btnText: "RUN_ONE_TIME", // 执行一次
        },
        {
          command: "querylog",
          btnText: "QUERY_LOG", // 查询日志
        },
      ];
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "jobDesc",
          Width: 150,
          title: () => this.$t("TASK_NAME"), // 任务名称
          width: 300,
        },
        {
          dataIndex: "executorRouteStrategy",
          width: 140,
          sorter: false,
          scopedSlots: { customRender: "executorRouteStrategy" },
          title: () => this.$t("EXECTOR_ROUTE_STRATEGY"), // 执行器路由策略
        },
        {
          dataIndex: "jobCron",
          minWidth: 200,
          sorter: false,
          title: () => this.$t("JOB_CORN"), // 	任务执行CRON表达式
        },
        {
          dataIndex: "lastHandleCode",
          width: 180,
          sorter: false,
          scopedSlots: { customRender: "lastHandleCode" },
          title: () => this.$t("LAST_HANDLE_CODE"), // 最近一次执行状态
        },
        {
          dataIndex: "triggerStatus",
          sorter: false,
          scopedSlots: { customRender: "triggerStatus" },
          title: () => this.$t("TRIGGER_STATUS"), // 调度状态
          width: 120,
        },
        {
          dataIndex: "address",
          sorter: false,
          title: () => this.$t("REGISTER_NODE"), // 注册节点
          scopedSlots: { customRender: "address" },
          width: 120,
        },
        {
          dataIndex: "nextTriggerTime",
          sorter: false,
          title: () => this.$t("NEXT_TRIGGER_TIME"), // 下次注册时间
          scopedSlots: { customRender: "nextTriggerTime" },
          width: 200,
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ];
    },
    gridColumns() {
      return [
        {
          dataIndex: "title",
          minWidth: 200,
          title: () => this.$t("JOB_GROUP_NAME"), // 执行器名称
        },
        {
          dataIndex: "appName",
          minWidth: 200,
          title: () => this.$t("APP_NAME"), // appName
        },
        {
          dataIndex: "addressList",
          minWidth: 200,
          title: () => this.$t("MACHINE_ADDRESS"), // 机器地址
        },
      ];
    },
    triggerColumns() {
      return [
        {
          dataIndex: "time",
          minWidth: 200,
          title: () => this.$t("TIGGER_TIME"),
        },
      ];
    },
  },
  mounted() {
    this.searchDictCode();
  },
  methods: {
    // 数据字典查询
    searchDictCode() {
      // 获取调度状态
      this.getDictByCode(`DIC:CORE:JOB_TRIGGER_STATUS`).then((res) => {
        this.queryFormItem.triggerStatus.options = res.data.data;
      });

      // 获取任务类型
      this.getDictByCode(`DIC:CORE:JOB_TASK_TYPE`).then((res) => {
        this.queryFormItem.glueType.options = res.data.data;
      });

      // 获取执行状态
      this.getDictByCode(`DIC:CORE:JOB_DATA_HANDLE_CODE`).then((res) => {
        this.lastHandleCodeList = res.data.data;
      });

      // 路由策略
      this.getDictByCode(`DIC:CORE:JOB_ROUTING_STRATEGY`).then((res) => {
        this.executorRouteStrategyList = res.data.data;
      });
    },
    // 后台分页查询
    searchPageData(data) {
      this.$axios
        .get("/job-server/api/job/search", { params: data })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 操作列
    command(row, command) {
      if (command === "trigger") {
        this.$confirm({
          title: this.$t("RUN_ONE_TIME"),
          content: this.$t("CONFIRM_RUN_TIP"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "exclamation-circle",
          onOk: () => {
            this.$axios
              .get(`/job-server/api/job/trigger`, {
                params: { executorParam: "", jobId: row.id },
              })
              .then((res) => {
                this.$message.success(this.$t("TASK_SUCCESS")); // 任务执行成功
                this.$refs.MomTable?.query();
              });
          },
        });
      } else if (command === "querylog") {
        this.$router.push({
          query: {
            jobId: row.id,
            jobDesc: row.jobDesc,
          },
          path: "/upms/system/job/log",
        });
      }
    },
    // 转化调度状态
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 切换运行状态 （运行/停止）
    triggerStatusChange(row, infoText, confirmButtonText, tips) {
      this.$confirm({
        title: confirmButtonText,
        content: infoText,
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          if (row.triggerStatus === 1) {
            this.$axios
              .put(`/job-server/api/job/stop/${row.id}`)
              .then((res) => {
                this.$message.success(tips);
                this.$refs.MomTable?.query();
              });
          } else {
            this.$axios
              .put(`/job-server/api/job/start/${row.id}`)
              .then((res) => {
                this.$message.success(tips);
                this.$refs.MomTable?.query();
              });
          }
        },
      });
    },
    // 查看节点和下次触发时间
    showDetail(row, name) {
      if (name === "nextTriggerTime") {
        this.$axios
          .get(`/job-server/api/job/next-trigger-time`, {
            params: { cron: row.jobCron },
          })
          .then((res) => {
            this.triggerTimes = [];
            if (res.data.data) {
              this.triggerTimes = res.data.data.map((item) => {
                return {
                  time: item,
                };
              });
            }
          });
      } else {
        this.$axios
          .get(`/job-server/api/job-group/${row.jobGroup}`)
          .then((res) => {
            this.gridData = res.data.data ? [res.data.data] : [];
          });
      }
    },
    handleAdd() {
      this.$router.push({
        path: "/upms/system/job/task/add",
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/upms/system/job/task/edit",
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(`/job-server/api/job/batch-delete`, {
                params: {
                  ids: this.selectedRowKeys.join(","),
                },
              })
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.page = 1;
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 点击表格行内的删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios.delete(`/job-server/api/job/${row.id}`).then((res) => {
            this.$message.success(this.$t("DELETE_SUCCESS"));
            this.page = 1;
            this.$refs.MomTable?.query();
          });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.no-data {
  color: #909399;
  line-height: 15px;
  text-align: center;
}
.showDetail {
  color: #01baea !important;
  text-decoration: underline;
  cursor: pointer;
  background-color: transparent !important;
  border-color: transparent !important;
  text-shadow: 0 0 0 transparent !important;
  box-shadow: 0 0 0 transparent !important;
}
/deep/.ant-table td {
  white-space: nowrap;
}
</style>
