<template>
  <div>
    <MomTable
      ref="MomTable"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      row-key="id"
      :page.sync="page"
      :total="total"
      :init-call="false"
      :action-buttons="tableAction"
      :mega-extend="{
        rowAction: {
          width: 62,
        },
      }"
      @search="searchPageData"
    >
      <template slot="triggerCode" slot-scope="text, record">
        <span>{{ formatData(callResult, record.triggerCode) }}</span>
      </template>
      <template slot="triggerMsg" slot-scope="text, record">
        <a-popover trigger="click">
          <a slot="content">
            <div style="color: #000" v-html="record.triggerMsg"></div>
          </a>
          <a-button class="showDetail" type="primary">
            {{ $t("VIEW") }}
          </a-button>
        </a-popover>
      </template>
      <template slot="jobDesc">
        <a-select
          v-model="queryForm.jobDesc"
          allow-clear
          :placeholder="$t('PLACESELECT')"
          style="width: 100%"
        >
          <a-select-option
            v-for="item in jobDescList"
            :key="item.id"
            :value="item.id"
            >{{ $t(item.jobDesc) }}</a-select-option
          >
        </a-select>
      </template>
      <template slot="handleCode" slot-scope="text, record">
        <span>{{ formatData(executeResult, record.handleCode) }}</span>
      </template>
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('TASK_LOG:CLEAN_LOG')"
          class="btn__red-1"
          @click="handleClean"
        >
          <a-icon type="delete" />
          {{ $t("CLEAN_LOG") }}
        </a-button>
      </div>
    </MomTable>
    <MegaModal
      :title="$t('VIEW_DETAIL')"
      :visible.sync="dialogVisible"
      :width="800"
      @cancel="dialogVisible = false"
    >
      <div v-html="logContent"></div>
      <div slot="footer" class="dialog-footer">
        <a-button type="primary" @click="refreshClean">
          <a-icon type="reload" />
          {{ $t("REFRESH_LOG") }}
        </a-button>
        <a-button @click="dialogVisible = false">
          <Icon type="icon-dir-f-rollback" :size="18" />
          {{ $t("CANCEL") }}
        </a-button>
      </div>
    </MegaModal>
    <i-dialog-form
      :visible="dialogVisble"
      :title="$t('CLEAN_LOG')"
      :form-item="dialogFormItem"
      :search-form="dialogForm"
      @save="save"
      @close="dialogVisble = false"
    />
  </div>
</template>

