<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>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="状态：">
            <el-select
              v-model="filter.status"
              placeholder="状态"
              clearable
              style="width: 120px;"
            >
              <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
              filterable
            >
              <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
              style="width: 120px;"
            >
              <el-option
                v-for="(val, key) in DATA_TASK_RESULT"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @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 part-box-pad">
      <el-table
        ref="TableList"
        :data="tasks"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="printPlanName"
          label="项目"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="type" label="类别" width="160">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
        </el-table-column>
        <el-table-column prop="result" label="结果" width="100">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          prop="createName"
          label="创建人"
          min-width="80"
        ></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160px"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.hasReportFile && checkPrivilege('link', 'export')"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toDonwloadLog(scope.row)"
              >导出日志</el-button
            >
            <el-button
              v-if="
                scope.row.resetCreatePdf && checkPrivilege('link', 'createPdf')
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toResetCreatePdf(scope.row)"
              >重新生成PDF</el-button
            >
            <el-button
              v-if="
                !scope.row.resetCreatePdf && checkPrivilege('link', 'download')
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toDonwloadFile(scope.row)"
              >下载文件</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, taskResetPdf } from "../api";
import { attachmentDownload } from "../../login/api";
import { downloadByUrl } from "@/plugins/download";

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
    };
  },
  mounted() {
    this.toPage(1);
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      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, "提示", {
        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: "TASK_REPORT"
      }).catch(() => {});
      this.loading = false;

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

      const url = res.url;
      if (url.endsWith(".txt")) {
        window.open(url);
        return;
      }

      downloadByUrl(url);
      this.$message.success("文件下载成功！");
    },
    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(() => {});
      this.loading = false;

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

      downloadByUrl(res.url);
      this.$message.success("文件下载成功！");
    },
    async toResetCreatePdf(row) {
      if (this.loading) return;

      this.loading = true;
      const res = await taskResetPdf(row.id).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.$message.success("操作成功！");
      this.getList();
    }
  }
};
</script>
