<script setup>
// 引入依赖
// import api from '@/api/course'
// import com_api from '@/api/common'
// import WarningBar from '@/components/warningBar/warningBar.vue'
import api from '@/api/course'
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(['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_course_ids.value = val1.seleted_arr || []
})
// 变量
const selected_course_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 course_ids = ref([])
// 生命周期
const subjectList = inject('subjectList')
// console.log(subjectList.value)
// const current_subject =getSubjectId(inject('current_subject'))
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)
  // getCourseList()
})
// 方法
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 getCourseList() {
  const res = await api.getCourseList(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
  // getCourseList()
  onSubmit()
}
function onSubmit() {
  queryParams.value.page = 1
  getCourseList()
}
function onReset() {
  queryParams.value = {
    page:1,
    pageSize:10,
    name:'',
    subject:'',
    status:'',
  }
}
const handleSelectionChange = (val) => {
  course_ids.value = val
}
function handleCurrentChange(val) {
  queryParams.value.page = val
  getCourseList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getCourseList()
}
function addFunc() {
  const list = course_ids.value.map((item,i) => {
    return item.course_id
  })
  emit('addFunc',list)
  drawer.value = false
}
const multipleTableRef = ref(null)
const toggleSelection = (rows) => { // 判断是否被选中
  if (rows) {
    rows.forEach((row) => {
      if(selected_course_ids.value.length>0 && selected_course_ids.value.includes(row.course_id)) {
        multipleTableRef.value.toggleRowSelection(row, true)
      }
      else{
        multipleTableRef.value.toggleRowSelection(row, false)
      }
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}
function viewCourseFunc(row) { // 查看课程
  router.push({name:'viewCourse',params:{course_id:row.course_id}})
}
</script>
<template>
  <div>
    <el-button v-if="selected_course_ids.length==0" size="small" @click="chooseChapterChildExercises">添加课程</el-button>
    <el-button v-else size="small" @click="chooseChapterChildExercises" type="plain">点击查看（已选{{selected_course_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.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.id"
                />
              </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="course_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="course_id" sortable="custom" />
            <el-table-column align="left" label="名称" min-width="150" prop="name" />
            <el-table-column align="left" label="科目" min-width="150" prop="subject" />
            <el-table-column align="left" label="价格" min-width="150" prop="price" />
            <el-table-column align="left" label="状态" min-width="150" prop="status">
              <template #default="scope">
                {{scope.row.status == 1?'上架':scope.row.status == 2?'待审核':scope.row.status == 3?'通过':scope.row.status == 4?'未通过':'下架'}}
              </template>
            </el-table-column>
            <el-table-column align="left" label="是否精品" min-width="150" prop="is_boutique" />
            <el-table-column align="left" fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button
                  icon="view"
                  size="small"
                  type="primary"
                  link
                  @click="viewCourseFunc(scope.row)"
                >查看</el-button>
<!--                <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>
        <!--  按钮-->
        <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>
