<template>
  <div class="monitoring">
    <header>
      <div class="left">
        <div class="title">
          <h1>后台任务监控</h1>
        </div>
        <div class="search">
          <el-input
            placeholder="任务名称"
            v-model="searchForm.task_name"
            @keyup.enter.native="submitsearchForm"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <div class="right">
        <el-button type="primary" @click="monPush" :loading="pushLoading"
          >输出</el-button
        >
        <el-button
          icon="el-icon-refresh"
          :loading="refreshLoading"
          @click="initMainTableData(searchForm)"
          circle
        ></el-button>
      </div>
    </header>
    <main>
      <BaseTable
        ref="mainTable"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :funData="funData"
        :funWidth="funWidth"
        :showIndex="true"
        :tabLoading="mainTabLoading"
        @onFunc="tableButtonHandle"
        :tableHeight="'70vh'"
        :border="false"
      >
        <template v-slot:sts="{ row }">
          <div>{{ stsDict[row.sts] }}</div>
        </template>
        <template v-slot:task_tag="{ row }">
          <baseNewSelect
            v-model="row.task_tag"
            :searchApiInfo="task_tag_apiInfo.searchApiInfo"
            :searchKey="task_tag_apiInfo.searchKey"
            :prop="task_tag_apiInfo.prop"
            :lookflag="true"
          ></baseNewSelect>
        </template>
        <template v-slot:diff_time="{ row }">
          <div>{{ getTimeHandler(row.diff_time) }}</div>
        </template>
      </BaseTable>
    </main>
    <footer>
      <basePage
        :pageModel="pageModel"
        @update:pageModel="currentChangeHandle"
      ></basePage>
    </footer>
  </div>
</template>

