<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="课程类型">
        <el-select
          v-model="formData.ctTypeNode"
          placeholder="请选择课程类型"
          @change="handleCtTypeNodeChange"
        >
          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.COURSE_TYPE)"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="大纲课程" prop="courseType">
        <el-tree-select
          v-model="formData.courseType"
          :data="courseTypeTree"
          :props="{...defaultProps,
            label: (node) => `${node.ctTypeNode === '0' || node.ctTypeNode === '-1' || node.ctTypeNode === undefined ? node.ctType : node.ctTypeSort + '、' + node.ctType}`,
            // 根据 ctTypeNode 字段判断是否禁用选项
            disabled: (node) => node.ctTypeNode === '0' || node.ctTypeNode === '-1',
            // 明确指定 value 字段为 id
            value: 'id'
            }"
          placeholder="请选择课程类型"
          :default-expand-all="true"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
      </el-form-item>

      <el-form-item label="课程标签" prop="courseLabel">
        <el-select
          v-model="formData.courseLabel"
          placeholder="请选择课程标签"
          clearable
        >
          <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="courseContentType">
        <el-radio-group v-model="formData.courseContentType">
          <el-radio-button v-for="dict in getStrDictOptions(DICT_TYPE.COURSE_COUTNET_TYPE)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'all'" label="课程内容" prop="courseContent">
        <Editor v-model="formData.courseContent" height="150px" />
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'text'" label="纯文本" prop="coursePath">
        <Editor v-model="formData.courseContent" height="150px"  />
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'image'" label="课程图片集" prop="coursePath">
        <UploadImgs v-model="formData.courseImagePath"
                    @upload-progress="handleUploadProgress"
                    @upload-start="handleUploadStart"
                    @upload-complete="handleUploadComplete"/>
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'music'" label="课程音频" prop="coursePath">
        <UploadMusic v-model="formData.courseMusicPath"
                     @upload-progress="handleUploadProgress"
                     @upload-start="handleUploadStart"
                     @upload-complete="handleUploadComplete"/>
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'video'" label="课程视频" prop="coursePath">
        <UploadVideo
          v-model="formData.courseVideoPath"
          @upload-progress="handleUploadProgress"
          @upload-start="handleUploadStart"
          @upload-complete="handleUploadComplete"
        />
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'ppt'" label="课程PPT" prop="courseFilePath">
        <UploadFile v-model="formData.courseFilePath" :fileType="['ppt','pptx']" :fileSize="50"
                    :limit="1"
                    @upload-progress="handleUploadProgress"
                    @upload-start="handleUploadStart"
                    @upload-complete="handleUploadComplete"/>
      </el-form-item>

      <!-- 上传进度条 -->
      <el-form-item>
        <div v-if="isUploading" class="uploadProgress">
          <el-progress :percentage="uploadProgress" />
          <div class="text-xs text-gray-500 text-right mt-1">{{ uploadProgress }}% 已上传</div>
        </div>
      </el-form-item>

      <el-form-item v-if="formData.courseContentType === 'ailab'" label="AI生成课" prop="courseContent">
        <div class="flex items-center">
          <el-button type="primary" @click="handleAiGenerateClick">{{ isScriptValid ? '编辑脚本' : 'AI创作' }}</el-button>
          <el-icon v-if="isScriptValid" class="ml-2 text-green-500"><i-ep-check /></el-icon>
          <span v-if="isScriptValid" class="ml-1 text-green-500 text-sm">脚本校验通过！</span>
        </div>
      </el-form-item>

      <template v-if="formData.courseContentType === 'quest'">
        <el-form-item >
          <br/><h2>问题</h2><br/>

        </el-form-item>

        <div style="width: 80%;margin: 0px auto">
          <!-- 基础信息 -->
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">题目标题</label>
            <input
              v-model="formData.courseBlocklyJson.title"
              class="w-full border border-gray-300 rounded p-2"
              placeholder="输入题目标题"
            />
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">题目描述</label>
            <textarea
              v-model="formData.courseBlocklyJson.description"
              class="w-full border border-gray-300 rounded p-2"
              rows="3"
              placeholder="输入题目描述"
            ></textarea>
          </div>

          <!-- 迷宫地图配置 -->
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">迷宫尺寸</label>
            <div class="flex gap-2">
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.width"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                min="5"
                max="20"
                placeholder="宽度"
              />
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.height"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                min="5"
                max="20"
                placeholder="高度"
              />
            </div>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">墙坐标（JSON 数组，如 [[0,1]]）</label>
            <textarea
              v-model="formData.courseBlocklyJson.mazeConfig.walls"
              class="w-full border border-gray-300 rounded p-2"
              rows="3"
              placeholder="输入墙坐标"
            ></textarea>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">起点坐标</label>
            <div class="flex gap-2">
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.start[0]"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                placeholder="X"
              />
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.start[1]"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                placeholder="Y"
              />
            </div>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">终点坐标</label>
            <div class="flex gap-2">
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.end[0]"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                placeholder="X"
              />
              <input
                v-model.number="formData.courseBlocklyJson.mazeConfig.end[1]"
                class="w-1/2 border border-gray-300 rounded p-2"
                type="number"
                placeholder="Y"
              />
            </div>
          </div>

          <!-- 初始积木配置 -->
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">初始积木（JSON 数组，如 {"type":"move_forward","count":3} ）</label>
            <textarea
              v-model="formData.courseBlocklyJson.initialBlocks"
              class="w-full border border-gray-300 rounded p-2"
              rows="3"
              placeholder="输入初始积木配置"
            ></textarea>
          </div>

          <!-- 答案配置 -->
          <div class="mb-4">
            <label class="block text-gray-700 font-medium mb-1">参考解法代码</label>
            <textarea
              v-model="formData.courseBlocklyJson.solutionCode"
              class="w-full border border-gray-300 rounded p-2"
              rows="3"
              placeholder="输入参考代码（如 moveForward(3); turnRight(); ）"
            ></textarea>
          </div>
        </div>
      </template>

      <template v-else>
        <el-form-item label="课程是否有检查" prop="courseIsInspect">
          <el-radio-group v-model="formData.courseIsInspect">
            <el-radio
              v-for="dict in getStrDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程耗时" prop="courseTime">
          <el-input-number v-model="formData.courseTime" :min="1" :step="1" step-strictly>
            <template #suffix><span>分</span></template>
          </el-input-number>
        </el-form-item>
      </template>

      <el-form-item label="课程排序" prop="courseOrder">
        <el-input-number v-model="formData.courseOrder" placeholder="请输入课程排序" class="!w-1/1" />
      </el-form-item>
      <el-form-item label="课程状态" prop="courseStatus">
        <el-radio-group v-model="formData.courseStatus">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || isUploading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- AI 生成课程页面 -->
  <AiGengrate v-model:visible="showAiGengrate" :initial-step="aiGengrateStep" :initial-script-data="formData.courseContent" @save="handleAiSave" />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CourseApi, CourseVO } from '@/api/bjdx/course'
