<template>
  <div>
    <el-row>
      <el-col>
        <el-button @click="add()" type="success" style="margin-left: 20px;" size="mini"><i
            class="el-icon-plus"></i>
          新增
        </el-button>
        <div style="text-align: right;float:right;">
          <el-input style="width:200px;" size="mini" v-model="queryTaskName"
                    placeholder="任务名称"></el-input>
          <el-input style="width:200px;margin-left:20px" size="mini" v-model="queryProject"
                    placeholder="引擎名称"></el-input>
          <el-select
              v-model="queryNode"
              placeholder="选择节点"
              style="width:200px;margin-left:20px"
              size="mini">
            <el-option
                v-for="node in nodeOptions"
                :key="node.id"
                :label="node.nodeName"
                :value="node.nodeIp">
            </el-option>
          </el-select>
          <el-select
              v-model="queryTaskStatus"
              placeholder="任务状态"
              style="width:100px;margin-left:20px"
              size="mini">
            <el-option
                v-for="status in taskStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value">
            </el-option>
          </el-select>
          <el-button @click="query" type="primary" size="mini" style="margin-left:20px;"><i
              class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetQuery" type="info" size="mini" style="margin-left:20px;float:right"><i
              class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
        <myTable :metaData="metadata" :tableData="tableData" :isLoading="isLoading"
                 @selection-change="handleSelectionChange">
          <template v-slot="{ index }">
            <el-tooltip class="item" effect="dark"
                        content="立即运行一次"
                        placement="top">
              <el-button type="info" icon="el-icon-s-promotion" @click="runTask(index)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip v-if="tableData[index].enableFlag === '0'" class="item" effect="dark"
                        content="启动"
                        placement="top">
              <el-button type="success" icon="el-icon-caret-right" @click="enable(index,'1')" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip v-if="tableData[index].enableFlag === '1'" class="item" effect="dark"
                        content="暂停"
                        placement="top">
              <el-button type="warning" icon="el-icon-video-pause" @click="enable(index,'0')" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark"
                        content="编辑"
                        placement="top">
              <el-button type="primary" icon="el-icon-edit" @click="edit(index)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark"
                        content="复制"
                        placement="top">
              <el-button type="success" icon="el-icon-document-copy" @click="copyTask(index)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark"
                        content="删除"
                        placement="top">
              <el-button type="danger" icon="el-icon-delete" @click="deleteTaskById(index)" size="mini"
                         plain circle></el-button>
            </el-tooltip>
          </template>
        </myTable>
        <el-pagination
            style="padding: 15px"
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            :current-page="pageIndex"
            @current-change="onPageChange"
        ></el-pagination>
      </el-col>
    </el-row>
    <addTaskDialog v-model="formData" :dialogVisible=dialogVisible @close="closeDialog"></addTaskDialog>
  </div>
</template>
<script>
import Vue from "vue";
import {mapActions, mapState} from "vuex";
import {
  Select,
  Row,
  Col,
  Button,
  Message,
  Pagination,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  MessageBox
} from "element-ui";
import addTaskDialog from "./AddTaskDialog"
import myTable from "../components/CustomTable"
import crawlNodeApi from "../../js/api/crawlNodeApi"

Vue.use(Select);
Vue.use(Row);
Vue.use(Col);
Vue.use(Button);
Vue.use(Pagination);
Vue.use(Dropdown);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);

import taskApi from "../../js/api/taskApi";

