<template>
  <div class="app-container">
    <div class="tab-wrapper">
      <div class="item" :class="{ active: active == 1 }" @click="active = 1, queryParams.pageNum = 1">学员数据</div>
      <div class="item" :class="{ active: active == 2 }" @click="active = 2, queryParams.pageNum = 1">试题数据</div>
    </div>
    <!-- 表单  -->
    <el-form :model="queryParams" ref="formData" inline size="mini">
      <el-form-item label="姓名" prop="userName" v-if="active == 1">
        <el-input v-model="queryParams.userName" clearable placeholder="请输入姓名" v-no-whitespace />
      </el-form-item>
      <!-- 是否及格 -->
      <el-form-item label="是否及格" prop="isPass" v-if="active == 1">
        <el-select v-model="queryParams.isPass" clearable placeholder="请选择是否及格">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <!-- 题目名称 -->
      <el-form-item label="题目名称" prop="content" v-if="active == 2">
        <el-input v-model="queryParams.content" clearable placeholder="请输入题目名称"  v-no-whitespace/>
      </el-form-item>
      <!-- 题目类型 -->
      <el-form-item label="题目类型" prop="questionType" v-if="active == 2">
        <el-select v-model="queryParams.questionType" clearable placeholder="请选择题目类型">
          <el-option label="单选题" value="1" />
          <el-option label="多选题" value="2" />
          <el-option label="判断题" value="3" />
          <el-option label="简答题" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport">导出数据</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-if="active == 1" :data="tableData" fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      ></el-table-column>
      <el-table-column
        v-for="item in taskTableHeader"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        align="center"
      >
        <template v-slot="scope" v-if="item.prop === 'sex'">
          <span>{{ scope.row.sex == 1 ? '女' : '男' }}</span>
        </template>
        <template v-slot="scope" v-else-if="item.prop === 'isPass'">
          <span v-if="scope.row.isPass == '0'">不及格</span>
          <span v-else-if="scope.row.isPass == '1'">及格</span>
          <span v-else-if="!scope.row.isPass">-</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDetails(scope.row)">试卷详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table v-if="active == 2" :data="tableData2" fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      ></el-table-column>
      <el-table-column
        v-for="item in taskTableHeader2"
        show-overflow-tooltip
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        align="center"
      >
        <template v-slot="scope" v-if="item.prop === 'questionType'">
          <span>{{ getQuestionLabel(scope.row.questionType) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 试卷详情弹框 -->
    <el-dialog title="试卷详情" :visible.sync="dialogVisible" width="66%">
      <el-row :gutter="20">
        <!-- 左侧答题卡 -->
        <el-col :span="6" :offset="0">
          <el-card class="box-card">
            <div class="top-content">
              <div class="title">答题卡</div>
            </div>
            <div class="tab-wrapper">
              <div class="item" :class="{ active: dialogActive == 1 }" @click="dialogActive = 1">
                全部（{{ paperDetail.allQuestionNum }}）
              </div>
              <div class="item" :class="{ active: dialogActive == 2 }" @click="dialogActive = 2">
                错题（{{ paperDetail.errorNum }}）
              </div>
            </div>
            <!-- 正确,错误,未答 三种颜色提示 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="8">
                <div class="color-box" style="background-color: #67c23a"></div>
                <span>正确</span>
              </el-col>
              <el-col :span="8">
                <div class="color-box" style="background-color: #f56c6c"></div>
                <span>错误</span>
              </el-col>
              <el-col :span="8">
                <div class="color-box" style="background-color: #909399"></div>
                <span>未答</span>
              </el-col>
            </el-row>
            <!-- 单选题 -->
            <el-row :gutter="10" class="mb8">
              <div style="margin: 5px">单选题</div>
              <el-col :span="4.8" v-for="(item, index) in singleTopic" :key="index">
                <div style="margin-bottom: 5px">
                  <el-tag v-if="item.isPass" type="success">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isError" type="danger">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isNotAnswer" type="info">{{ item.topicNum }}</el-tag>
                </div>
              </el-col>
            </el-row>
            <!-- 多选题 -->
            <el-row :gutter="10" class="mb8">
              <div style="margin: 5px">多选题</div>
              <el-col :span="4.8" v-for="(item, index) in multipleTopic" :key="index">
                <div style="margin-bottom: 5px">
                  <el-tag v-if="item.isPass" type="success">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isError" type="danger">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isNotAnswer" type="info">{{ item.topicNum }}</el-tag>
                </div>
              </el-col>
            </el-row>
            <!-- 判断题 -->
            <el-row :gutter="10" class="mb8">
              <div style="margin: 5px">判断题</div>
              <el-col :span="4.8" v-for="(item, index) in judgeTopic" :key="index">
                <div style="margin-bottom: 5px">
                  <el-tag v-if="item.isPass" type="success">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isError" type="danger">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isNotAnswer" type="info">{{ item.topicNum }}</el-tag>
                </div>
              </el-col>
            </el-row>
            <!-- 简答题 -->
            <el-row :gutter="10" class="mb8">
              <div style="margin: 5px">简答题</div>
              <el-col :span="4.8" v-for="(item, index) in shortAnswerTopic" :key="index">
                <div style="margin-bottom: 5px">
                  <el-tag v-if="item.isPass" type="success">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isError" type="danger">{{ item.topicNum }}</el-tag>
                  <el-tag v-if="item.isNotAnswer" type="info">{{ item.topicNum }}</el-tag>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <!-- 右侧试卷详情 -->
        <el-col :span="18" :offset="0">
          <el-card class="box-card">
            <div class="top-content">
              <div class="title">{{ paperData.paperName }}</div>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="20">
                <el-row :gutter="10" class="mb8">
                  <el-col :span="4">
                    <div>总分：{{ paperData.totalScore }}</div>
                  </el-col>
                  <el-col :span="4">
                    <div>及格分：{{ paperData.passScore }}</div>
                  </el-col>
                  <el-col :span="4">
                    <div>试题数：{{ paperData.topicNum }}</div>
                  </el-col>
                </el-row>
                <!-- 试卷说明 -->
                <el-row :gutter="10" class="mb8">
                  <el-col :span="20">
                    <div>试卷说明：{{ paperData.topicExplain }}</div>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="4" style="display: flex; justify-content: flex-end">
                <div
                  class="score-wrapper"
                  v-if="paperData.submitTime"
                  :class="{ 'is-not-pass': paperData.score < paperData.passScore }"
                >
                  <div>{{ paperData.score }}</div>
                  <div>{{ paperData.score < paperData.passScore ? '不及格' : '及格' }}</div>
                </div>
                <div class="score-wrapper" v-else style="background: #ff9040">
                  <div>{{ paperData.score }}</div>
                  <div>{{ '未作答' }}</div>
                </div>
              </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-row :gutter="5" class="mb8">
              <el-col :span="3">
                <div>
                  姓名：
                  <span class="top-item">{{ paperData.name }}</span>
                </div>
              </el-col>
              <el-col :span="5">
                <div>
                  部门：
                  <span class="top-item">{{ paperData.department }}</span>
                </div>
              </el-col>
              <el-col :span="3">
                <div>
                  得分：
                  <span class="top-item">{{ paperData.score }}</span>
                </div>
              </el-col>
              <el-col :span="3">
                <div>
                  得分率：
                  <span class="top-item">{{ paperData.scoreRate }}</span>
                </div>
              </el-col>
              <el-col :span="5">
                <div>
                  作答用时：
                  <span class="top-item">{{ (paperData.answerTime / 60).toFixed(2) }}分钟</span>
                </div>
              </el-col>
              <el-col :span="5">
                <div>
                  交卷时间：
                  <span class="top-item">{{ paperData.submitTime }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>
          <el-card v-for="(item, index) in paperDetailDataList" :key="index" style="margin-bottom: 10px">
            <el-row :gutter="1">
              <el-col :span="3" :offset="0">
                <div v-if="item.topicType == 1">{{ item.topicNum }}.【单选题】</div>
                <div v-if="item.topicType == 2">{{ item.topicNum }}.【多选题】</div>
                <div v-if="item.topicType == 3">{{ item.topicNum }}.【判断题】</div>
                <div v-if="item.topicType == 4">{{ item.topicNum }}.【简答题】</div>
              </el-col>
              <el-col :span="18" :offset="0">
                <div>{{ item.topicName }}</div>
              </el-col>
              <el-col :span="3" :offset="0">
                <div>（{{ item.topicScore }}分）</div>
              </el-col>
            </el-row>
            <el-row>
              <div class="question-img-list">
                <div class="img" v-for="(img, imgIndex) in item.questionPictureVoList">
                  <el-image
                    :key="imgIndex"
                    :src="img.url"
                    :showLoading="true"
                    width="60px"
                    height="60px"
                    :preview-src-list="[img.url]"
                  />
                </div>
              </div>
            </el-row>
            <!-- 选项 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="24">
                <el-row
                  :gutter="10"
                  class="mb8"
                  style="margin-left: 10px; font-weight: bold"
                  v-for="(opt, optIndex) in item.topicOption"
                  :key="optIndex"
                >
                  <el-col :span="24">
                    <div>{{ opt.option }}.{{ opt.value }}</div>
                    <div class="question-img-list">
                      <div class="img" v-for="(img, imgIndex) in opt.questionPictureVoList">
                        <el-image
                          :key="imgIndex"
                          :src="img.url"
                          :showLoading="true"
                          width="60px"
                          height="60px"
                          :preview-src-list="[img.url]"
                        />
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-col :span="8">
                <div>
                  正确答案：
                  <span class="top-item">{{ item.topicAnswer }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  你的答案：
                  <span class="top-item">{{ item.yourAnswer }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-col :span="24">
                <div class="analysis">
                  <div class="is-analysis">解析:</div>
                  <div>{{ item.topicAnalysis }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getExamPaperDetail,
  getExamPaperQuestions,
  getTaskUsers,
} from '@/api/educationalTraining/resourceAdministration'
import { StrUtil } from '@/utils/StrUtil'
import { indexContinuous, lookFile } from '@/utils/bonus'

export default {
  data() {
    return {
      active: 1,
      showSearch: true,
      currentRow: {}, // 当前行数据
      examPaperId: '', // 试卷ID
      examTaskId: '', // 考试任务ID
      paperDetail: {},
      trainTopicName: '歇息', // 培训主题名称
      trainObject: '外委单位', // 学习对象
      trainLevel: '公司级', // 培训级别
      trainDate: '2021-08-01', // 培训日期
      shouldNumber: '30', // 应到人数
      actualNumber: '30', // 实到人数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        isPass: '', // 是否及格
        content: '', // 题目名称
        questionType: '', // 题目类型
        taskType: '3',
      },
      total: 0, // 总条数
      // 列表-表格头
      taskTableHeader: [
        { prop: 'name', label: '姓名' },
        { prop: 'sex', label: '性别' },
        { prop: 'idCard', label: '身份证号码' },
        { prop: 'phone', label: '联系方式' },
        { prop: 'proName', label: '工程名称' },
        { prop: 'subName', label: '承包商名称' },
        { prop: 'typeOfWork', label: '岗位' },
        { postName: 'workType', label: '工种' },
        { prop: 'score', label: '考试成绩' },
        { prop: 'isPass', label: '是否及格' },
      ],
      // 列表-数据
      tableData: [],
      taskTableHeader2: [
        { prop: 'content', label: '题目名称' },
        { prop: 'questionType', label: '题型' },
        { prop: 'correctAnswer', label: '正确答案' },
        { prop: 'correctNum', label: '正确人数' },
        { prop: 'errorNum', label: '错误人数' },
      ],
      tableData2: [],
      dialogVisible: false, // 试卷详情弹框
      dialogActive: 1, // 1全部 2错题
      allTopicNum: 0, // 全部题数
      errorTopicNum: 0, // 错题数
      // 单选题
      singleTopic: [],
      // 多选题
      multipleTopic: [],
      // 判断题
      judgeTopic: [],
      // 简答题
      shortAnswerTopic: [],
      // 试卷数据
      paperData: {},
      // 试卷详情数据-列表
      paperDetailDataList: [],
    }
  },
  created() {
    // 获取路由query 传递过来 JSON.parse(this.$route.query.data)

    this.examPaperId = this.$route.query.examPaperId || ''
    this.examTaskId = this.$route.query.examTaskId || ''
    console.log('学习任务数据', this.examPaperId)
    this.getList()
  },
  watch: {
    active() {
      this.getList()
    },
  },
  methods: {
    indexContinuous,
    // 查询
    handleQuery() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.formData.resetFields()
      this.getList()
    },
    getQuestionLabel(type) {
      switch (type) {
        case '1':
          return '单选题'
        case '2':
          return '多选题'
        case '3':
          return '判断题'
        case '4':
          return '简答题'
        default:
          return ''
      }
    },
    // 导出
    handleExport() {
      console.log('导出')
      try {
        let fileName = ''
        let url = ''
        if (this.active === 1) {
          this.queryParams.examTaskId = this.examTaskId
          fileName = `学员数据_${new Date().getTime()}.xLsx`
          url = '/exam/examTask/exportTaskUsers'
        } else {
          this.queryParams.examPaperId = this.examPaperId
          fileName = `试题数据_${new Date().getTime()}.xLsx`
          url = '/exam/examTask/exportExamPaperQuestions'
        }
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 获取列表
    getList() {
      try {
        console.log('查询参数-列表', this.queryParams)
        // const res =
        // this.tableData = res.rows

        if (this.active === 1) {
          this.queryParams.examTaskId = this.examTaskId
          getTaskUsers(this.queryParams).then(res => {
            console.log('学员数据', res)
            this.tableData = res.rows
            this.total = res.total
          })
        } else {
          this.queryParams.examPaperId = this.examPaperId
          getExamPaperQuestions(this.queryParams).then(res => {
            console.log('试题数据', res)
            this.tableData2 = res.rows
            this.total = res.total
          })
        }
      } catch (error) {
        console.log('获取列表失败', error)
      }
    },
    setQuestionOption: function (questionVos, i, questionType) {
      const topicNum = i + 1
      const chooseAnswer = questionVos[i].chooseAnswer
      const correctAnswer = questionVos[i].correctAnswer
      const isPass = chooseAnswer === correctAnswer
      const isNotAnswer = StrUtil.isEmptyOrNull(chooseAnswer)
      const isError = !isPass && !isNotAnswer

      const topicData = { topicNum, isPass, isError, isNotAnswer }
      switch (questionType) {
        case 1:
          this.singleTopic.push(topicData)
          console.log('this.singleTopic:' + this.singleTopic)
          break
        case 2:
          this.multipleTopic.push(topicData)
          console.log('this.multipleTopic:' + this.multipleTopic)
          break
        case 3:
          this.judgeTopic.push(topicData)
          console.log('this.judgeTopic:' + this.judgeTopic)
          break
        case 4:
          this.shortAnswerTopic.push(topicData)
          console.log('this.shortAnswerTopic:' + this.shortAnswerTopic)
          break
      }
      console.log('topicData:' + topicData)

      const paperDetailData = {
        topicNum,
        topicType: questionType,
        topicName: questionVos[i].content,
        topicScore: questionVos[i].score,
        topicAnswer: correctAnswer,
        yourAnswer: chooseAnswer,
        topicAnalysis: questionVos[i].analysis,
        questionAnswerVoList: questionVos[i].questionAnswerVoList,
        questionPictureVoList: questionVos[i].questionPictureVoList,
        topicOption: questionVos[i].questionAnswerVoList.map(opt => ({
          option: opt.options,
          value: opt.answerOptions,
          questionPictureVoList: opt.questionPictureVoList,
        })),
      }
      this.paperDetailDataList.push(paperDetailData)
    },

    // 试卷详情
    handleDetails(row) {
      console.log('试卷详情', row)
      getExamPaperDetail({ examPaperId: this.examPaperId, userUuid: row.userUuid, userId: row.userId }).then(res => {
        console.log('试卷详情数据', res)
        this.paperDetail = res.data
        let questionVos = this.paperDetail.questionVos
        this.paperDetail.questionVos.forEach((item, index) => {
          item.questionAnswerVoList.forEach((opt, optIndex) => {
            opt.questionPictureVoList.forEach((pic, picIndex) => {
              pic.url = lookFile() + pic.pictureUrl
            })
          })
          item.questionPictureVoList.forEach((pic, picIndex) => {
            pic.url = lookFile() + pic.pictureUrl
          })
        })
        this.paperData = {
          totalScore: res.data.totalScore,
          passScore: res.data.passScore,
          topicNum: res.data.allQuestionNum,
          topicExplain: res.data.statement,
          score: res.data.score,
          name: res.data.userName,
          department: res.data.deptName,
          scoreRate: res.data.scoreRate,
          answerTime: res.data.answerTime,
          submitTime: res.data.handPaper,
        }
        this.singleTopic = []
        this.multipleTopic = []
        this.judgeTopic = []
        this.shortAnswerTopic = []
        this.paperDetailDataList = []
        for (let i = 0; i < questionVos.length; i++) {
          this.setQuestionOption(questionVos, i, Number(questionVos[i].questionType))
        }
        console.log('试卷详情数据', JSON.stringify(this.paperDetailDataList))
        console.log('试卷详情数据', JSON.stringify(this.singleTopic))
        console.log('试卷详情数据', JSON.stringify(this.multipleTopic))
        console.log('试卷详情数据', JSON.stringify(this.judgeTopic))
        console.log('试卷详情数据', JSON.stringify(this.shortAnswerTopic))
        this.dialogVisible = true
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}

.top-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;

  .title {
    font-size: 15px;
    font-weight: bold;
  }

  .lf-line {
    width: 2px;
    height: 20px;
    background-color: #ccc;
    margin: 0 20px;
  }
}

.tab-wrapper {
  display: flex;
  justify-content: flex-start;
  padding: 10px;
  margin-bottom: 20px;

  .item {
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 5px;
    border: 1px solid #409eff;
    margin-right: 10px;

    &.active {
      background-color: #409eff;
      color: #fff;
    }
  }
}

.color-box {
  width: 10px;
  height: 10px;
  display: inline-block;
  margin-right: 5px;
}

.score-wrapper {
  width: 60px;
  height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center; // 垂直居中
  align-items: center;
  text-align: right;
  background: #67c23a;
  border-radius: 50%;
  color: #fff;
  font-size: 13px;
  // 不及格整体背景色
  &.is-not-pass {
    background: #f56c6c;
  }
}

.top-item {
  color: #409eff;
}

.analysis {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 10px;

  .is-analysis {
    margin-bottom: 10px;
    width: 60px;
    text-align: center;
    background: #f56c6c;
    border-radius: 10px;
  }
}

.question-img-list {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  margin-top: 10px;
}
.img {
  margin-right: 10px;
  width: 60px;
  height: 60px;
}
</style>
