<template>
  <div class="sync-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" inline>
        <template v-if="checkPriv('condition', 'condition')">
          <secp-select
            v-model="filter"
            defaultSelectExam
            @exam-default="toPage(1)"
          ></secp-select>
          <el-form-item label="同步类型：">
            <el-select
              v-model="filter.type"
              placeholder="同步类型"
              clearable
              :disabled="typeDisabled"
              style="width: 300px"
            >
              <el-option
                v-for="(val, key) in STMMS_SYNC_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>
              <el-option
                v-for="(val, key) in STMMS_SYNC_STATUS"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="同步结果：">
            <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 label-width="0px">
          <el-button
            v-if="checkPriv('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="dataList">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="semesterName"
          label="学期"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          min-width="100"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程（代码）" min-width="200">
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类别"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
        </el-table-column>
        <el-table-column prop="resultStr" label="结果" width="80">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.result === 'ERROR'"
              placement="left-start"
              popper-class="answer-popover"
              width="400"
              trigger="hover"
            >
              <p class="text-prewrap" v-html="scope.row.errorMessage"></p>
              <span class="color-danger" slot="reference">{{
                scope.row.resultStr
              }}</span>
            </el-popover>
            <p v-else class="color-success">{{ scope.row.resultStr }}</p>
          </template>
        </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="创建人"
          width="140"
        ></el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.hasReportFile && checkPriv('link', 'export')"
              type="text"
              class="btn-primary"
              :disabled="loading"
              @click="toDonwloadLog(scope.row)"
              >导出日志</el-button
            >
            <el-button
              v-if="scope.row.result === 'ERROR'"
              type="text"
              class="btn-primary"
              :disabled="loading"
              @click="toResync(scope.row)"
              >重新同步</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>
  </div>
</template>

<script>
import { DATA_TASK_RESULT } from "@/constants/enumerate";
import { syncResultListPage, syncResync } from "../api";
import { attachmentDownload } from "../../login/api";
import { getEnums } from "../../base/api";
import { downloadByUrl } from "@/plugins/download";

export default {
  name: "sync-manage",
  props: {
    syncType: {
      type: String,
      default: "",
    },
    nonePrivilege: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      STMMS_SYNC_TYPE: {},
      STMMS_SYNC_STATUS: {},
      DATA_TASK_RESULT,
      filter: {
        semesterId: "",
        examId: "",
        courseCode: "",
        paperNumber: "",
        result: "",
        type: "",
        status: "",
      },
      typeDisabled: false,
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      loading: false,
    };
  },
  created() {
    if (this.syncType) {
      this.filter.type = this.syncType;
      this.typeDisabled = true;
    }
    this.getSyncTypes();
    this.getSyncStatus();
  },
  methods: {
    checkPriv(type, field) {
      return this.nonePrivilege || this.checkPrivilege(type, field);
    },
    async getSyncTypes() {
      const res = await getEnums("PUSH_TYPE_ENUM");
      const data = res || [];
      this.STMMS_SYNC_TYPE = {};
      data.forEach((item) => {
        this.STMMS_SYNC_TYPE[item.code] = item.name;
      });
    },
    async getSyncStatus() {
      const res = await getEnums("TB_TASK_STATUS");
      const data = res || [];
      this.STMMS_SYNC_STATUS = {};
      data.forEach((item) => {
        this.STMMS_SYNC_STATUS[item.code] = item.name;
      });
    },
    async getList() {
      if (!this.checkPriv("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await syncResultListPage(datas);
      this.dataList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async toDonwloadLog(row) {
      if (this.loading) return;

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

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

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

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

      this.loading = true;
      const res = await syncResync(row.id).catch(() => false);
      this.loading = false;

      if (!res) return;
      this.$message.success("操作成功！");
    },
  },
};
</script>
