<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="课程类型">
        <el-select
          v-model="queryParams.ctTypeNode"
          placeholder="请选择课程类型"
          class="!w-240px"
          @change="handleCtTypeNodeChange"
        >
          <el-option label="ai通识课" value="1" />
          <el-option label="ai实操课" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="大纲课程" prop="courseType">
        <el-tree-select
          v-model="queryParams.courseType"
          :data="courseTypeTree"
          :props="{...defaultProps,
            label: (node) => `${node.ctTypeNode === '0' || node.ctTypeNode === undefined ? node.ctType : node.ctTypeSort + '、' + node.ctType}`,
            }"
          placeholder="请选择课程类型"
          :default-expand-all="true"
          class="!w-240px"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容类型" prop="courseContentType">
        <el-select
          v-model="queryParams.courseContentType"
          placeholder="请选择内容类型"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.COURSE_COUTNET_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="课程作者" prop="courseAuthor">
        <el-input
          v-model="queryParams.courseAuthor"
          placeholder="请输入课程作者"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="课程老师" prop="courseTeacher">
        <el-input
          v-model="queryParams.courseTeacher"
          placeholder="请输入课程老师"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>-->
      <el-form-item label="是否有检查" prop="courseIsInspect">
        <el-select
          v-model="queryParams.courseIsInspect"
          placeholder="请选择是否有检查"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程标签" prop="courseLabel">
        <el-select
          v-model="queryParams.courseLabel"
          placeholder="请选择课程标签"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.COURSE_LABEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程状态" prop="courseStatus">
        <el-select
          v-model="queryParams.courseStatus"
          placeholder="请选择课程状态"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['bjdx:course:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['bjdx:course:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
<!--      <el-table-column label="课程d" align="center" prop="id" />-->
      <el-table-column label="课程类型" align="center" prop="courseTypeName" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="内容类型" align="center" prop="courseContentType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COURSE_COUTNET_TYPE" :value="scope.row.courseContentType" />
        </template>
      </el-table-column>
<!--      <el-table-column label="课程路径" align="center" prop="courseVideoPath" />-->
      <el-table-column label="课程内容" align="center" prop="courseContent" width="120px">
          【预览查看】
      </el-table-column>
<!--      <el-table-column label="课程作者" align="center" prop="courseAuthor" />-->
<!--      <el-table-column label="课程老师" align="center" prop="courseTeacher" />-->
<!--      <el-table-column label="课程大小" align="center" prop="courseSize" />-->
<!--      <el-table-column label="课程时长" align="center" prop="courseTime" />-->
      <el-table-column label="是否有检查" align="center" prop="courseIsInspect">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.courseIsInspect" />
        </template>
      </el-table-column>
      <el-table-column label="课程标签" align="center" prop="courseLabel">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COURSE_LABEL" :value="scope.row.courseLabel" />
        </template>
      </el-table-column>
      <el-table-column label="课程排序" align="center" prop="courseOrder"/>
      <el-table-column label="课程状态" align="center" prop="courseStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.courseStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180px"> <!-- 调整列宽适配新按钮 -->
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="scope.row.tenantId == getTenantId()"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['bjdx:course:update']"
          >
            编辑
          </el-button>
<!--          <el-button-->
<!--            link-->
<!--            type="info"-->
<!--            @click="openPreview(scope.row)"-->
<!--          >-->
<!--            预览-->
<!--          </el-button>-->
          <el-button
            link
            type="success"
            :disabled="scope.row.courseContentType !== 'video'"
            title="仅视频课程可配置"
            @click="handleConfig(scope.row.id,scope.row.courseName,scope.row.tenantId)"
          >
            配置
          </el-button>
          <el-button
            link
            type="danger"
            v-if="scope.row.tenantId == getTenantId()"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['bjdx:course:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CourseForm ref="formRef" @success="getList" />

  <!-- 新增预览弹窗 -->
  <CoursePreview ref="previewRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import { CourseApi, CourseVO } from '@/api/bjdx/course'
import CourseForm from './CourseForm.vue'
import CoursePreview from '@/views/bjdx/course/CoursePreview.vue'
import { useRouter } from 'vue-router'
import { defaultProps, handleTree } from '@/utils/tree'
import { CourseTypeApi } from '@/api/bjdx/coursetype'
import { getTenantId } from '@/utils/auth'
import { ElButton } from 'element-plus'

/** 课程 列表 */
defineOptions({ name: 'Course' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CourseVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  courseName: undefined,
  courseContentType: undefined,
  courseImagePath: undefined,
  courseVideoPath: undefined,
  courseContent: undefined,
  courseAuthor: undefined,
  courseTeacher: undefined,
  courseSize: undefined,
  courseTime: undefined,
  courseIsInspect: undefined,
  ctTypeNode: "1",//课程类型
  courseType: undefined,
  courseTypeName: undefined,
  courseLabel: undefined,
  courseOrder: undefined,
  courseStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
// 新增预览相关变量
const previewRef = ref()
const courseTypeTree = ref() // 树形结构

/** 打开预览弹窗 */
const openPreview = (row) => {
  // 使用$nextTick确保组件挂载后调用
    previewRef.value?.open(row)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CourseApi.getCoursePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  getList()
}

/** 处理课程类型节点变更 */
const handleCtTypeNodeChange = (ctTypeNode) => {
  queryParams.courseType = undefined
  getCourseTypeTree(ctTypeNode)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.ctTypeNode = "1"
  getCourseTypeTree()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CourseApi.deleteCourse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 配置按钮操作 */
const router = useRouter()
const handleConfig = (id: number,courseName: string,tenantId: number) => {
  router.push({
    name: 'courseConfig',
    query: { courseId: id , courseName: courseName,tenantId: tenantId}
  })
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CourseApi.exportCourse(queryParams)
    download.excel(data, '课程.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获得课程-类型树 */
const getCourseTypeTree = async (filterCtTypeNode = "1") => {
  courseTypeTree.value = []
  const data = await CourseTypeApi.getCourseTypeSimpleList()

  let filteredData = data
  if (filterCtTypeNode !== undefined) {
    filteredData = data.filter(item => item.ctTypeNode === '0' || item.ctTypeNode === filterCtTypeNode)
  }
  const root: Tree = { id: 0, ctType: '课程类型' + (filterCtTypeNode === "1" ? '（ai通识课）' : '（ai实操课）'), children: [] }
  root.children = handleTree(filteredData, 'id', 'ctParentId')
  courseTypeTree.value.push(root)
}

/** 初始化 **/
onMounted(() => {
  getList()
  getCourseTypeTree()
})
</script>
