<script setup>
// 引入依赖
import capi from '@/api/course'
// import com_api from '@/api/common'
// import WarningBar from '@/components/warningBar/warningBar.vue'
import api from '@/api/exercises'
import { ref, onMounted, watch, inject, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// import chapterCom from '../components/chapter.vue'
const props = defineProps(['seleted_arr'])
const emit = defineEmits(['addFunc'])
// import { clients, getNowDate } from '@/utils'
import custom from '@/utils/custom'
// import { getToken } from '@/utils/auth'
// 监听
watch(props,(val1,val2) => {
  selected_question_ids.value = val2.seleted_arr?JSON.parse(val2.seleted_arr):[]
})
// console.log(props)
// 变量
const selected_question_ids = ref(props.seleted_arr || [])

// const headers = ref({ Authorization: 'Bearer ' + getToken() })
const drawer = ref(false)
const queryParams =ref({
  page:1,
  pageSize:10,
  content:'',
  subject:'',
  type:'',
  teacherId:0
})
const typeList = custom.getExercisesTypeList()
const tableData =ref([])
const total = ref(0)
const question_ids = ref([])
// 生命周期
// const subjectList = inject('subjectList')
const subjectList = ref([])
const current_subject = inject('current_subject')
queryParams.value.subject = current_subject
const subjectParams = ref({
    page:1,
    pageSize:100,
})
onMounted(() => {
  // console.log(headers.value)
  // getExercisesList()
  getSubject()
})
// 方法
async function getSubject(){ // 获取课程分类
  const res = await capi.getSubjectList(subjectParams.value)
  if(res.code === 0) {
    // subjectList.value = custom.getStdSubject(res.data.records)
    subjectList.value = custom.addTreeFormatSubject(res.data.records,'name')
  }
}
async function getExercisesList() {
  const res = await api.getExercisesList(queryParams.value)
  if(res.code === 0) {
    tableData.value = res.data.records
    total.value = res.data.total
    await nextTick()
    toggleSelection(tableData.value)
  }
}
function chooseChapterChildExercises() {
  drawer.value = true
  // getExercisesList()
  onSubmit()
}
function onSubmit() {
  queryParams.value.page = 1
  getExercisesList()
}
function onReset() {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    type:'',
    subject:'',
    teacherId:0
  }
}
const handleSelectionChange = (val) => {
  question_ids.value = val
}
function getExercisesName(row) {
  // console.log(JSON.parse(row.question))
  return JSON.parse(row.question).title
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getExercisesList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getExercisesList()
}
function addFunc() {
  // console.log(question_ids.value)
  const list = question_ids.value.map((item,i) => {
    return item.question_id
  })
  // console.log(list)
  emit('addFunc',list)
  drawer.value = false
}
const multipleTableRef = ref(null)

const toggleSelection = (rows) => { // 判断是否被选中
  if (rows) {
    rows.forEach((row) => {
      if(selected_question_ids.value.includes(row.question_id)) {
        multipleTableRef.value.toggleRowSelection(row, true)
      }else{
        multipleTableRef.value.toggleRowSelection(row, false)
      }
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}
function selectFunc(row, index) {
  return false
}
</script>
<template>
  <div>
    <el-button v-if="selected_question_ids.length==0" size="small" @click="chooseChapterChildExercises">添加习题</el-button>
    <el-button v-else size="small" @click="chooseChapterChildExercises" type="plain">点击查看（已选{{selected_question_ids.length}}道题）</el-button>
<!--    <div v-if="url_name">{{url_name}}</div>-->
    <el-drawer v-model="drawer" title="习题库" size="60%">
      <div class="drawer-section">
        <!--      搜索框-->
        <div class="search-box gva-btn-list">
          <el-form ref="searchForm" :inline="true" :model="queryParams">
            <el-form-item label="题目">
              <el-input v-model="queryParams.content" 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-tree-select v-model="queryParams.subject" :data="subjectList" :render-after-expand="false" />
            </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="list-box">
          <el-table border ref="multipleTableRef" row-key="question_id" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55"
              reserve-selection="true"
            />
            <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">
                <div v-html="getExercisesName(scope.row)"></div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="分值" min-width="150" prop="score" />
          </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>
        <!--  按钮-->
        <div class="btn-box" style="text-align: right">
<!--          <el-button size="small" type="primary" icon="plus" @click="addFunc">添加</el-button>-->
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<style scoped>
  .drawer-section{
    padding: 10px;
  }
</style>
