<script setup>
// 引入依赖
// import api from '@/api/course'
// import com_api from '@/api/common'
// import WarningBar from '@/components/warningBar/warningBar.vue'
import api from '@/api/examination'
import { ref, onMounted, watch, inject, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {formatDate} from '@/utils/format'
const router = useRouter()
const route = useRoute()
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// import chapterCom from '../components/chapter.vue'
const props = defineProps(['url_name','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_exam_ids.value = val1.seleted_arr || []
})
// 变量
const selected_exam_ids = ref(props.seleted_arr || [])

// const headers = ref({ Authorization: 'Bearer ' + getToken() })
const drawer = ref(false)
const queryParams =ref({
  page:1,
  pageSize:10,
  name:'',
  // subject:'',
  status:'',
})
const typeList = custom.getExercisesTypeList()
const tableData =ref([])
const total = ref(0)
const exam_ids = ref([])
// 生命周期
const subjectList = inject('subjectList')
// console.log(subjectList.value)
// const current_subject_str = inject('current_subject')
// const current_subject = ref(null)
// watch(current_subject_str,(val1,val2) => {
//   console.log(val1)
//   queryParams.value.subject = getSubjectId(val1)
//   console.log(queryParams.value.subject)
// })
// queryParams.value.subject = current_subject
onMounted(() => {
  // console.log(headers.value)
  // getExaminationList()
})
// 方法
function getSubjectId(str) {
  // console.log(str)
  let s_id = null
  for(let item of subjectList.value) {
    if(item.name === str) {
      s_id = item.id
    }
  }
  return s_id
}
async function getExaminationList() {
  const res = await api.getExaminationList(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
  // getExaminationList()
  onSubmit()
}
function onSubmit() {
  queryParams.value.page = 1
  getExaminationList()
}
function onReset() {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    subject:'',
    status:'',
  }
}
const handleSelectionChange = (val) => {
  exam_ids.value = val
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getExaminationList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getExaminationList()
}
function addFunc() {
  const list = exam_ids.value.map((item,i) => {
    return item.exam.exam_id
  })
  // console.log(list)
  emit('addFunc',list)
  drawer.value = false
}
const multipleTableRef = ref(null)
const toggleSelection = (rows) => { // 判断是否被选中
  if (rows) {
    rows.forEach((row) => {
      if(selected_exam_ids.value.length>0 && selected_exam_ids.value.includes(row.exam.exam_id)) {
        multipleTableRef.value.toggleRowSelection(row, true)
      }
      else{
        multipleTableRef.value.toggleRowSelection(row, false)
      }
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}

function getStateName(state) {
  let str = ''
  switch (state){
    case 1:
        str = '上架'
      break;
    case -1:
        str = '下架'
      break;
  }
  return str
}
</script>
<template>
  <div>
    <el-button v-if="selected_exam_ids.length==0" size="small" @click="chooseChapterChildExercises">添加试卷</el-button>
    <el-button v-else size="small" @click="chooseChapterChildExercises" type="plain">点击查看</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.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>
              <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 ref="multipleTableRef" row-key="exam.exam_id" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55"
              reserve-selection="true"
            />
            <el-table-column align="center" label="ID" min-width="60" prop="exam.exam_id" sortable="custom" />
            <el-table-column align="center" label="试卷名称" min-width="150" prop="exam.name" />
            <el-table-column align="center" label="科目" min-width="150" prop="exam.subject" />
            <el-table-column align="center" label="封面" min-width="150" >
              <template #default="scope">
                <img class="e-img" :src="scope.row.exam.cover" alt="">
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" min-width="150" >
              <template #default="scope">
                <div>{{getStateName(scope.row.exam.status)}}</div>
              </template>
            </el-table-column>
            <el-table-column label="销量">
              <template #default="scope">
                <div>{{scope.row.exam.sale}}份</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="组数" min-width="150" >
              <template #default="scope">
                <div>{{scope.row.exam_types.length}}组</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" min-width="150" >
              <template #default="scope">
                {{formatDate(scope.row.exam.CreatedAt)}}
              </template>
            </el-table-column>
<!--            <el-table-column align="center" 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="deleteExamFunc(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>
        <!--  按钮-->
        <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;
  }
  .e-img{
    width: 150px;
    height: 100px;
  }
</style>
