<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="checkPrivilege('condition', 'condition')">
          <el-form-item label="同步类型：">
            <el-select v-model="filter.type" placeholder="同步类型" clearable>
              <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="checkPrivilege('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="thirdRelateId"
          label="云阅卷考试ID"
        ></el-table-column>
        <el-table-column prop="objectId" label="同步对象ID"></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 && checkPrivilege('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,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </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 { enumsByType } from "../../base/api";
import { downloadByUrl } from "@/plugins/download";

export default {
  name: "sync-manage",
  data() {
    return {
      STMMS_SYNC_TYPE: {},
      STMMS_SYNC_STATUS: {},
      DATA_TASK_RESULT,
      filter: {
        result: "",
        type: "",
        status: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      loading: false
    };
  },
  created() {
    this.getSyncTypes();
    this.getSyncStatus();
    this.getList();
  },
  methods: {
    async getSyncTypes() {
      const res = await enumsByType("PUSH_TYPE_ENUM");
      const data = res || [];
      this.STMMS_SYNC_TYPE = {};
      data.forEach(item => {
        this.STMMS_SYNC_TYPE[item.name] = item.desc;
      });
    },
    async getSyncStatus() {
      const res = await enumsByType("TB_TASK_STATUS");
      const data = res || [];
      this.STMMS_SYNC_STATUS = {};
      data.forEach(item => {
        this.STMMS_SYNC_STATUS[item.name] = item.desc;
      });
    },
    async getList() {
      if (!this.checkPrivilege("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>
