<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="checkPriv('condition', 'condition')">
          <secp-select
            v-if="!nonePrivilege"
            v-model="filter"
            @exam-default="toPage(1)"
          ></secp-select>
          <el-form-item label="类别：">
            <el-select
              v-model="filter.type"
              placeholder="类别"
              clearable
              filterable
              :disabled="typeDisabled"
              style="width: 300px"
            >
              <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="状态：">
            <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="数据结果：" 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="checkPriv('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>
        <template v-if="!nonePrivilege">
          <el-table-column
            prop="semesterName"
            label="学期"
            min-width="210"
          ></el-table-column>
          <el-table-column
            prop="examName"
            label="考试"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="courseName"
            label="课程（代码）"
            min-width="260"
          >
            <template slot-scope="scope">
              {{ scope.row.courseName | defaultFieldFilter }}（{{
                scope.row.courseCode | defaultFieldFilter
              }}）
            </template>
          </el-table-column>
          <el-table-column prop="paperNumber" label="试卷编号" min-width="100"
            ><template slot-scope="scope">
              {{ scope.row.paperNumber | defaultFieldFilter }}
            </template></el-table-column
          >
        </template>

        <el-table-column prop="type" label="类别" width="160">
        </el-table-column>
        <el-table-column
          v-if="showPlanName"
          prop="printPlanName"
          label="印刷计划"
          min-width="200"
        >
        </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="160"
        ></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPriv('link', 'export')"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toViewLog(scope.row)"
              >日志详情</el-button
            >
            <el-button
              v-if="scope.row.hasResultFile && checkPriv('link', 'download')"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toDonwloadFile(scope.row.id, scope.row.downloadType)"
              >下载文件</el-button
            >
            <el-button
              v-if="scope.row.hasErrorFile"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toDonwloadFile(scope.row.id, 'ERROR_FILE')"
              >下载错误文件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      class="log-dialog"
      :visible.sync="modalIsShow"
      title="日志"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      top="10vh"
      width="800px"
    >
      <div style="min-height: 300px; overflow: auto">
        <p v-for="(cont, cidx) in logList" :key="cidx">{{ cont }}</p>
      </div>
    </el-dialog>
  </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 { downloadByUrl } from "@/plugins/download";

export default {
  name: "data-task-manage",
  props: {
    taskType: {
      type: String,
      default: "",
    },
    nonePrivilege: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        courseId: "",
        paperNumber: "",
        type: "",
        status: "",
        result: "",
      },
      typeDisabled: false,
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      DATA_TASK_STATUS,
      DATA_TASK_TYPE,
      DATA_TASK_RESULT,
      tasks: [],
      curTask: {},
      multipleSelection: [],
      loading: false,
      // log dialog
      modalIsShow: false,
      logList: [],
    };
  },
  computed: {
    showPlanName() {
      return ["EXAMINATION_IMPORT"].includes(this.taskType);
    },
  },
  mounted() {
    if (this.taskType) {
      this.filter.type = this.taskType;
      this.typeDisabled = true;
    }
    if (this.nonePrivilege) {
      this.toPage(1);
    }
  },
  methods: {
    checkPriv(type, field) {
      return this.nonePrivilege || this.checkPrivilege(type, field);
    },
    async getList() {
      if (!this.checkPriv("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 toDonwloadFile(id, type) {
      if (this.loading) return;

      this.loading = true;
      const res = await attachmentDownload({
        id,
        type,
      }).catch(() => {});
      this.loading = false;

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

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

      downloadByUrl(res.url);
      this.$message.success("文件下载成功！");
    },
    toViewLog(row) {
      this.logList = (row.summary || "").split("\n");
      this.modalIsShow = true;
    },
  },
};
</script>