<script>
import basePage from "./compoments/basePage.vue";
import BaseTable from "./compoments/baseTable.vue";
import { getApiModuleApi, getExcelApi } from "@/api/apiChunks/index.js";
import baseNewSelect from "./compoments/baseNewSelect.vue";
export default {
  data() {
    return {
      refreshLoading: false,
      pushLoading: false,
      task_tag_apiInfo: {
        searchApiInfo: {
          tl: "apiReflectionService",
          as: "sys_api_reflectionService",
          dj: "queryOneById",
        },
        searchKey: "id",
        prop: {
          id: "id",
          label: "ref_name",
        },
      },
      stsDict: {
        Y: "正常",
        N: "不正常",
      },
      searchForm: {
        task_name: "",
      },
      mainTabLoading: false,
      funData: [
        {
          type: "execute",
          text: "执行",
          color: "#5a9cf8",
        },
        {
          type: "hang_up",
          text: "挂起",
          color: "#5a9cf8",
        },
        {
          type: "dele",
          text: "删除",
          color: "#e47470",
        },
      ],
      tableColumn: [
        {
          id: "task_name",
          title: "任务名称",
        },
        {
          id: "task_tag",
          title: "任务场景",
          tooltip: true,
        },
        {
          id: "task_classes",
          title: "类型",
        },
        {
          id: "org_id",
          title: "部署公司",
        },
        {
          id: "sts",
          title: "状态",
          tooltip: true,
        },
        {
          id: "plan_time",
          title: "计划时间",
          tooltip: true,
        },
        {
          id: "diff_time",
          title: "上次耗时",
        },
        {
          id: "run_num",
          title: "运行次数",
        },
        {
          id: "server_name",
          title: "服务器",
          tooltip: true,
        },
      ],
      tableData: [],
      pageModel: {
        pageIndex: 1,
        total: 10,
        limit: 10,
      },
    };
  },
  methods: {
    // 时间处理
    getTimeHandler(time) {
      var days = parseInt(time / (1000 * 60 * 60 * 24));
      var hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = (time % (1000 * 60)) / 1000;
      return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
    },
    // 执行与挂起
    async executeHandle(obj) {
      const res = await getApiModuleApi(
        {
          tl: "integrationTaskMonitoringService",
          as: "integrationTaskMonitoring",
          dj: "updateTaskMonitoringCarryAndHang",
        },
        obj
      );
      if (res.status == 200) {
        this.$nextTick(() => {
          this.initMainTableData(this.searchForm);
        });
        return true;
      }
    },
    // 输出excel
    async monPush() {
      this.pushLoading = true;
      const res = await getExcelApi(
        {
          tl: "integrationTaskMonitoringService",
          as: "integrationTaskMonitoring",
          dj: "queryMonitoringExportation",
        },
        {
          task_name: this.searchForm.task_name,
        }
      );
      this.pushLoading = false;
      if (!res) {
        this.$message({
          type: "error",
          message: "下载失败！",
        });
      } else {
        let url = window.URL.createObjectURL(
          new Blob([res], { type: "application/vnd.ms-excel" })
        );
        let fileName = "后台任务监控";
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName + ".xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }
    },
    // 初始化表单
    async initMainTableData(obj = {}) {
      this.refreshLoading = true;
      const res = await getApiModuleApi(
        {
          tl: "integrationTaskMonitoringService",
          as: "integrationTaskMonitoring",
          dj: "queryListJson",
        },
        {
          pageNum: this.pageModel.pageIndex,
          pageSize: this.pageModel.limit,
          ...obj,
        }
      );
      this.refreshLoading = false;
      if (res.status == 200) {
        this.tableData = res.attribute;
      }
    },
    // 表单搜索回车
    submitsearchForm() {
      this.initMainTableData(this.searchForm);
    },
    // 表格操作
    tableButtonHandle(val, item) {
      if (item.type === "execute") {
        let obj = {
          type: "1",
        };
        obj["task_id"] = val.task_id;
        obj["task_code"] = val.task_code;
        obj["task_name"] = val.task_name;
        this.executeHandle(obj).then(() => {
          this.$message({
            type: "success",
            message: "执行成功！",
          });
        });
      } else if (item.type == "dele") {
        this.$confirm("确认删除？")
          .then(async () => {
            console.log(111);
            const res = await getApiModuleApi(
              {
                tl: "integrationTaskMonitoringService",
                as: "integrationTaskMonitoring",
                dj: "updateTaskMonitoringSts",
              },
              { task_id: val.task_id }
            );
            console.log(res);
            if (res.status == 200) {
              if (
                this.pageModel.total + this.pageModel.limit - 1 <=
                this.pageModel.pageIndex * this.pageModel.limit
              ) {
                this.pageModel.pageIndex--;
              }
              console.log("删除");
              this.$nextTick(() => {
                this.initMainTableData(this.searchForm);
              });
            }
          })
          .catch(() => {});
      } else if (item.type === "hang_up") {
        let obj = {
          type: "2",
        };
        obj["task_id"] = val.task_id;
        obj["task_code"] = val.task_code;
        obj["task_name"] = val.task_name;
        this.executeHandle(obj).then(() => {
          this.$message({
            type: "success",
            message: "挂起成功！",
          });
        });
      } else if (item.type === "view") {
        this.$router.push({
          name: "sceneAdd",
          query: { id: val.id, lookFlag: true },
        });
      }
    },
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
        this.initMainTableData(this.searchForm);
      });
    },
  },
  computed: {
    // 操作框的宽度
    funWidth() {
      return this.funData.length * 70;
    },
  },
  components: {
    BaseTable,
    basePage,
    baseNewSelect,
  },
  created() {
    this.initMainTableData();
  },
};
</script>

<style scoped lang='scss'>
.monitoring {
  width: 100%;
  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background-color: #fff;
    border-radius: 20px;

    .left {
      align-items: center;
      display: flex;
      .search {
        margin-left: 30px;
      }
    }
  }
  main {
    padding: 20px;
    height: 75vh;
    border-radius: 20px;
    background-color: #fff;
  }
  footer {
    margin-top: 20px;
  }
}
</style>