
<script setup>
// 引入依赖
import api from '@/api/examination'
import capi from '@/api/course'
import custom from '@/utils/custom'
import {formatDate} from '@/utils/format'
import _ from 'lodash'
import WarningBar from '@/components/warningBar/warningBar.vue'
import exercisesPool from '@/view/course/components/exercisesPool.vue'
import groupPool from '@/view/examinationManage/components/groupPool.vue'

import {ref,onMounted,provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// store
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// 组件通信
const props = defineProps(['exam_id','chaper_name'])
// const emit = defineEmits(['reload'])
// 变量
const path = ref(import.meta.env.VITE_BASE_API)
// const typeList = custom.getExercisesTypeList()
// const queryParams = ref({
//   teacherId:0,
//   page:1,
//   pageSize:10,
//   name:'',
//   status:'',
//   subject:''
// })
const subjectParams = ref({
    page:1,
    pageSize:100,
})
const tableData = ref([])
const subjectList = ref([])
const current_subject = ref('')
const deleteVisible = ref(false)
const question_ids = ref([])
const total = ref(0)
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const form =ref({price:4.9})
const rules = ref({
  // name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
})
const question_id = ref(0)
const content = ref(null)
// const options = ref([]) // 答案选项数组
const exam_types = ref([])
const exam_ids = ref([])
const price_props = ['first','second','third','price']
const exam_type_ids = ref([])
// 生命周期
onMounted(() => {
  // getExaminationList()
  // getExaminationDetail()
  // getSubject()
})
// provide('subjectList', subjectList)
// provide('current_subject', current_subject)
const std_group = ref({
  persons:'',
  expiry_date:'',
  public_date:'',
  first:'',
  second:'',
  third:''
})
const exam_info =ref(null)
// 方法
async function viewFunc() {
  dialogFormVisible.value = true
  if(subjectList.value.length === 0) {
    await getSubject()
  }
  // await getSubject()
  getExaminationDetail()
}

async function getExaminationDetail() {
  const res = await api.getExaminationDetail({
    id:props.exam_id
  })
  if(res.code === 0) {
    exam_info.value = res.data
    form.value = res.data.exam
    form.value.price = 4.9
    exam_types.value = res.data.exam_types.map((item) => {
    for(let prop in item) {
      if(price_props.includes(prop)) {
            item[prop] /= 100
        }
      }
      return item
    })
    console.log(exam_info.value,exam_types.value)
  }
}
// async function getExaminationList() {
//   const res = await api.getExaminationList(queryParams.value)
//   if(res.code === 0) {
//     tableData.value = res.data.records
//     total.value = res.data.total
//   }
// }
async function getSubject(){ // 获取课程分类
  const res = await capi.getSubjectList(subjectParams.value)
  if(res.code === 0) {
    subjectList.value = custom.getStdSubject(res.data.records)
  }
}
// function onSubmit() {
//   getExaminationList()
// }
// const onReset = () => {
//   queryParams.value = {
//     page:1,
//     pageSize:10,
//     name:'',
//     status:'',
//     subject:''
//   }
// }
function openDialog(type) {
  // let params = {}
  switch (type){
    case 'add':
      dialogTitle.value = '新增试卷'
        form.value = {price:4.9}
      break;
    case 'edit':
      // params.question_id = question_id.value
      dialogTitle.value = '编辑试卷'
      break;
  }
  dialogFormVisible.value = true
  // router.push({name:'addCourse',params})
}
// async function onDelete() {
//   const ids = exam_ids.value
//   const res = await api.delExamination({ exam_ids:ids })
//   if (res.code === 0) {
//     ElMessage({
//       type: 'success',
//       message: res.msg
//     })
//     // if (tableData.value.length === ids.length && page.value > 1) {
//     //   page.value--
//     // }
//     deleteVisible.value = false
//     getExaminationList()
//   }
// }
// const handleSelectionChange = (val) => {
//   exam_ids.value = val.map((item) => {
//       return item.exam.exam_id
//   })
// }
// const exam_id = ref(null)
// function handleCurrentChange(val) {
//   queryParams.value.page = val
//   getExaminationList()
// }
// function handleSizeChange(val) {
//   queryParams.value.pageSize = val
//   getExaminationList()
// }
function closeDialog(){
  dialogFormVisible.value = false
  exam_types.value = []
  form.value = {}
}
async function enterDialog() { // 提交
  // form.value.teacher_id = 0
  // form.value.exam_type = exam_types.value.map((item) => {
  //   for(let prop in item) {
  //     if(Object.keys(std_group.value).includes(prop)) {
  //       item[prop] = Number(item[prop])
  //       if(price_props.includes(prop)) {
  //         item[prop] *= 100
  //       }
  //     }
  //   }
  //   return item
  // })
  // form.value.price = parseInt(Number(form.value.price )*100)
  // form.value.duration = parseInt(form.value.duration)
  // const params = {
  //   ...form.value
  // }
  // params.question_ids = JSON.stringify(form.value.question_ids)
  // params.course_ids = JSON.stringify(form.value.course_ids)
  // let func_name = 'addExamination'
  // if(form.value.exam_id) { // 编辑
  //   func_name = 'editExamination'
  // }
  // const res = await api[func_name](params)
  // if(res.code === 0) {
  //   ElMessage({
  //     type: 'success',
  //     message: res.msg
  //   })
  //   closeDialog()
  //   getExaminationList()
  // }
}
// function viewCourseFunc(row) { // 查看课程
//   router.push({name:'viewCourse',params:{question_id:row.question_id}})
// }
// function getExercisesName(row) {
//   return JSON.parse(row.question).title
// }
// const std_options_title = ref(['A','B','C','D','E','F'])
// function addOptionFunc() {
//   exam_types.value.push(_.cloneDeep(std_group.value))
// }
// function delet_func(i) {
//   exam_types.value.splice(i,1)
// }
// function handleAvatarSuccess(res) {
//   form.value.cover = res.data.file.url
// }
// function beforeAvatarUpload(file) {
//   const isLt05M = file.size / 1024 / 1024 < 20
//   const isJPG = file.type.indexOf('image/') === -1
//   if (isJPG) {
//     ElMessage.error('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件')
//   }
//   if (!isLt05M) {
//     ElMessage.error('上传头像图片大小不能超过 2M!')
//   }
//   return !isJPG && isLt05M
// }
// function changeSubjectFunc(e) {
//   current_subject.value = e
// }
function addExercisesFunc(data) {
  form.value.question_ids = data
}
function addGroupFunc(data) {
  console.log("父组件行为")
  exam_types.value = _.clone(data)
}

</script>
<template>
  <div>
    <el-button size="small" @click="viewFunc" type="plain">点击查看</el-button>
    <!--  编辑窗口 -->
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="'章节：'+chaper_name">
      <el-form  ref="apiForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名称" >
          <el-input disabled v-model="form.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-select disabled v-model="form.subject" @change="changeSubjectFunc" clearable placeholder="请选择">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              disabled
            class="avatar-uploader"
            :action="`${path}/fileUploadAndDownload/upload`"
            :headers="{ 'x-token': userStore.token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar avatar-uploader-img" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="测试时长" >
          <el-input disabled type="number" v-model="form.duration" placeholder="请输入测试时长（分钟）" />
        </el-form-item>
        <el-form-item label="测试价格" >
          <el-input type="number" v-model="form.price" disabled placeholder="请输入测试价格（元）" />
        </el-form-item>
        <el-form-item label="测试组别" >
          <groupPool @addFunc="addGroupFunc" :exam_types="exam_types" :exam_id="exam_id" />
        </el-form-item>
        <el-form-item label="添加习题" >
          <exercisesPool @addFunc="addExercisesFunc" :seleted_arr="form.question_ids" />
        </el-form-item>
        <el-form-item label="是否上架" >
          <el-switch
              disabled
            v-model="form.status"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="-1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="closeDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.el-table .el-table__cell{
  z-index: unset;
}
</style>
<style scoped lang="scss">

  .avatar-uploader-img{
    width: 178px;
    height: 178px;
  }
  .avatar-uploader{

  }
  .rb-item{
    margin-bottom: 10px;
  }
  .e-img{
    width: 150px;
    height: 100px;
  }
  .option-item{
    border-bottom: 1px solid #ebebeb;
    margin-bottom: 10px;
    .oi-row{
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .oi-item{
        //color: red;
      }
    }
  }
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
