<template>
  <el-row :gutter="20">
    <!-- 左侧课程类型树 -->
    <el-col :span="5" :xs="24">
      <ContentWrap class="h-1/1 custom-scrollbar" style="overflow-x: auto; overflow-y: auto; height: calc(100vh - 100px);">

        <!-- 搜索条件框 -->
        <div class="mb-20px">
          <el-input
            v-model="treeSearchValue"
            placeholder="搜索课程类型"
            prefix-icon="ep:search"
            clearable
            @input="handleTreeSearch"
            class="!w-full"
          />
        </div>

        <!-- 课程类型树形选择器 -->
        <el-tree
          v-model="queryParams.acType"
          :data="filteredCourseTypeTree"
          :props="{
            label: (node) => `${node.ctTypeNode === '0' || 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="acContentType">
            <el-select
              v-model="queryParams.acContentType"
              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="acName">
            <el-input
              v-model="queryParams.acName"
              placeholder="请输入课程名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="是否有检查" prop="acIsInspect">
            <el-select
              v-model="queryParams.acIsInspect"
              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="acLabel">
            <el-select
              v-model="queryParams.acLabel"
              placeholder="请选择课程标签"
              clearable
              class="!w-240px"
              @change="handleQuery"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AICOURSE_COURSE_LABEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程状态" prop="acStatus">
            <el-select
              v-model="queryParams.acStatus"
              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',queryParams.acType)"
              v-hasPermi="['aiCourse:course:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['aiCourse: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="acTypeName" />
          <el-table-column label="课程名称" align="center" prop="acName" />
          <el-table-column label="内容类型" align="center" prop="acContentType" >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COURSE_COUTNET_TYPE" :value="scope.row.acContentType" />
            </template>
          </el-table-column>
          <el-table-column label="课程内容" align="center" prop="acContent" width="120px">
            【预览查看】
          </el-table-column>
          <el-table-column label="是否有检查" align="center" prop="acIsInspect">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.acIsInspect" />
            </template>
          </el-table-column>
          <el-table-column label="课程标签" align="center" prop="acLabel">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.AICOURSE_COURSE_LABEL" :value="scope.row.acLabel" />
            </template>
          </el-table-column>
          <el-table-column label="课程排序" align="center" prop="acOrder"/>
          <el-table-column label="课程状态" align="center" prop="acStatus">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.acStatus" />
            </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="['aiCourse:course:update']"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.acContentType == 'video'"
                link
                type="success"
                title="仅视频课程可配置"
                @click="handleConfig(scope.row.id,scope.row.acName,scope.row.tenantId)"
              >
                配置
              </el-button>
              <el-button
                link
                type="danger"
                v-if="scope.row.tenantId == getTenantId()"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['aiCourse: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>

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

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import { AiCourseApi, AiCourseVO } from '@/api/aiCourse/aiCourse'
import AiCourseForm from './AiCourseForm.vue'
import { useRouter } from 'vue-router'
import { handleTree } from '@/utils/tree'
import { AiCourseTypeApi } from '@/api/aiCourse/aiCourseType'
import { getTenantId } from '@/utils/auth'

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

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

const loading = ref(true) // 列表的加载中
const list = ref<AiCourseVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const treeSearchValue = ref('') // 树形搜索值
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  acName: undefined,
  acContentType: undefined,
  acContent: undefined,

  acIsInspect: undefined,
  ctTypeNode: "1",//课程类型
  acType: undefined,
  acTypeName: undefined,
  acLabel: undefined,
  acOrder: undefined,
  acStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const acTypeTree = ref() // 原始树形结构
const filteredCourseTypeTree = computed(() => {
  if (!treeSearchValue.value) {
    return acTypeTree.value
  }

  const filterTree = (tree, searchText) => {
    return tree.map(node => {
      const newNode = { ...node }
      // 检查节点是否匹配搜索文本
      const isMatch = newNode.ctType && newNode.ctType.toLowerCase().includes(searchText.toLowerCase())

      // 如果有子节点，递归过滤
      if (newNode.children && newNode.children.length > 0) {
        const filteredChildren = filterTree(newNode.children, searchText)
        if (filteredChildren.length > 0 || isMatch) {
          newNode.children = filteredChildren
          return newNode
        }
      } else if (isMatch) {
        // 没有子节点但节点本身匹配
        return newNode
      }

      // 如果既没有匹配的子节点也不匹配自身，则返回null
      return null
    }).filter(node => node !== null) // 过滤掉null值
  }

  return filterTree([...acTypeTree.value], treeSearchValue.value)
})

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

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

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

/** 处理树搜索 */
const handleTreeSearch = () => {
  // 搜索时不需要自动查询列表，只过滤树节点
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.ctTypeNode = "1"
  queryParams.acType = undefined
  treeSearchValue.value = ''
  getacTypeTree().then(() => {
    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 AiCourseApi.deleteAiCourse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 配置按钮操作 */
const router = useRouter()
const handleConfig = (id: number, acName: string, tenantId: number) => {
  router.push({
    path: '/aiCourse/course-config',
    query: { acId: id, acName: acName, tenantId: tenantId }
  })
}

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

/** 获得课程-类型树 */
const getacTypeTree = async (filterCtTypeNode = "1") => {
  acTypeTree.value = []
  const data = await AiCourseTypeApi.getAiCourseTypeSimpleList()

  let filteredData = data
  if (filterCtTypeNode !== undefined) {
    filteredData = data.filter(item => item.ctTypeNode === '0' || item.ctTypeNode === filterCtTypeNode)
  }
  const root = { id: 0, ctType: '课程类型', children: [] }
  root.children = handleTree(filteredData, 'id', 'ctParentId')
  acTypeTree.value = [root]
}

/** 初始化 **/
onMounted(() => {
  getList()
  getacTypeTree()
})
</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>
