<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :show-enable-flag="true"
      :mega-extend="{
        rowAction: {
          width: 172,
        },
      }"
      @beforeSearch="beforeSearch"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('ARCHIVING_TASKS:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('ARCHIVING_TASKS:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ formatData(statusList, text) }}
        </span>
      </template>
      <template slot="archiveMode" slot-scope="text">
        <span>
          {{ formatData(archiveList, text) }}
        </span>
      </template>
    </MomTable>
  </div>
</template>
<script>
import ApiConstant from "@/api/ApiConstant";
import { Icon } from "@mega-design/ui-vue";

export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { Icon },
  data() {
    return {
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      statusList: [], // 状态列表
      archiveList: [], // 归档方式列表
      // 查询的表单的配置项
      queryForm: {
        jobCode: undefined,
        jobName: undefined,
        datasourceId: undefined,
        archiveMode: undefined,
      },
      actionButtons: [
        (h, { record }) =>
          this.hasAuth("ARCHIVING_TASKS:TODO") && (
            <span
              class="text-primary"
              title={this.$t("RUN_ONE_TIME")}
              style="cursor: pointer;"
              onClick={() => this.handRun(record)}>
              <Icon
                type="icon-cur-implement"
                size={16}
                title={this.$t("RUN_ONE_TIME")}
              />
            </span>
          ),
        //
        (h, { record }) =>
          this.hasAuth("ARCHIVING_TASKS:VIEW") && (
            <span
              class="text-primary"
              title={this.$t("QUERY_LOG")}
              onClick={() => this.handView(record)}>
              <Icon
                type="icon-cur-a-filesearch"
                size={16}
                title={this.$t("QUERY_LOG")}
              />
            </span>
          ),
        this.hasAuth("ARCHIVING_TASKS:EDIT") && "edit",
        this.hasAuth("ARCHIVING_TASKS:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        jobCode: {
          label: () => this.$t("TASK_CODE"),
        },
        jobName: {
          label: () => this.$t("TASK_NAME"),
        },
        datasourceId: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "dataSourceName",
            value: "id",
          },
          label: () => this.$t("DATA_SOURCE"),
        },
        archiveMode: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("FILING_METHOD"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "jobCode",
          title: this.$t("TASK_CODE"),
          sorter: false,
          ellipsis: true,
          minWidth: 180,
        },
        {
          dataIndex: "jobName",
          title: this.$t("TASK_NAME"),
          ellipsis: true,
          minWidth: 180,
        },
        {
          dataIndex: "datasourceName",
          ellipsis: true,
          title: () => this.$t("DATA_SOURCE_NAME"),
          minWidth: 180,
        },
        {
          dataIndex: "datasourceType",
          ellipsis: true,
          title: () => this.$t("DATA_SOURCE_TYPE"),
          minWidth: 180,
        },
        {
          dataIndex: "archiveMode",
          ellipsis: true,
          title: () => this.$t("FILING_METHOD"),
          scopedSlots: { customRender: "archiveMode" },
          minWidth: 180,
        },
        {
          dataIndex: "planTime",
          ellipsis: true,
          title: () => this.$t("DAILY_EXECUTION_TIME"),
          minWidth: 180,
        },
        {
          dataIndex: "lastExecTime",
          ellipsis: true,
          title: () => this.$t("LAST_EXECUTION_TIME"),
          minWidth: 180,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
  },
  methods: {
    beforeSearch() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_FLAG`), // 启用状态
        this.getDictByCode(`DIC:DVOPS:ARCHIVE_MODE`), // 归档方式
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/list`), // 数据源的下拉
      ]).then(([enableStatusRes, archiveRes, dataSourceRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.archiveList = archiveRes.data.data;
        this.queryFormItem.datasourceId.options = dataSourceRes.data.data;
        this.queryFormItem.archiveMode.options = archiveRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem);
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 新增按钮的点击
    handleAdd() {
      this.$router.push({
        path: "/upms/system/setting/archivingTasks/add",
      });
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.$router.push({
        path: "/upms/system/setting/archivingTasks/edit",
        query: {
          id: row.id,
        },
      });
    },
    // 跳转到归档日志
    handView(row) {
      this.$router.push({
        path: "/upms/system/setting/archiveLog",
        query: {
          jobName: row.jobName,
          jobCode: row.jobCode,
        },
      });
    },
    // 执行一次
    handRun(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job/trigger?id=${row.id}`
        )
        .then(() => {
          this.$message.success(this.$t("RUN_SUCCESS"));
          this.$refs.MomTable?.query();
        });
    },
    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(
                `${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then(() => {
                this.selectedRowKeys = [];
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                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(
              `${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job/${row.id}`
            )
            .then(() => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job/enable/${id}/${status}`
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    command(row) {},
  },
};
</script>
