<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<template>
  <div class="v-page classify_page">
    <div class="v-ctx" v-loading="paper_list_loading">
      <FormLayout
        ref="formLayoutRef"
        :items="formItems"
        :model="form"
        :rules="rules"
        label-width="70px"
        label-position="right"
        :inline="true"
      >
        <template v-slot:title>
          <QueryInput v-model="form.title" @query="pagingFindList"></QueryInput>
        </template>
        <template v-slot:btns>
          <el-button round type="primary" @click="createSimuTest"
          >新建考试</el-button
          >
        </template>
      </FormLayout>
      <TableLayout
        :column="column"
        :data="table_data"
        :pageInfo="page_info"
        @current-change="(e) => pagingChange({ currentPage: e })"
        @size-change="(e) => pagingChange({ pageSize: e })"
      >
        <template v-slot:examStartTime="props">
          <div>
            <p>开始时间：{{ props.row.examStartTime }}</p>
            <p>结束时间：{{ props.row.examEndTime }}</p>
          </div>
        </template>
        <template v-slot:passPercent="props">
          <p>
          {{
            Math.round((props.row.passPercent * props.row.totalScore) / 100)
            }}
            </p>
        </template>
        <template v-slot:myDuration="props">
          <p>{{ formatTime(props.row.myDuration) }}</p>
        </template>
        <template v-slot:status="props">
          <div
            :style="{
              'background-color': ['#208ac6', '#01c883', '#999999'][
              props.row.status
              ],
            }"
            class="exam-status"
          >
            {{ ["待开考", "已开始", "已结束"][props.row.status] }}
          </div>
        </template>
        <template v-slot:action="props">
          <!-- <el-button type="text" icon="el-icon-edit">{{ props.row.type }}</el-button> -->
          <el-button
            type="text"
            icon="i-x-zxks-canjiakaoshi"
            style="color: #02c761 !important"
            v-if="props.row.status == 1"
            @click="toExamHandler(1, props.row)"
            >参加考试</el-button
          >
          <el-button
          type="text"
          icon="i-j-fbks-yulan"
          @click="lookLastExam(props.row)"
            >查看答卷
          </el-button>
          <el-button
            class="print-icon"
            type="text"
            icon="el-icon-printer"
            @click="toPrint(props.row)"
            >打印
          </el-button>
          <el-button
            type="text"
            icon="i-j-ksap-shanchu"
            @click="deletePapers($event, props.row)"
            style="color: #f04343 !important"
            >删除</el-button
          >
        </template>
      </TableLayout>
    </div>
  </div>
</template>

