<template>
  <div ref="main" class="page-container">
    <back-box v-show="!isDetail">
      <template slot="title">
        <span>即时测-数据报表</span>
      </template>
      <template slot="btns">
        <el-tooltip v-if="!code && gdClass" effect="dark" content="已归档试卷" placement="bottom">
          <el-button type="primary" icon="fa fa-archive" size="mini" plain circle @click="toArchiving"></el-button>
        </el-tooltip>
      </template>
    </back-box>
    <div v-show="!isDetail" class="table-box" v-loading="loading">
      <div v-if="!isMultipleClass">
        <p class="btn-box">
          <el-button type="primary" round @click="linkToDetail2">查看汇总报表</el-button>
        </p>
        <el-table :data="tableData" :max-height="tableMaxHeight" border style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="subjectName" label="科目" align="center"></el-table-column>
          <el-table-column prop="className" label="班级" align="center"></el-table-column>
          <el-table-column prop="title" label="试卷名称" align="center"></el-table-column>
          <el-table-column prop="examPaperScore" label="卷面分" align="center"></el-table-column>
          <el-table-column label="测验人数/班级人数" align="center">
            <template slot-scope="scoped">{{ `${scoped.row.answeredNum}/${scoped.row.classPersonNum}` }}</template>
          </el-table-column>
          <el-table-column prop="examStartTime" label="测验开始时间" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scoped">
              <el-tooltip v-if="scoped.row.answerNum != 0 || scoped.row.recordStatus != 0
                " effect="dark" content="详情" placement="top">
                <el-button type="primary" circle size="mini" icon="fa fa-arrow-right"
                  @click="linkTo(scoped.row)"></el-button>
              </el-tooltip>
              <template v-if="scoped.row.answerNum == 0">
                <el-tooltip v-if="role != 'ROLE_BANZHUREN'" effect="dark" content="设置答案" placement="top">
                  <el-button type="primary" circle size="mini" icon="fa fa-file-text"
                    @click="edit(scoped.row)"></el-button>
                </el-tooltip>
                <template v-else>未设置答案</template>
              </template>
              <!-- <el-tooltip v-else effect="dark" content="答卷录分" placement="top">
                <el-button type="primary" circle size="mini" @click="openScoreSet(scoped.row)">分</el-button>
              </el-tooltip> -->
              <el-tooltip v-else effect="dark" content="答卷录分" placement="top">
                <el-button type="primary" circle size="mini" @click="openScoreSet(scoped.row)">分</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-box">
          <el-pagination small="" layout="total,prev, pager, next" :hide-on-single-page="true" :total="total"
            @current-change="changePage" :current-page="page" :page-size="size">
          </el-pagination>
        </div>
        <ScoreSet v-show="diaScoreSet" :role="role" :id="examId" :title="examTitlt" :examScore="examScore"
          @closeScoreSet="closeScoreSet" />
      </div>
      <div v-else>
        <el-table :data="tableData" :max-height="tableMaxHeight" border style="width: 100%">
          <el-table-column prop="subjectName" label="科目" align="center"></el-table-column>
          <el-table-column prop="classList" label="班级" align="center">
            <template slot-scope="scoped">
              <span v-for="(item, index) in scoped.row.classNames">{{ `${index == 0 ? '' : '/'}` + item }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="试卷名称" align="center"></el-table-column>
          <el-table-column prop="examPaperScore" label="卷面分" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scoped">
              <el-button type="primary" circle size="mini" icon="el-icon-arrow-right"
                @click="linkContrast(scoped.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-box">
          <el-pagination small="" layout="total,prev, pager, next" :hide-on-single-page="true" :total="total"
            @current-change="changePage" :current-page="page" :page-size="size">
          </el-pagination>
        </div>
      </div>
    </div>
    <router-view v-show="isDetail"></router-view>
  </div>
</template>

<script>
import ScoreSet from "./components/scoreSet.vue"
export default {
  components: {
    ScoreSet
  },
  data() {
    return {
      code: "",
      gdClass: 0, //已归档班级数量
      tableMaxHeight: null,
      role: "",
      loading: false,
      diaScoreSet: false,
      examId: "",//当前操作试卷
      examTitlt: "",//当前操作试卷名称
      examScore: 0,//当前操作试卷卷面总分
      query: {
        //搜索条件
        classId: [],
        subjectNames: [],
        startDay: "",
        endDay: "",
      },
      multipleSelection: [],
      tableData: [],
      page: 1,
      size: 20,
      total: 0,
      isMultipleClass: false,
    };
  },
  computed: {
    isDetail: function () {
      let bol = (this.$route.name == "即时测报表分析") ? true : false
      return bol
    }
  },
  async created() {
    this.code = this.$store.getters.csCode;
    this.init()
  },
  mounted() {
    this.tableMaxHeight = this.$refs.main.offsetHeight;
  },
  watch: {
    "$route.query.params": function (nVal) {
      let isFromTestDetail = sessionStorage.getItem("isFromTestDetail");
      if (!isFromTestDetail && nVal) {
        this.init()
      }
    }
  },
  methods: {
    //初始化
    init() {
      const queryData = this.$route.query.params
      queryData ? this.query = { ...this.query, ...JSON.parse(queryData) } : ''
      console.log(this.query)
      this.$store.commit('setClasses', this.query.classId.join(','))
      if (this.query.classId.length > 1) {
        this.isMultipleClass = true
      }
      this.role =
        this.$store.getters.info.showRole ||
        this.$store.getters.info.permissions[0].role;
      if (this.role != "ROLE_PERSONAL") {
        this._QueryGdClass()
      }
      this.page = 1
      this.total = 0
      this.tableData = []
      this._QueryData()
    },
    //归档列表
    toArchiving() {
      this.$router.push({
        path: "/testArchiving",
      });
    },
    //跳转单卷分析
    linkTo(obj) {
      //去详情
      this.$router.push({
        path: "/testAnalysis",
        query: {
          id: obj.id,
          title: obj.title,
          score: obj.examPaperScore || 0,
          type: 1,
          subjectName: obj.subjectName,
          classId: this.query.classId[0],
          params: this.$route.query.params
        },
      });
    },
    //汇总跳转-多卷
    linkToDetail2() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请选择试卷！")
        return
      };
      let subjectArr = []
      const ids = this.multipleSelection.map(item => {
        subjectArr.push(item.subjectName)
        return item.id
      })
      subjectArr = [...new Set(subjectArr)]
      console.log(subjectArr)
      if (ids.length == 1) {
        this.$router.push({
          path: "/testAnalysis",
          query: {
            id: ids[0],
            title: this.multipleSelection[0].title,
            score: this.multipleSelection[0].examPaperScore || 0,
            type: 1,
            subjectName: subjectArr.join(),
            classId: this.query.classId[0],
            params: this.$route.query.params
          },
        });
      } else {
        //去详情
        this.$router.push({
          path: "/testAnalysis",
          query: {
            ids: ids.join(),
            classId: this.query.classId[0],
            type: subjectArr.length == 1 ? 2 : 3,
            subjectName: subjectArr.join(),
            params: this.$route.query.params
          },
        });
      }
    },
    // 多班对比
    linkContrast(obj) {
      console.log(obj)
      this.$router.push({
        path: "/testAnalysis",
        query: {
          ids: obj.ids.join(','),
          classId: obj.classIds.join(','),
          subjectName: obj.subjectName,
          title: obj.title,
          type: 4
        },
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //打开答卷录分
    openScoreSet(obj) {
      this.examId = obj.id;
      this.examTitlt = obj.title;
      this.examScore = obj.examScore;
      this.diaScoreSet = true;
    },
    //关闭设置分数
    closeScoreSet() {
      this.diaScoreSet = false
    },
    //修改答案
    edit(item) {
      this.$router.push({
        path: "/examinationPaperEdit",
        query: {
          paperId: item.id,
          title: item.title,
          type: 2,
        },
      });
    },

    async _QueryGdClass() {
      const fetchClassList =
        this.role == "ROLE_BANZHUREN"
          ? this.$request.cTClassList
          : this.$request.tClassList;
      const { data, status, info } = await fetchClassList({ status: 1 });
      if (status === 0) {
        this.gdClass = data?.list?.length || 0;
      } else {
        this.$message.error(info);
      }
    },
    changePage(page) {
      this.page = page;
      this._QueryData();
    },
    async _QueryData() {
      this.loading = true;
      let query = {};
      for (let key in this.query) {
        if (this.query[key] != "") {
          if (key == 'classId') {
            if (this.query.classId?.length == 1) {
              query.classId = this.query[key][0]
            } else {
              query.classIds = [...this.query[key]]
            }
          } else {
            query[key] = this.query[key];
          }
        }
      }
      const examReportList = this.role == "ROLE_PERSONAL" ?
        this.$request.pExamReportList : this.$request.examReportList
      const { data, status, info } = await examReportList({
        ...query,
        page: this.page,
        size: this.size,
      });
      this.loading = false;
      if (status === 0) {
        if (this.query.classId.length > 1) {
          //多班级
          let tableObj = {};
          data?.list?.map((item) => {
            if (tableObj[item.examPaperId]) {
              tableObj[item.examPaperId].ids.push(item.id)
              tableObj[item.examPaperId].classIds.push(item.classId)
              tableObj[item.examPaperId].classNames.push(item.className)
            } else {
              tableObj[item.examPaperId] = {
                ids: [item.id],
                examPaperId: item.examPaperId,
                classIds: [item.classId],
                classNames: [item.className],
                title: item.title,
                examPaperScore: item.examPaperScore,
                subjectName: item.subjectName
              }
            }
          });
          Object.keys(tableObj).map(keys => {
            if (tableObj[keys].classIds.length > 1) {
              this.tableData.push(tableObj[keys])
            }
          })
        } else {
          this.tableData = (data?.list && [...data?.list]) || [];
          this.total = data?.count || 0;
        }
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>

<style>
div::-webkit-scrollbar {
  width: 3px;
  height: 10px;
}

div::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #ccc;
}
</style>
<style lang="scss" scoped>
.page-container {
  position: relative;
  height: 100%;

  &.active {
    overflow: hidden;
  }
}

.table-box {
  margin: 20px;
  border-radius: 5px;

  :deep(.fa-arrow-right) {
    padding-left: 2px;
  }

  :deep(.fa-file-text) {
    padding-left: 2px;
  }
}

.down {
  padding-top: 16px;
}

.click-b {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}

.btn-box {
  text-align: right;
  padding: 0 12px 16px;
}
</style>