
<script setup>
// 引入依赖
import api from '@/api/exercises'
import capi from '@/api/course'
import custom from '@/utils/custom'
import {formatDate} from '@/utils/format'
import _ from 'lodash'
// import { toSQLLine } from '@/utils/stringFun'
import WarningBar from '@/components/warningBar/warningBar.vue'
import ckEditor from '@/components/richText/ckEditor5.vue'
import {ref,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 变量
const typeList = custom.getExercisesTypeList()
const queryParams = ref({
  teacherId:0,
  page:1,
  pageSize:10,
  name:'',
  type:'',
  subject:''
})
const subjectParams = ref({
    page:1,
    pageSize:100,
})
const tableData = ref([])
const subjectList = ref([])
const deleteVisible = ref(false)
const question_ids = ref([])
const total = ref(0)
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const form =ref({})
const rules = ref({
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
})
const question_id = ref(0)
const content = ref(null)
const options = ref([]) // 答案选项数组
const question_form = ref({
  options:[],
  answer:'',
  title:''
})
// 生命周期
onMounted(() => {
  getExercisesList()
  getSubject()
})
// 方法
async function getExercisesList() {
  const res = await api.getExercisesList(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() {
  getExercisesList()
}
const onReset = () => {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    status:'',
    subject:''
  }
}
function openDialog(type) {
  // let params = {}
  switch (type){
    case 'add':
      dialogTitle.value = '新增习题'
      form.value = {}
      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 = question_ids.value.map(item => item.question_id)
  const res = await api.delExercises({ question_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
    getExercisesList()
  }
}
const handleSelectionChange = (val) => {
  question_ids.value = val
}
function editCourseFunc(row) {
  form.value = _.cloneDeep(row)
  question_id.value = form.value.question_id
  content.value = JSON.parse(form.value.question).title
  question_form.value = JSON.parse(form.value.question)
  if(!question_form.value.options) {
    question_form.value.options = []
  }
  openDialog('edit')
}
function deleteCourseFunc(row) {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    const res = await api.delExercises({
          question_ids:[row.question_id]
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getExercisesList()
    }
  },() => {
  })
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getExercisesList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getExercisesList()
}
function closeDialog(){
  dialogFormVisible.value = false
  question_form.value = {
    options:[],
    answer:'',
    title:''
  }
  form.value = {}
}
async function enterDialog() { // 提交
  form.value.score = parseInt(form.value.score)
  form.value.teacher_id = 0
  form.value.question = JSON.stringify(question_form.value)
  let func_name = 'addExercises'
  if(form.value.question_id) { // 编辑
      func_name = 'editExercises'
  }
  const res = await api[func_name](form.value)
  if(res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    // if (tableData.value.length === ids.length && page.value > 1) {
    //   page.value--
    // }
    // deleteVisible.value = false
    closeDialog()
    getExercisesList()
  }
}
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() {
  // for(let i=0 ;i<std_options_title.value.length;i++) {
  //     if(!options.value.has(std_options_title.value[i])) {
  //       options.value.set(std_options_title.value[i],'')
  //       break;
  //     }
  // }

  for(let i=0 ;i<std_options_title.value.length;i++) {
    let has_flag = false
    for(let item of question_form.value.options){
      if(item.name === std_options_title.value[i]) {
        has_flag = true
      }
    }
    if(!has_flag) {
      let data = {
        name:std_options_title.value[i],
        value: ''
      }
      question_form.value.options.push(data)
      break
    }
  }
}
function delet_func(item) {
  question_form.value.options.pop()
}
</script>
<template>
  <div>
    <!--    搜索框-->
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="queryParams">
        <el-form-item label="题目名称">
          <el-input v-model="queryParams.name" placeholder="根据题目名称进行查询" />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select v-model="queryParams.subject" 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-select v-model="queryParams.type" clearable placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--    表格数据-->
    <div class="gva-table-box">
      <!--      批量操作-->
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="openDialog('add')">新增</el-button>
        <el-popover v-model="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button size="small" type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button size="small" type="primary" @click="onDelete">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" size="small" type="danger" :disabled="!question_ids.length" style="margin-left: 10px;" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>
      <!--      数据列表-->
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="left" label="ID" min-width="60" prop="question_id" sortable="custom" />
        <el-table-column align="left" label="题型" min-width="150" prop="name" >
          <template #default="scope">
            {{custom.getExercisesTypeName(scope.row.type)}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="科目" min-width="150" prop="subject" />
        <el-table-column align="left" label="题目" min-width="150" >
          <template #default="scope">
            <!--            {{getExercisesName(scope.row)}}-->
            <div v-html="getExercisesName(scope.row)"></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="分值" prop="score" />
        <!-- <el-table-column align="left" label="创建者" min-width="150" prop="teacher_id" /> -->
        <el-table-column align="left" label="创建时间" min-width="150" >
          <template #default="scope">
            {{formatDate(scope.row.CreatedAt)}}
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              icon="edit"
              size="small"
              type="primary"
              link
              @click="editCourseFunc(scope.row)"
            >编辑</el-button>
            <el-button
              icon="delete"
              size="small"
              type="danger"
              link
              @click="deleteCourseFunc(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>

    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
      <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科目" prop="subject">
          <el-select v-model="form.subject" 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="题型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" >
          <ckEditor v-model="question_form.title" style="width:100%" :content="question_form.title" />
        </el-form-item>
        <el-form-item label="分值" >
          <el-input type="number" v-model="form.score" placeholder="请输入分值" />
        </el-form-item>
        <el-form-item label="答案" >
          <!--          <el-input v-model="form.score" placeholder="请输入分值" />-->
          <view class="options-box">
            <view class="option-item" v-if="question_form" v-for="(item,i) in question_form.options">
              <view>{{item.name}}</view>
              <ckEditor v-model="item.value" :content="item.value" style="margin-left:5px;width:100%" />
              <el-icon style="margin-left: 5px;cursor: pointer" v-if="(i+1) == question_form.options.length" @click="delet_func(item)"><Delete /></el-icon>
            </view>
            <el-button @click="addOptionFunc">添加答案</el-button>
          </view>
        </el-form-item>
        <el-form-item label="正确答案" >
          <el-input v-model="question_form.answer" placeholder="请输入正确答案（如，选择题：A或A-B；填空题直接填值）" />
        </el-form-item>
        <el-form-item label="题目解析" >
<!--          <el-input v-model="form.analysis" placeholder="请输入题目解析" />-->
          <ckEditor v-model="form.resolve" style="width:100%" :content="form.resolve"  />
        </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="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
  .option-item{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