<script>
import { TableLayout, FormLayout } from '@/components/layout'
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import {
  createExamHistoryApi,
  getLastedHistoryApi,
  createSimExamHistoryApi
} from '@/api/assessment-evaluation/onlineTest'
import {
  pagingFindSimPaperApi,
  deleteSomePapersApi
} from '@/api/assessment-evaluation/paper'
import QueryInput from '@/components/widget/QueryInput.vue'
import { dataReportMixin } from '@/utils/data-report'
export default {
  components: {
    TableLayout,
    FormLayout,
    QueryInput
  },

  data: () => ({
    table_data: [],
    page_info: { currentPage: 1, pageSize: 10, total: 0 },
    // 试题分类树是否加载中
    paper_list_loading: false,
    form: { title: '', isPractive: 1 },
    is_show_info: false,
    exam_info_dialog_show: false,
    current_exam: null
  }),

  created () {
    this.formItems = [
      { prop: 'title' },
      { prop: 'btns', model: { class: 'gy-btns' } }
    ]
    this.rules = {
      // name: { required: true, message: '请输入角色名称', trigger: 'blur' }
    }
    this.column = [
      {
        prop: 'title',
        label: '试卷名',
        align: 'center',
        'show-overflow-tooltip': true
      },
      // { prop: 'classify', label: '试卷分类', align: 'center', 'show-overflow-tooltip': true },
      {
        prop: 'totalScore',
        label: '总分',
        'min-width': 50,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'passPercent',
        label: '及格分',
        'min-width': 50,
        align: 'center',
        'show-overflow-tooltip': true
      },
      // { prop: 'questionCount', label: '试题总数', align: 'center', 'show-overflow-tooltip': true },
      // { prop: 'creator', label: '创建人', align: 'center', 'show-overflow-tooltip': true },
      {
        prop: 'myScore',
        label: '成绩',
        'min-width': 50,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'myDuration',
        label: '考试用时',
        'min-width': 80,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'mistakes',
        label: '错题',
        'min-width': 50,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 150,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'action',
        label: '操作',
        //  width: 350,
        width: 300,
        align: 'center',
        'show-overflow-tooltip': true
      }
    ]
  },
  activated () {
    this.pagingFindList()
  },
  methods: {
    /*
      删除试卷回调
    */
    deletePapers (e, examItem) {
      let delList = this.tableSelectionsList
      if (examItem) {
        delList = [examItem]
      }
      const tipsText = '确认删除吗?'
      this.$confirm(tipsText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // eslint-disable-next-line prefer-promise-reject-errors
      })
        .then((res) => {
          this.paper_list_loading = true
          deleteSomePapersApi(delList.map((_) => _.id)).then((res) => {
            this.pagingFindList()
            this.paper_list_loading = false
          })
        })
        .catch((_) => {})
    },
    /*
      创建新的模拟测试页面
    */
    createSimuTest () {
      this.$router.push({
        path: '/assessment-evaluation/simulation-test/add-sim-test'
      })
    },
    /*
      最后一次考试记录信息
    */
    lookLastExam (row) {
      this.paper_list_loading = true
      getLastedHistoryApi(row.studentOnlineExamId)
        .then((res) => {
          if (res.data == null) {
            return this.$message.error('该场考试没有查询到您的考试记录')
          }
          this.$router.push({
            path:
              '/assessment-evaluation/online-test/begin-online-exam/' +
              res.data.id,
            query: { preview: 1 }
          })
        })
        .finally((_) => {
          this.paper_list_loading = false
        })
    },
    formatTime (msTime) {
      const time = msTime / 1000
      let hour = Math.floor(time / 60 / 60)
      hour = hour.toString().padStart(2, '0')
      let minute = Math.floor(time / 60) % 60
      minute = minute.toString().padStart(2, '0')
      let second = Math.floor(time) % 60
      second = second.toString().padStart(2, '0')
      return `${hour}:${minute}:${second}`
    },
    /*
      去考试检测
    */
    toExamPaper () {
      if (this.is_show_info) {
        this.exam_info_dialog_show = false
      } else if (+this.current_exam.status === 1) {
        if (this.current_exam?.examTimes - this.current_exam?.myTimes <= 0) { return this.$message.error('您已没有该场考试的考试机会') }
        createExamHistoryApi({ onlineExamId: this.current_exam.id }).then(
          (res) => {
            if (res.data) {
              this.$message('开始考试，本次考试将计入考试次数')
              this.$router.push({
                path:
                  '/assessment-evaluation/online-test/begin-online-exam/' +
                  res.data.id
              })
            }
          }
        )
        this.exam_info_dialog_show = false
      } else if (+this.current_exam.status === 0) {
        return this.$message.error('考试暂未开始')
      } else if (+this.current_exam.status === 2) {
        return this.$message.error('考试已结束')
      }
    },
    /*
      去考试参加考试回调
    */
    toExamHandler (type = 2, row) {
      this.current_exam = row
      createSimExamHistoryApi({
        onlineExamId: this.current_exam.studentOnlineExamId
      }).then((res) => {
        if (res.data) {
          this.$message.success('开始考试，本次考试将计入考试次数')
          this.$router.push({
            path:
              '/assessment-evaluation/online-test/begin-online-exam/' +
              res.data.id
          })
        }
      })
    },
    /*
      分页变化
    */
    pagingChange (event) {
      if (
        typeof event.currentPage !== 'number' &&
        typeof event.pageSize !== 'number'
      ) { return }

      this.page_info = { ...this.page_info, ...event }
      this.pagingFindList()
    },
    /*
      初始化分页信息
    */
    initPageInfo () {
      this.page_info = {
        currentPage: 1,
        pageSize: this.page_info.pageSize,
        total: 0
      }
    },
    /*
      分页查询
    */
    pagingFindList (e) {
      if (e instanceof PointerEvent) {
        this.initPageInfo()
      }
      this.paper_list_loading = true
      pagingFindSimPaperApi({ ...this.page_info, ...this.form })
        .then((res) => {
          const { currentPage, pageSize, total } = res.data
          this.table_data = res.data.data
          // eslint-disable-next-line eqeqeq
          if (this.table_data.length === 0 && this.page_info.currentPage != 1) {
            this.initPageInfo()
            this.pagingFindList()
          }
          this.page_info = { currentPage, pageSize, total }
        })
        .finally((_) => {
          this.paper_list_loading = false
        })
    },
    toPrint (row) {
      this.paper_list_loading = true
      getLastedHistoryApi(row.studentOnlineExamId)
        .then((res) => {
          if (res.data == null) {
            return this.$message.error('该场考试没有查询到您的考试记录')
          }
          this.$router.push({
            path: '/print-paper/' + row.id,
            query: { examIdPaperId: res.data.id }
          })
        })
        .finally((_) => {
          this.paper_list_loading = false
        })
    }
  },

  mixins: [
    /**
     * 数据上报
     */
    dataReportMixin('MOCK_EXAMINATION')
  ]
}
</script>
<style lang="scss">
.classify_page .form_layout {
  margin-top: 16px;

  .suf {
    line-height: 1 !important;
  }

  .el-form-item:last-child {
    float: right;
  }
}
</style>
<style lang="scss" scoped>
.exam-status {
  width: 60px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: #ccc;
  border-radius: 20px;
}
</style>
