<template>
  <div class="data-task-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="55px" inline>
        <el-form-item label="状态：">
          <el-select v-model="filter.status" placeholder="请选择" clearable>
            <el-option
              v-for="(val, key) in DATA_TASK_STATUS"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别：">
          <el-select v-model="filter.type" placeholder="请选择" clearable>
            <el-option
              v-for="(val, key) in DATA_TASK_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据结果：" label-width="85px">
          <el-select v-model="filter.result" placeholder="请选择" clearable>
            <el-option
              v-for="(val, key) in DATA_TASK_RESULT"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="icon icon-search" @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <!-- <el-button
          type="danger"
          icon="el-icon-delete"
          @click="toRemove('DELETE')"
          >批量删除</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete-solid"
          @click="toRemove('CLEAR')"
          >清空</el-button
        > -->
      </div>
    </div>
    <div class="part-box">
      <el-table
        ref="TableList"
        :data="tasks"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50"
          align="center"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="printPlanName" label="项目"></el-table-column>
        <el-table-column prop="type" label="类别"> </el-table-column>
        <el-table-column prop="status" label="状态"> </el-table-column>
        <el-table-column prop="result" label="结果"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="createName" label="创建人"></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          align="center"
          width="120px"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.hasReportFile"
              class="btn-table-icon"
              type="text"
              icon="el-icon-download"
              :disabled="loading"
              @click="toDonwloadLog(scope.row)"
              title="导出日志"
            ></el-button>
            <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-download-act"
              :disabled="loading"
              @click="toDonwloadFile(scope.row)"
              title="下载文件"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  DATA_TASK_STATUS,
  DATA_TASK_TYPE,
  DATA_TASK_RESULT
} from "@/constants/enumerate";
import { dataTaskList, removeDataTask } from "../api";
import { attachmentDownload } from "../../login/api";
import { downloadFileURL } from "@/plugins/utils";

export default {
  name: "data-task-manage",
  data() {
    return {
      filter: {
        type: "",
        status: "",
        result: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      DATA_TASK_STATUS,
      DATA_TASK_TYPE,
      DATA_TASK_RESULT,
      tasks: [],
      curTask: {},
      multipleSelection: [],
      loading: false
    };
  },
  created() {
    this.toPage(1);
  },
  methods: {
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      const data = await dataTaskList(datas);
      this.tasks = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
      this.multipleSelection = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
      console.log(this.multipleSelection);
    },
    toRemove(type) {
      let tips = "";
      if (type === "CLEAR") {
        tips = "确定要清空所有任务吗？";
      } else {
        tips = "确定要删除选中的任务吗？";
        if (!this.multipleSelection.length) {
          this.$message.error("请选择要删除的记录！");
          return;
        }
      }

      this.$confirm(tips, "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(async () => {
          const data = await removeDataTask({
            ids: type === "CLEAR" ? null : this.multipleSelection,
            type: type === "CLEAR" ? "ALL" : null
          }).catch(() => {});
          if (!data) return;
          this.$message.success("操作成功！");
          this.deletePageLastItem();
        })
        .catch(() => {});
    },
    async toDonwloadLog(row) {
      if (this.loading) return;

      this.loading = true;
      const res = await attachmentDownload({
        id: row.id,
        type: "REPORT"
      }).catch(() => {});

      if (!res) {
        this.loading = false;
        this.$message.error("文件下载失败，请重新尝试！");
        return;
      }

      const url = res.url;
      let result = true;
      await downloadFileURL(url).catch(() => {
        result = false;
      });
      this.loading = false;

      if (result) {
        this.$message.success("文件下载成功！");
      } else {
        this.$message.error("文件下载失败，请重新尝试！");
      }
    },
    async toDonwloadFile(row) {
      if (this.loading) return;

      this.loading = true;
      const type = row.hasResultFile ? "RESULT" : "IMPORT_FILE";
      const res = await attachmentDownload({
        id: row.id,
        type
      }).catch(() => {});

      if (!res) {
        this.loading = false;
        this.$message.error("文件下载失败，请重新尝试！");
        return;
      }

      const url = res.url;
      let result = true;
      await downloadFileURL(url).catch(() => {
        result = false;
      });
      this.loading = false;

      if (result) {
        this.$message.success("文件下载成功！");
      } else {
        this.$message.error("文件下载失败，请重新尝试！");
      }
    }
  }
};
</script>
