<template>
  <el-row :gutter="20">
    <!-- 左侧课程类型树 -->
    <el-col :span="5" :xs="24">
      <ContentWrap class="h-1/1" style="overflow-x: auto; overflow-y: auto; height: calc(100vh - 100px);" >
        <!-- 课程类型切换 -->
        <div class="mb-20px">
          <el-form-item label="课程类型" class="!mb-0">
            <el-select
              v-model="queryParams.ctTypeNode"
              placeholder="请选择课程类型"
              class="!w-full"
              @change="handleCtTypeNodeChange"
            >
              <el-option v-for="courseType in courseTypeList"
                :key="courseType.id"
                :label="courseType.name"
                :value="courseType.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- 搜索框 -->
        <div class="mb-20px">
          <el-input
            v-model="treeSearchValue"
            placeholder="搜索课程类型"
            clearable
            @input="handleTreeSearch"
            class="!w-full"
            prefix-icon="ep:search"
          />
        </div>
        <!-- 课程类型树形选择器 -->
        <el-tree
          v-model="queryParams.courseType"
          :data="filteredCourseTypeTree"
          :props="{
            label: (node) => `${node.ctTypeNode === '0' || node.ctTypeNode === '-1' || node.ctTypeNode === undefined ? node.ctType : node.ctTypeSort + '、' + node.ctType}`,
            children: 'children',
            value: 'id'
          }"
          :default-expand-all="true"
          node-key="id"
          highlight-current
          @node-click="handleCourseTypeClick"
        />
      </ContentWrap>
    </el-col>
    <el-col :span="19" :xs="24">
      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="90px"
        >
          <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="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="课程类型" 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="courseContent" width="120px">
            【预览查看】
          </el-table-column>
          <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="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>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <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 { handleTree } from '@/utils/tree'
import { CourseTypeApi } from '@/api/bjdx/coursetype'
import { getTenantId } from '@/utils/auth'

/** 课程 列表 */
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 treeSearchValue = ref('') // 树形搜索值

// 从字典获取课程类型列表
const courseTypeList = computed(() => {
  return getStrDictOptions(DICT_TYPE.COURSE_TYPE).map(dict => ({
    id: dict.value,
    name: dict.label
  }))
})

/** 打开预览弹窗 */
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
  treeSearchValue.value = '' // 清空搜索框
  getCourseTypeTree(ctTypeNode).then(() => {
    // 选择课程类型后自动搜索
    handleQuery()
  })
}

/** 处理课程类型节点点击 */
const handleCourseTypeClick = (data) => {
  queryParams.courseType = data.id
  handleQuery()
}

/** 处理树形搜索 */
const handleTreeSearch = () => {
  // 搜索时自动清除当前选中的课程类型
  queryParams.courseType = undefined
}

/** 过滤树形数据 */
const filteredCourseTypeTree = computed(() => {
  if (!treeSearchValue.value) {
    return courseTypeTree.value
  }

  const filterTree = (nodes, keyword) => {
    return nodes.map(node => {
      const newNode = { ...node }
      // 检查节点是否匹配搜索关键词
      const isMatch = newNode.ctType && newNode.ctType.toLowerCase().includes(keyword.toLowerCase())

      // 如果有子节点，递归过滤
      if (newNode.children && newNode.children.length > 0) {
        const filteredChildren = filterTree(newNode.children, keyword)

        // 如果节点匹配或有匹配的子节点，则显示该节点
        if (isMatch || filteredChildren.length > 0) {
          newNode.children = filteredChildren
          return newNode
        }
        return null
      }

      // 叶子节点如果匹配则显示
      return isMatch ? newNode : null
    }).filter(Boolean)
  }

  return filterTree(courseTypeTree.value, treeSearchValue.value)
})

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.ctTypeNode = "1"
  queryParams.courseType = undefined
  treeSearchValue.value = '' // 清空搜索框
  getCourseTypeTree().then(() => {
    handleQuery()
  })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, queryParams.ctTypeNode, 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 === '-1' || item.ctTypeNode === filterCtTypeNode)
  }
  const courseTypeItem = courseTypeList.value.find(item => item.id === filterCtTypeNode)
  const root = { id: 0, ctType: '课程类型（' + courseTypeItem.name + '）', children: [] }
  root.children = handleTree(filteredData, 'id', 'ctParentId')
  courseTypeTree.value = [root]
}

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

<style scoped>
/* 优化滚动条样式 */
:deep(.custom-scrollbar) {
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc #f0f2f5;
}

/* 兼容WebKit浏览器（Chrome、Safari等） */
:deep(.custom-scrollbar::-webkit-scrollbar) {
  width: 3px;
  height: 3px;
}

:deep(.custom-scrollbar::-webkit-scrollbar-track) {
  background: #f0f2f5;
  border-radius: 3px;
}

:deep(.custom-scrollbar::-webkit-scrollbar-thumb) {
  background: #c0c4cc;
  border-radius: 3px;
  transition: background 0.3s;
}

:deep(.custom-scrollbar::-webkit-scrollbar-thumb:hover) {
  background: #909399;
}
</style>