export default {
  name: "CommonTaskTab",
  components: {
    'addTaskDialog': addTaskDialog,
    'myTable': myTable
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      multipleSelection: [],
      formLabelWidth: "100px",
      formInputWidth: "290px",
      tableName: "task",
      pageIndex: 0,
      systemFlagOptions: [],
      formData: {
        name: "",
        carrierType: "",
        enableFlag: "",
        taskType: "1",
        clusterName: "",
        systemFlag: "",
        cron: "",
        server: "",
        project: "",
        spider: "",
        id: "",
        createTime: "",
      },
      taskStatusOptions: [
        {value: 0, label: "已暂停"},
        {value: 1, label: "已启动"}
      ],
      nodeOptions: [],
      queryTaskName: "",
      queryProject: "",
      queryNode: "",
      queryTaskStatus: null,
      filterSingleSiteTask: true,
    };
  },
  computed: {
    metadata: function () {
      const temp = [];
      this.$store.state.metadata.metadata.forEach((element) => {
        if (element.tableName === "task") {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    },
    ...
        mapState({
          tableData: (state) => state.task.tasks,
          total: (state) => state.task.total,
          isLoading: (state) => state.task.isLoading
        })
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    add() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.clearForm();
    },
    deleteTaskById(index) {
      MessageBox.confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            let ids = [this.tableData[index].id]
            taskApi.delTasks(ids, (response) => {
              if (response.data.code === 200) {
                Message({
                  message: "删除成功：" + this.tableData[Number(index)]["name"],
                  type: "success",
                });
              }
              this.refresh()
            })
          })
          .catch(() => {
          })
    },
    runTask(index) {
      let ids = [];
      ids.push(this.tableData[index]["id"]);
      taskApi.startTasks(ids, (response) => {
        if (response.data.code === 200) {
          Message({
            message: "启动" + this.tableData[Number(index)]["name"],
            type: "success",
          });
        }
      });
    },
    setQueryDataBody() {
      let dataBody = {
        taskType: 1
      }
      if (this.queryTaskName.length > 0) {
        dataBody.name = this.queryTaskName
      }
      if (this.queryProject.length > 0) {
        dataBody.project = this.queryProject
      }
      if (this.queryTaskStatus !== null) {
        dataBody.enableFlag = this.queryTaskStatus
      }
      if (this.queryNode.length > 0) {
        dataBody.server = this.queryNode
      }
      return dataBody;
    },
    resetQueryDataBody() {
      let dataBody = {
        taskType: 1
      }
      this.queryTaskName = ""
      this.queryProject = ""
      this.queryTaskStatus = null
      this.queryNode = ""
      return dataBody;
    },
    onPageChange(index) {
      this.pageIndex = index;
      this.queryPageable({
        index: this.pageIndex - 1,
        size: 10,
        dataBody: this.setQueryDataBody()
      });
    },
    closeDialog() {
      this.dialogVisible = false;
      if (this.formData.save) {
        taskApi.saveTask(this.formData, this.isEdit, (response) => {
          if (response.data.code === 200) {
            Message.success("保存成功！");
            this.queryPageable({
              index: this.pageIndex - 1,
              size: 10,
              dataBody: this.setQueryDataBody()
            });
          } else {
            Message.error("保存失败！");
          }
        })
      }
    },
    edit(index) {
      this.formData = {...this.tableData[index]};
      // this.formData.carrierType = this.formData.carrierType.split(",")
      this.isEdit = true;
      this.dialogVisible = true;
    },
    copyTask(index) {
      MessageBox.confirm("是否复制此任务？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "info",
      })
          .then(() => {
            this.formData = {...this.tableData[index]};
            delete this.formData.id;
            this.isEdit = false;
            taskApi.saveTask(this.formData, this.isEdit, (response) => {
              if (response.data.code === 200) {
                Message.success("复制成功！");
                this.queryPageable({
                  index: this.pageIndex - 1,
                  size: 10,
                  dataBody: this.setQueryDataBody()
                });
              } else {
                Message.error("复制失败！");
              }
            })
            this.clearForm();
          })
          .catch(() => {
          })
    },
    enable(index, flag) {
      this.formData = {...this.tableData[index]};
      // this.formData.carrierType = this.formData.carrierType.toString();
      this.formData.enableFlag = flag;
      taskApi.saveTask(this.formData, true, (response) => {
        if (response.data.code === 200) {
          if (flag === "1") {
            Message({
              message: "启动成功",
              type: "success",
            });
          } else {
            Message({
              message: "已暂停任务",
              type: "warning",
            });
          }
          this.queryPageable({
            index: this.pageIndex - 1,
            size: 10,
            dataBody: this.setQueryDataBody()
          });
        } else {
          if (flag === "1") {
            Message("启动失败！");
          } else {
            Message("暂停失败！");
          }
        }
      })
    },
    clearForm() {
      this.formData = new this.resetFormData();
    },
    queryLog(index) {
      this.$router.push('log/detail/' + this.tableData[index]["id"]);
    },
    ...mapActions({
      queryPageable: "task/queryPageable"
    }),
    resetFormData() {
      this.id = "";
      this.name = "";
      this.carrierType = [];
      this.enableFlag = "";
      this.systemFlag = "";
      this.cron = "";
      this.server = "";
      this.project = "";
      this.spider = "";
      this.save = false;
    },
    query() {
      this.pageIndex = 1
      this.queryPageable({
        index: 0,
        size: 10,
        dataBody: this.setQueryDataBody()
      });
    },
    resetQuery() {
      this.pageIndex = 1
      this.queryPageable({
        index: 0,
        size: 10,
        dataBody: this.resetQueryDataBody()
      });
    },
    refresh() {
      this.queryPageable({
        index: this.pageIndex - 1,
        size: 10,
        dataBody: this.setQueryDataBody()
      });
    }
  },
  mounted: function () {
    this.pageIndex = 1
    this.queryPageable({
      index: this.pageIndex - 1,
      size: 10,
      dataBody: {
        taskType: 1,
      }
    });
    if (this.nodeOptions.length === 0) {
      crawlNodeApi.queryAllCrawlNodes(response => {
        if (response.data.code === 200) {
          this.nodeOptions = response.data.content
        }
      })
    }
  },
};

</script>

<style scoped>
.el-pagination {
  display: flex;
  justify-content: center;
}

.el-table .cell,
.el-table th > .cell {
  text-align: center;
}
</style>