<script>
import moment from "moment";
import { Icon, Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
    Icon,
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (vm.$route.query.jobId) {
        // 执行器
        // eslint-disable-next-line
        vm.jobId = vm.$route.query.jobId.toString();
        // eslint-disable-next-line
        vm.queryForm.jobDesc = vm.$route.query.jobDesc.toString();
        vm.searchPageData();
      } else {
        // 获取数据
        vm.searchPageData();
      }
    });
  },
  data() {
    return {
      showBtns: true,
      dialogVisible: false,
      code_rule: "", // 编码规则
      tableData: [],
      page: 1, // 页码
      total: 0, // 总条数
      dialogVisble: false, // 弹框的显示 隐藏
      // 查询sort
      sortParams: null,
      // 查询的表单的配置项
      queryForm: {
        jobDesc: "",
        jobGroup: "",
        logStatus: "",
      },
      // 新增或修改的表单配置项
      dialogForm: {
        jobGroup: "",
        jobId: "",
        type: "",
      },
      // 日志内容
      logContent: "",
      // 显示日志
      logShow: false,
      jobId: "",
      params: {
        executorAddress: "",
        logId: "",
        triggerTime: "",
        fromLineNum: "0",
      },
      tableAction: [
        (h, value, a, b) => (
          <a-button type="text" onClick={() => this.handleView(value)}>
            <Icon
              class="operation-icon"
              type="icon-cur-eye"
              size={20}
              title={this.$t("VIEW")}
            />
          </a-button>
        ),
      ],
      callResult: [],
      jobDescList: [],
      executeResult: [],
    };
  },
  computed: {
    // 表格筛选项
    queryFormItem() {
      return this.$observable("queryFormItem", {
        jobDesc: {
          label: () => this.$t("TASK_NAME"),
          slots: { title: "jobDesc" },
        },
        jobGroup: {
          itemType: "select",
          label: () => this.$t("EXECUTOR"),
          labelWidth: "90",
          optionsProps: {
            label: "label",
            value: "value",
          },
          options: [],
        },
        logStatus: {
          itemType: "select",
          label: () => this.$t("LOG_STATUS"),
          labelWidth: "90",
          optionsProps: {
            label: "label",
            value: "value",
          },
          options: [],
        },
      });
    },
    // 表单的配置项详情
    dialogFormItem() {
      return this.$observable("dialogFormItem", {
        jobGroup: {
          itemType: "select",
          i18n: this.$t("EXECUTOR"), // 	执行器
          isRequired: true,
          options: [],
        },
        jobId: {
          itemType: "select",
          i18n: this.$t("TASK_NAME"), // 	任务
          isRequired: true,
          options: [],
        },
        type: {
          itemType: "select",
          i18n: this.$t("TYPE"), // 类型
          isRequired: true,
          options: [],
        },
      });
    },
    // 表格配置项
    tableColumns() {
      return [
        {
          dataIndex: "jobId",
          title: () => this.$t("JOB_ID"),
          width: 200,
          sorter: false,
        },
        {
          dataIndex: "jobDesc",
          title: () => this.$t("TASK_NAME"),
          options: [],
          minWidth: 240,
        },
        {
          dataIndex: "triggerTime",
          title: () => this.$t("TRIGGER_TIME"),
          options: [],
          sorter: false,
          width: 200,
        },
        {
          key: "triggerCode",
          title: () => this.$t("TRIGGER_RESULT"),
          scopedSlots: { customRender: "triggerCode" },
          options: [],
          sorter: false,
          width: 200,
        },
        {
          key: "triggerMsg",
          title: () => this.$t("TRIGGER_REMARK"),
          scopedSlots: { customRender: "triggerMsg" },
          options: [],
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "handleTime",
          title: () => this.$t("HANDLE_TIME"),
          width: 220,
        },
        {
          key: "handleCode",
          title: () => this.$t("HANDLE_RESULT"),
          scopedSlots: { customRender: "handleCode" },
          options: [],
          sorter: false,
          width: 200,
        },
      ];
    },
  },
  watch: {
    "dialogForm.jobGroup": {
      handler(newVal, oldVal) {
        this.getJobData();
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    // 初始化字典数据
    this.initDictData();
  },
  methods: {
    // 获取任务数据
    getJobData() {
      this.dialogForm.jobId = "";
      if (!this.dialogForm.jobGroup) {
        return;
      }
      this.$axios
        .get(`/job-server/api/job/list`, {
          params: { jobGroup: this.dialogForm.jobGroup },
        })
        .then((res) => {
          if (res.data.data && res.data.data.length > 0) {
            res.data.data.forEach((item) => {
              // eslint-disable-next-line
              item.label = item.jobDesc;
              // eslint-disable-next-line
              item.value = item.id.toString();
            });
          }
          this.$set(this.dialogFormItem.jobId, "options", res.data.data);
        });
    },
    // 初始化字典数据
    initDictData() {
      // 执行器
      this.$axios.get(`/job-server/api/job-group/list`).then((res) => {
        if (res.data.data && res.data.data.length > 0) {
          res.data.data.forEach((item) => {
            // eslint-disable-next-line
            item.label = item.title;
            // eslint-disable-next-line
            item.value = item.id.toString();
          });
        }
        this.queryFormItem.jobGroup.options = res.data.data;
        this.dialogFormItem.jobGroup.options = res.data.data;
      });

      // 状态
      this.getDictByCode(`DIC:CORE:JOB_DATA_QUERY_CODE`).then((res) => {
        this.queryFormItem.logStatus.options = res.data.data;
      });
      // 类型
      this.getDictByCode(`DIC:CORE:JOB_CLEAR_LOG_TYPE`).then((res) => {
        this.dialogFormItem.type.options = res.data.data;
      });
      // 调度结果
      this.getDictByCode(`DIC:CORE:JOB_DATA_TRIGGER_CODE`).then((res) => {
        this.callResult = res.data.data;
      });
      // 执行结果
      this.getDictByCode(`DIC:CORE:JOB_DATA_HANDLE_CODE`).then((res) => {
        this.executeResult = res.data.data;
      });
      // 任务名称列表查询
      this.$axios.get(`/job-server/api/job/list`).then((res) => {
        this.jobDescList = res.data.data;
      });
    },
    // 后台分页查询
    searchPageData(data) {
      const obj = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        jobId: this.jobId,
        ...this.queryForm,
        ...this.sortParams,
      };
      const params = data || obj;
      this.$axios.get(`/job-server/api/log/search`, { params }).then((res) => {
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
      });
    },
    // 清理日志
    handleClean() {
      this.dialogVisble = true;
    },
    // 刷新日志
    refreshClean() {
      this.getLogDetail(true);
    },
    // 点击表格行内的查看
    handleView(row) {
      this.dialogVisible = true;
      this.logContent = "";
      this.params.executorAddress = row.record.executorAddress;
      this.params.logId = row.record.id;
      this.params.triggerTime = moment(row.record.triggerTime).format("x");
      this.getLogDetail();
    },
    // 获取日志详情
    getLogDetail(isRefresh) {
      this.$axios
        .get(`/job-server/api/log/log-detail-cat`, { params: this.params })
        .then((res) => {
          this.logContent = res.data.data.logContent;
          if (isRefresh) {
            this.$message.success(this.$t("REFRESH_SUCCESS"));
          }
        });
    },
    // 监听保存时间
    save(form) {
      this.$axios
        .delete(`/job-server/api/log/clear-log`, { data: form })
        .then((res) => {
          if (res.data.code === 200) {
            this.$refs.MomTable?.query();
            this.$message.success(this.$t("CLEAN_SUCCESS"));
          } else {
            this.$message.success(this.$t("CLEAN_FAIL"));
          }
          this.dialogVisble = false;
        });
    },
    formatData(data, status) {
      const result = data?.find((item) => item.value === status?.toString());
      return result ? result.label : "";
    },
  },
};
</script>
<style lang="less" scoped>
.log-container {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
  overflow: scroll;
  background: #f5f5f5;
  pre {
    display: block;
    margin: 0 0 10.5px;
    padding: 10px;
    color: #334851;
    word-wrap: break-word;
    word-break: break-all;
    background-color: #f5f5f5;
    // border: 1px solid #ccd1d3;
    border-radius: 1px;
  }
}

/deep/.el-dialog .el-dialog__body {
  padding: 20px !important;
}

.dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid #e8e8e8;
}
/deep/.ant-modal-body {
  margin-bottom: 40px;
}
/deep/.ant-table td {
  white-space: nowrap;
}
.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-popover-inner-content {
  width: 490px;
}
</style>
