<template>
  <el-dialog
    class="select-tiku-paper-dialog page-dialog"
    :visible.sync="modalIsShow"
    title="试卷选择"
    top="10vh"
    width="900px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @open="visibleChange"
  >
    <div class="part-box part-box-pad">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <el-form-item label="试卷名称：">
          <el-input
            v-model.trim="filter.paperName"
            placeholder="请输入试卷名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-checkbox v-model="youSelf">仅显示本人试卷</el-checkbox>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" @click="getList">查询</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="序号"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="name" label="试卷名称"></el-table-column>
        <el-table-column prop="createByAccount" label="命题人">
        </el-table-column>
        <el-table-column prop="paperDetailCount" label="大题数" width="65">
        </el-table-column>
        <el-table-column prop="unitCount" label="小题数" width="65">
        </el-table-column>
        <el-table-column prop="totalScore" label="试卷总分" width="80">
        </el-table-column>
        <el-table-column prop="creationTime" label="创建时间" width="160">
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="60">
          <template slot-scope="scope">
            <el-button
              :class="
                scope.row.id === row.paperId ? 'btn-success' : 'btn-primary'
              "
              type="text"
              @click="toSelect(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 v-if="showTkTips" class="tips-markedness">
      <p class="tips-info">
        请在题库-试卷列表点击生成试卷，检查试卷，确定试卷无误后点击顶部确定按钮
        <el-button
          v-if="tkAuth.hasAuth"
          type="text"
          class="btn-primary btn-link ml-2"
          @click="toTk"
          >点击跳转题库</el-button
        >
      </p>
    </div>
    <div slot="footer">
      <el-button @click="cancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import json5 from "json5";
import { tikuPaperListQuery, tikuPaperDetail } from "../../api";
import { tikuAuth } from "../../../stmms/api";

export default {
  name: "select-tiku-paper-dialog",
  props: {
    row: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      filter: {
        paperName: "",
        account: "",
      },
      youSelf: true,
      dataList: [],
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      loading: false,
      // tiku
      showTkTips: false,
      tkAuth: {
        hasAuth: false,
        role: null,
      },
    };
  },
  mounted() {
    this.checkTkAuth();
  },
  methods: {
    visibleChange() {
      this.filter = {
        paperName: "",
        account: "",
      };
      this.youSelf = true;
      this.toPage(1);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getList() {
      const datas = {
        courseId: this.row.courseId,
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (this.youSelf)
        datas.account = this.$ls.get("user", { loginName: "" }).loginName;
      const res = await tikuPaperListQuery(datas);
      this.dataList = res.records;
      this.total = res.total;
      if (this.dataList.length) {
        this.showTkTips = true;
      }
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    getPaperStruct(paperJson) {
      const structs = [];
      paperJson.details.forEach((detail) => {
        detail.questions.forEach((question) => {
          if (question.subQuestions && question.subQuestions.length) {
            question.subQuestions.forEach((subq) => {
              structs.push(
                `${detail.number}_${question.number}_${question.structType}_${subq.number}_${subq.structType}`
              );
            });
          } else {
            structs.push(
              `${detail.number}_${question.number}_${question.structType}`
            );
          }
        });
      });

      return structs.join();
    },
    async comparePaperStruct(paperIds) {
      const allFunc = paperIds.map((paperId) =>
        tikuPaperDetail({
          paperId,
          examId: this.row.examId,
          uuid: this.row.uuid,
        })
      );

      const result = await Promise.all(allFunc).catch(() => {});
      if (!result) return;

      const paperStructs = result.map((item) => {
        const paperJson = item.paperJson
          ? json5.parse(item.paperJson)
          : { details: [] };

        return this.getPaperStruct(paperJson);
      });

      const compareStruct = paperStructs[0];
      const valid = !paperStructs.some((item) => item !== compareStruct);
      return { valid };
    },
    async toSelect(row) {
      if (this.row.comparePaperId && this.row.comparePaperId !== row.id) {
        const res = await this.comparePaperStruct([
          row.id,
          this.row.comparePaperId,
        ]).catch(() => {});
        if (!res) return;
        if (!res.valid) {
          this.$message.error("试卷结构不一致，请重新选择！");
          return;
        }
      }
      this.$emit("confirm", row);
      this.cancel();
    },
    checkTkAuth() {
      const user = this.$ls.get("user");
      const userRoles = user.roleSource.filter(
        (item) => item.roleSource === "QUESTION_LIBRARY"
      );
      if (!userRoles.length) {
        this.tkAuth.hasAuth = false;
        return;
      }

      this.tkAuth.hasAuth = true;

      const stRole = userRoles.find(
        (item) => item.roleCode === "SUBJECT_TEACHER"
      );
      this.tkAuth.role = {
        ...(stRole ? stRole : userRoles[0]),
        loginName: user.loginName,
        realName: user.realName,
      };
    },
    async toTk() {
      if (this.loading) return;
      this.loading = true;
      const data = await tikuAuth({
        loginName: this.tkAuth.role.loginName,
        realName: this.tkAuth.role.realName,
        role: this.tkAuth.role.roleCode,
        returnUrl: encodeURIComponent(window.location.href),
      }).catch(() => {});
      this.loading = false;

      if (!data) return;
      window.open(data.redirectUrl);
    },
  },
};
</script>