import { defaultProps, handleTree } from '@/utils/tree'
import { CourseTypeApi } from '@/api/bjdx/coursetype'
import { deleteFileByUrl } from '@/api/infra/file'
import AiGengrate from './aiGenerate/aiGengrate.vue'

/** 课程 表单 */
defineOptions({ name: 'CourseForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const showAiGengrate = ref(false) // 控制 AI 生成页面的显示
const aiGengrateStep = ref(1) // 控制 AI 生成页面的初始步骤

// 计算属性：检查 courseContent 的 JSON 脚本是否合规
const isScriptValid = computed(() => {
  if (!formData.value.courseContent) return false
  try {
    const scriptData = JSON.parse(formData.value.courseContent)
    // 这里可以根据实际需求添加更详细的验证逻辑
    return typeof scriptData === 'object' && scriptData !== null
  } catch (error) {
    return false
  }
})
const formData = ref({
  id: undefined,
  ctTypeNode: undefined,
  courseName: undefined,
  courseContentType: undefined,
  courseImagePath: undefined,
  courseVideoPath: undefined,
  courseMusicPath: undefined,
  courseFilePath: undefined,
  courseContent: undefined,
  courseBlocklyJson:{
    title: '',
    description: '',
    mazeConfig: {
      width: 10,
      height: 10,
      walls: [],
      start: [0, 0],
      end: [9, 9]
    },
    initialBlocks: [],
    solutionCode: ''
  },
  courseAuthor: undefined,
  courseTeacher: undefined,
  courseSize: undefined,
  courseTime: undefined,
  courseIsInspect: "false",
  courseType: undefined,
  courseLabel: undefined,
  courseOrder: undefined,
  courseStatus: "0",
  tenantId: undefined,
  replacedUrls: [],
})

// 添加上传进度相关的状态
const uploadProgress = ref(0)
const isUploading = ref(false)

const formRules = reactive({
  courseType: [{ required: true, message: '课程类型不能为空', trigger: 'blur' }],
  courseName: [{ required: true, message: '课程名称不能为空', trigger: 'blur' },
    {max: 10, message: '长度不能超过10', trigger: 'blur' }],
  courseContent: [{ required: true, message: '课程内容不能为空', trigger: 'blur' }],
  courseLabel: [{ required: true, message: '课程标签不能为空', trigger: 'blur' }],
  courseOrder: [{ required: true, message: '课程排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const courseTypeTree = ref() // 树形结构

/** 打开弹窗 */
const open = async (type: string, typeNode: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const courseData = await CourseApi.getCourse(id)
      formData.value = {
        ...formData.value,
        ...courseData,
        // courseLabel: courseData.courseLabel?.split(','),
        courseImagePath: courseData.courseImagePath?.split(',')
      }
      // 确保 courseType 为正确的 id 类型
      formData.value.courseType = courseData.courseType ? Number(courseData.courseType) : undefined
    } finally {
      formLoading.value = false
    }
  }
  formData.value.ctTypeNode = typeNode
  await getCourseTypeTree(typeNode)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as CourseVO
    if (data.courseContentType === 'image') {
      data.courseImagePath = data.courseImagePath?.join(',')
    }
    // data.courseLabel = data.courseLabel?.join(',')
    if (formType.value === 'create') {
      await CourseApi.createCourse(data)
      message.success(t('common.createSuccess'))
    } else {
      await CourseApi.updateCourse(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false

    // 删除所有被替换的URL链接
    if (formData.value.replacedUrls && formData.value.replacedUrls.length > 0) {
      for (const url of formData.value.replacedUrls) {
        try {
          console.log('删除文件:', url)
          await deleteFileByUrl(url)
        } catch (error) {
          console.error('删除文件失败:', error)
        }
      }
    }

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 添加处理上传进度的方法
const handleUploadProgress = (progress: number) => {
  uploadProgress.value = progress
}

const handleUploadStart = () => {
  isUploading.value = true
  uploadProgress.value = 0
}

const handleUploadComplete = () => {
  isUploading.value = false
  uploadProgress.value = 100
}

// 处理 AI 生成课程保存
const handleAiSave = (scriptData, replacedUrls) => {
  formData.value.courseContent = JSON.stringify(scriptData)
  formData.value.courseContentType = 'ailab'
  formData.value.replacedUrls = replacedUrls
  showAiGengrate.value = false
}

// 处理 AI 生成按钮点击
const handleAiGenerateClick = () => {
  // 根据脚本是否有效设置初始步骤
  aiGengrateStep.value = isScriptValid.value ? 2 : 1
  showAiGengrate.value = true
}

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ctTypeNode: undefined,
    courseName: undefined,
    courseContentType: undefined,
    courseImagePath: undefined,
    courseVideoPath: undefined,
    courseFilePath: undefined,
    courseContent: undefined,
    courseBlocklyJson:{
      title: '',
      description: '',
      mazeConfig: {
        width: 10,
        height: 10,
        walls: [],
        start: [0, 0],
        end: [9, 9]
      },
      initialBlocks: [],
      solutionCode: ''
    },
    courseAuthor: undefined,
    courseTeacher: undefined,
    courseSize: undefined,
    courseTime: undefined,
    courseIsInspect: "false",
    courseType: undefined,
    courseLabel: undefined,
    courseOrder: undefined,
    courseStatus: "0",
    tenantId: undefined,
    replacedUrls: [],
  }
  formRef.value?.resetFields()
}
/** 获得课程-类型树 */
const getCourseTypeTree = async (filterCtTypeNode) => {

  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 root: Tree = { id: 0, ctType: '课程类型', ctTypeNode: '0', children: [] }
  root.children = handleTree(filteredData, 'id', 'ctParentId')
  courseTypeTree.value.push(root)
}
</script>

<style>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}
.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}
.uploadProgress{
  width: 50%;
}
</style>
