<!-- 表格里的管理弹出框 -->
<template>
  <MOSTY.PageTree :pageTitle="'考试详情信息'" :isShowLeftTree="false">
    <template #serach>
      <div class="titleBox mb10">
        <div class="title"><span>考试总人数：{{ personCount }}人，已考试人数：{{ oldCount }}人，未考试人数：{{ notCount }}人 </span></div>
        <div class="right-btnBox">

          <el-select placeholder="请选择" v-model="examState" @change="addUserHander" clearable>
            <el-option label="已考试" value="1"></el-option>
            <el-option label="未考试" value="0"></el-option>
          </el-select>
          <el-select style="margin-left: 10px;" placeholder="请选择考试次数" v-model="examCount" @change="addUserHander"
            clearable>
            <el-option v-for="item in examCountOpt" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-button class="ml10 mr10" type="primary" :loading="excelLoading" @click="exportExcels">导出</el-button>
          <div @click="handleClose">
            <el-button type="primary">
              <el-icon>
                <Close />
              </el-icon>关闭
            </el-button>
          </div>
        </div>
      </div>
    </template>
    <template #table>
      <div class="tabBoxs">
        <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :isSelect="false" :isSort="false"
          style="width: 100%;">
          <template #actions="{ row }">
            <!-- <span class="operesee" @click="showExamListDetail(row)"><el-icon>
                <View />
              </el-icon>查看详情</span> -->
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要设置为重新考试?"
              @confirm="repeatExam(row)">
              <template #reference>
                <span class="operesee"><el-icon>
                  </el-icon>重新考试</span>
              </template>
            </el-popconfirm>

          </template>
        </MOSTY.Table>

      </div>
      <div class="fenye">
        <el-pagination class="pagination" :current-page="listQuery.pageCurrent" :page-size="listQuery.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, prev, pager, next, sizes, jumper" :total="listQuery.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </template>
  </MOSTY.PageTree>
  <div>

  </div>
  <!-- 详情 -->
  <div v-if="examShow" class="dialog-box">
    <Examdaio @close="examShow = false" :Row="info" type="exam" :userId="currentRow.userId"
      :username="currentRow.userName" :sjRow="sjRow" />
  </div>
</template>

<script setup>
// 引入
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, reactive, computed } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import Examdaio from "../pxzyk/examdaio.vue";
const currentRow = ref({})
import { exportXlsx } from "@/excel/Export2Excel.js";
import { getItem } from "@/utils/storage"
import { ElMessage } from 'element-plus'

const examState = ref(null)
/** 考试次数 */
const examCount = ref(null)
// 数据
const props = defineProps({
  qwjcxqShow: {
    type: Boolean,
    default: true
  },
  sjRow: {
    type: Object,
    default: {}
  },
  listId: {
    type: String,
    default: ""
  },
});
const emits = defineEmits(["changeVi2"]);
const tableData = ref([
]);
// 分页
const listQuery = ref({
  id: props.listId,
  pageCurrent: 1,
  pageSize: 10,
  total: 0
});
const notCount = ref("")
const oldCount = ref("")
const personCount = ref("")
const examListShow = ref(false)
const info = ref({})
const examShow = ref(false)
const excelLoading = ref(false)
const tableColumn = reactive([
  {
    title: "考试名称",
    prop: "name"
  },
  {
    title: "考员姓名",
    prop: "userName"
  },
  {
    title: "所属单位",
    prop: "ssdwmc"
  },
  {
    title: "考员部门",
    prop: "deptName"
  },
  {
    title: "开考时间",
    prop: "startTime"
  },
  {
    title: "交卷时间",
    prop: "endTime"
  },
  {
    title: "考时（分）",
    prop: "examTime"
  },
  {
    title: "得分",
    prop: "examScore"
  },

  // {
  //   title: "操作",
  //   prop: "actions",
  //   slot: true
  // }
])
if (getItem('USERID') == '000000') {
  tableColumn.push({
    title: "操作",
    prop: "actions",
    slot: true
  })
}
/** 考试次数opt */
const examCountOpt = computed(() => {
  /** 可参加次数 */
  const kcjcs = props.sjRow?.kcjcs || 0;
  let arr = Array.from({ length: kcjcs }, (v, i) => {
    return {
      value: i,
      label: `第${i + 1}次考试`
    };
  });
  return arr
});

// 初始化
onMounted(() => {

  // 获取考试详情列表
  getKsList();
  // 统计考试人员数量
  getKsStatistics()
});
// 关闭
const handleClose = () => {
  emits("changeVi2", false);
};
// 统计考试人员数量
const getKsStatistics = () => {
  postApi(listQuery.value, "/mosty-jcgl/paper/getExamTypeStatistics").then(
    (res) => {
      notCount.value = res.notCount
      oldCount.value = res.oldCount
      personCount.value = res.personCount
    }
  );
};
const exportExcels = () => {
  excelLoading.value = true
  let title = {
    name: '考试名称',
    userName: "考员姓名",
    deptName: "考员部门",
    ssdwmc: "所属单位",
    startTime: "开考时间",
    endTime: "交卷时间",
    examTime: "考时（分）",
    examScore: "得分",
  };
  const param = {
    ...listQuery.value,
    // type: examState.value
    pageCurrent: 1,
    pageSize: 3000
  }
  postApi(param, "/mosty-jcgl/paper/getExamTypeDetail").then((res) => {
    if (res) {
      let data = res?.records || [];

      if (data) {
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          item.examTime = item.examTime || item.examTime == 0 ? item.examTime : ''
          item.examScore = item.examScore || item.examScore == 0 ? item.examScore : ''
          item.startTime = item.startTime ? item.startTime : ''
          item.endTime = item.endTime ? item.endTime : ''
        }
        let ksObj = {
          0: '未考试',
          1: '已考试'
        }
        /** 第N次考试 */
        const countCount = examCountOpt.value.find(item => item.value === listQuery.value.examCount)?.label
        let preSubtitle = `${data?.[0]?.name || ''} ${ksObj[examState.value] || ''} ${countCount || ''}`
        let tablename = `${preSubtitle}考试详情.xlsx`;

        exportXlsx(title, data, `${preSubtitle} 考试详情`, tablename);
        excelLoading.value = false
      }
      excelLoading.value = false
    }
  }).catch(() => {
    excelLoading.value = false
  });
};
// 获取考试详情列表
const getKsList = () => {
  postApi(listQuery.value, "/mosty-jcgl/paper/getExamTypeDetail").then(
    (res) => {
      listQuery.value.total = res.total;
      tableData.value = res.records;
    }
  );
};
const addUserHander = () => {
  listQuery.value.type = examState.value
  listQuery.value.examCount = examCount.value
  listQuery.value.pageCurrent = 1
  getKsList()
}
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  getKsList();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  getKsList();
};
/** 弹框[详情]点击 */
const showExamListDetail = (row) => {
  currentRow.value = row
  examListShow.value = false
  info.value = row
  info.value.examId = row.id
  examShow.value = true
}
/** 让其可以重考 */
const repeatExam = (row) => {
  getApi({ id: row.id }, '/mosty-jcgl/paper/resubmitExam').then(() => {
    ElMessage.success("设置为可重考成功");
    getKsList();
  })
}
</script>

<style lang="scss" scoped>
.dialog-box {
  z-index: 9999999;
}

.tabBoxs {
  height: calc(100vh - 300px);
}


::v-deep .el-dialog__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}

.right-btnBox {
  display: flex;
  align-items: center;
}
</style>
