<!-- 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>
          <!-- <el-input placeholder="请输入查询内容" v-model="form.title" class="input-with-select" clearable>
          <el-button slot="append" @click="pagingFindList">查询</el-button>
        </el-input> -->
          <QueryInput v-model="form.title" @query="pagingFindList"></QueryInput>
        </template>
        <template v-slot:btns> </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':
                props.row.examTimes - props.row.myTimes <= 0
                  ? '#999999'
                  : ['#208ac6', '#01c883', '#999999'][props.row.status],
            }"
            class="exam-status"
          >
            <span v-if="props.row.examTimes - props.row.myTimes <= 0">
            已结束
            </span>
            <span v-else>
              {{ ["待开考", "已开始", "已结束"][props.row.status] }}
            </span>
          </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 &&
            props.row.examTimes - props.row.myTimes > 0
            "
            @click="toExamHandler(1, props.row)"
            >参加考试</el-button
          >
          <el-button
            type="text"
            icon="i-j-rgpj-xiangqing"
            @click="toExamHandler(2, props.row)"
            v-if="props.row.status < 1"
          >
            查看详情
          </el-button>
          <el-button
            type="text"
            icon="i-j-fbks-yulan"
            @click="lookLastExam(props.row)"
            v-if="
            props.row.status == 2 ||
            props.row.examTimes - props.row.myTimes <= 0
            "
            >查看答卷
          </el-button>
          <el-button
            type="text"
            icon="el-icon-printer"
            class="print-icon"
            @click="toPrint(props.row)"
            v-if="
              props.row.status == 2 ||
              props.row.examTimes - props.row.myTimes <= 0
            "
            >打印
          </el-button>
          <!-- <el-button type="text" icon="el-icon-edit" @click="downLoadThisPdf" v-if="props.row.status == 2">下载
          </el-button> -->

          <!-- <el-dropdown v-if="props.row.status == 2" style="margin-left: 10px;" @command="downLoadThisPdf" trigger="click">
            <span class="el-dropdown-link">
              <el-button type="text" icon="el-icon-arrow-down">下载
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">下载答卷</el-dropdown-item>
              <el-dropdown-item command="b">下载考卷</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
        </template>
      </TableLayout>
    </div>
    <DialogLayout
      :title="is_show_info ? `考试详情` : '确认考试'"
      :visible="exam_info_dialog_show"
      @onCancel="
        exam_info_dialog_show = false;
        current_exam = null;
      "
      width="600px"
      @onConfirm="toExamPaper"
      :actionBarOption="{
        noCencel: current_exam?.status == 0,
        noConfirm: current_exam?.status == 0,
      }"
    >
      <div>
        <div class="gy-form mb">
          <div class="gy-form-item mb">
            <div class="gy-label">考试开始时间：</div>
            <div>{{ current_exam?.examStartTime }}</div>
          </div>
          <div class="gy-form-item mb">
            <div class="gy-label">考试结束时间：</div>
            <div>{{ current_exam?.examEndTime }}</div>
          </div>
          <div class="gy-form-item">
            <div class="gy-label">考试时长：</div>
            <div>
              <span class="red"> {{ current_exam?.examDuration }}</span
              >分钟
            </div>
          </div>
        </div>
        <div class="gy-form inline mb">
          <div class="gy-form-item">
            <div class="gy-label">考试总分：</div>
            <div class="red">{{ current_exam?.totalScore }}</div>
          </div>
          <div class="gy-form-item">
            <div class="gy-label">及格分：</div>
            <div class="red">
              {{
                Math.round(
                  (current_exam?.totalScore * current_exam?.passPercent) / 100
                  )
              }}
            </div>
          </div>
        </div>
        <div class="gy-form inline mb">
          <div class="gy-form-item">
            <div class="gy-label">考试次数：</div>
            <div class="red">{{ current_exam?.examTimes }}次</div>
          </div>
          <div class="gy-form-item">
            <div class="gy-label">剩余次数：</div>
            <div class="red">
            {{ current_exam?.examTimes - current_exam?.myTimes }}次
            </div>
          </div>
        </div>
        <div class="gy-form mb">
          <div class="gy-form-item">
            <div class="gy-label">考试描述：</div>
            <div class="gy-in">{{ current_exam?.examDesc }}</div>
          </div>
        </div>
      </div>
    </DialogLayout>
  </div>
</template>

<script>
import { TableLayout, FormLayout, DialogLayout } from '@/components/layout'
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import {
  pagingOnlineExamListApi,
  createExamHistoryApi,
  getLastedHistoryApi
} from '@/api/assessment-evaluation/onlineTest'
import QueryInput from '@/components/widget/QueryInput.vue'
export default {
  components: {
    TableLayout,
    FormLayout,
    QueryInput,
    DialogLayout
  },

  data: () => ({
    table_data: [],
    page_info: { currentPage: 1, pageSize: 10, total: 0 },
    // 试题分类树是否加载中
    paper_list_loading: false,
    form: { title: '' },
    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: '考试名称',
        'min-width': 130,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'classify',
        label: '考试分类',
        'min-width': 80,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'totalScore',
        label: '总分',
        'min-width': 60,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'passPercent',
        label: '及格分',
        'min-width': 60,
        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: 'examStartTime',
        label: '考试时间',
        'min-width': 220,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'status',
        label: '状态',
        width: 80,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'action',
        label: '操作',
        //  width: 350,
        width: 200,
        align: 'center'
      }
    ]
  },
  activated () {
    this.pagingFindList()
  },
  methods: {
    /* 测试用, */
    downLoadThisPdf (type) {
      this.$message.info(type)
      // getPdf('测试', 'jj9999')
    },
    /*
      获取最后一次考试的考试记录
    */
    lookLastExam (row) {
      this.paper_list_loading = true
      getLastedHistoryApi(row.id)
        .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) {
      if (type === 2) {
        this.is_show_info = true
      } else if (type === 1) {
        this.is_show_info = false
      }
      this.current_exam = row
      this.exam_info_dialog_show = true
    },
    /*
      分页变化
    */
    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
      }
    },
    toPrint (row) {
      this.paper_list_loading = true
      getLastedHistoryApi(row.id)
        .then((res) => {
          if (res.data == null) {
            return this.$message.error('该场考试没有查询到您的考试记录')
          }
          this.$router.push({
            path: '/print-paper/' + row.paperId,
            query: { examIdPaperId: res.data.id }
          })
        })
        .finally((_) => {
          this.paper_list_loading = false
        })
    },
    /*
      分页获取数据api
    */
    pagingFindList (e) {
      if (e instanceof PointerEvent) {
        this.initPageInfo()
      }
      this.paper_list_loading = true
      pagingOnlineExamListApi({ ...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
        })
    }
  }
}
</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>
