<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="课程名称" prop="ccCourseId">
        <el-input v-model="formData.courseName" placeholder="请输入课程名称" :disabled="true" />
        <el-input v-model="formData.ccCourseId" type="hidden" />
        <!-- 隐藏真实课程id -->
      </el-form-item>

      <el-row>
        <el-col :span="16">
          <el-form-item label="课程暂停时长" required>
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input-number v-model="formData.ccHours" :min="0" :step="1" step-strictly :precision="0" style="width: 140px;">
                <template #suffix><span>时</span></template>
              </el-input-number>
              <el-input-number v-model="formData.ccMinutes" :min="0" :max="59" :step="1" step-strictly :precision="0" style="width: 140px;">
                <template #suffix><span>分</span></template>
              </el-input-number>
              <el-input-number v-model="formData.ccSeconds" :min="0" :max="59" :step="1" step-strictly :precision="0" style="width: 140px;">
                <template #suffix><span>秒</span></template>
              </el-input-number>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否显示答案" prop="ccAnswerJudge" >
            <el-radio-group v-model="formData.ccAnswerJudge">
              <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-col>
        <el-col :span="24">
          <br/>
          <el-form-item label="问题呈现类型" prop="ccQuestSource" required>
            <el-segmented v-model="formData.ccQuestSource" :options="getStrDictOptions(DICT_TYPE.COURSE_QUEST_SHOW_TYPE)" />
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="formData.ccQuestSource === '1'" required>
          <el-form-item label="试题内容" prop="ccQuestContent">
            <Editor v-model="formData.ccQuestContent" height="150px" />
          </el-form-item>

          <el-form-item label="试题选项" prop="ccQuestOption">
            <el-input v-model="formData.ccQuestOption" placeholder="请输入试题选项（ 示例：多个选项用英文,分割 ）" />
          </el-form-item>

          <el-form-item label="答  案" prop="ccAnswer">
            <el-input v-model="formData.ccAnswer" placeholder="请输入答案" />
          </el-form-item>

          <el-form-item label="Ai问题提示" prop="ccAiQuestTip">
            <el-input v-model="formData.ccAiQuestTip" placeholder="请输入Ai问题提示（多条请使用英文,豆包分割）" />
          </el-form-item>

          <el-form-item label="Ai答案" prop="ccAiAnswer">
            <el-input v-model="formData.ccAiAnswer" placeholder="请输入Ai答案" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="formData.ccQuestSource === '2'">
        <ContentWrap>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="questQueryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="试题类型" prop="cqQuestType">
              <el-select
                v-model="questQueryParams.cqQuestType"
                placeholder="请选择试题类型"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.COURSE_QUESTION_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="试题内容" prop="cqQuestion">
              <el-input
                v-model="questQueryParams.cqQuestion"
                placeholder="请输入试题内容"
                clearable
                @keyup.enter="loadQuestionList"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="loadQuestionList"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
              >
              <el-button @click="resetQuestionQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
              >
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap>
          <el-table
            v-loading="questionLoading"
            :data="questionList"
            :stripe="true"
            :show-overflow-tooltip="true"
          >
            <el-table-column label="选择" width="80">
              <template #default="scope">
                <el-radio
                  v-model="formData.ccQuestId"
                  :label="scope.row.id"
                  @change="handleQuestionSelect(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="试题内容" align="center" prop="cqQuestion" >
              <template #default="scope">
                <div v-html="scope.row.cqQuestion"></div>
              </template>
            </el-table-column>
            <el-table-column label="试题解析" align="center" prop="cqQuestAnalysis" >
              <template #default="scope">
                <div v-html="scope.row.cqQuestAnalysis"></div>
              </template>
            </el-table-column>
            <el-table-column label="试题类型" align="center" prop="cqQuestType" >
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.COURSE_QUESTION_TYPE" :value="scope.row.cqQuestType" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="questionTotal"
            v-model:page="questQueryParams.pageNo"
            v-model:limit="questQueryParams.pageSize"
            @pagination="loadQuestionList"
          />
        </ContentWrap>
      </div>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
<!--      <el-button @click="submitForm" type="primary" :disabled="formLoading">同步内容</el-button>-->
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { BlocklyConfigApi, BlocklyConfigVO} from '@/api/blockly/blocklyConfig'
import { CourseQuestionApi} from '@/api/bjdx/coursequestion'



/** 合并后的课程配置与试题选择表单 */
defineOptions({ name: 'BlocklyConfigWithQuestionForm' })

const { t } = useI18n()
const message = useMessage()

// 原课程配置相关状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  ccCourseId: undefined, // 课程id（隐藏字段）
  courseName: undefined, // 课程名称（显示用）
  ccTime: 0, // 暂停时长总秒数（用于提交）
  ccHours: 0, // 小时
  ccMinutes: 0, // 分钟
  ccSeconds: 0, // 秒
  ccAnswerJudge: undefined, // 是否显示答案（必填）
  ccQuestId: undefined, // 选择的试题id
  ccQuestSource: '0', // 问题呈现类型
  ccQuestContent: undefined,  // 问题内容
  ccQuestOption: undefined,  // 问题选项
  ccAiQuestTip: undefined,  // AI问题提示
  ccAiAnswer: undefined,  // AI答案
  ccAnswer: undefined,  // 答案
  tenantId: undefined,
})
const formRules = reactive({
  ccHours: [{ required: true, message: t('common.required'), trigger: 'blur' }],
  ccMinutes: [{ required: true, message: t('common.required'), trigger: 'blur' }],
  ccSeconds: [{ required: true, message: t('common.required'), trigger: 'blur' }],
  ccQuestContent: [{ required: true, message: t('common.required'), trigger: 'change' }]
})
const formRef = ref()

// 试题列表相关状态
const questionLoading = ref(false)
const questionList = ref<any[]>([])
const queryParams = reactive({
  cqQuestType: undefined,
  cqQuestion: undefined
})
const selectedQuestIds = ref<number[]>([]) // 记录选中的试题id

/** 打开弹窗（新增参数：courseId, courseName） */
const open = async (type: string, id?: number, courseId?: number, courseName?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await BlocklyConfigApi.getCourseConfig(id)
      formData.value = data
      // 转换秒数为时分秒
      const totalSeconds = data.ccTime || 0
      formData.value.ccHours = Math.floor(totalSeconds / 3600)
      formData.value.ccMinutes = Math.floor((totalSeconds % 3600) / 60)
      formData.value.ccSeconds = totalSeconds % 60
    } finally {
      formLoading.value = false
    }
  }

  // 初始化课程信息
  formData.value.ccCourseId = courseId
  formData.value.courseName = courseName

  // 加载试题列表
  await loadQuestionList()
}

/** 新增试题分页相关状态 */
const questionTotal = ref(0) // 总条数

const questQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  cqQuestion: undefined,
  cqQuestAnalysis: undefined,
  cqQuestType: undefined,
  cqQuestAnswerId: undefined
})

/** 加载试题列表（修改分页参数传递） */
const loadQuestionList = async () => {
  questionLoading.value = true
  try {
    const res = await CourseQuestionApi.getCourseQuestionPage(questQueryParams)
    questionList.value = res.list
    questionTotal.value = res.total // 更新总条数
  } finally {
    questionLoading.value = false
  }
}

/** 重置试题筛选 */
const resetQuestionQuery = () => {
  questQueryParams.cqQuestType = undefined
  questQueryParams.cqQuestion = undefined
  loadQuestionList()
}

/** 处理试题选择 */
const handleQuestionSelect = (row: any) => {
  formData.value.ccQuestId = row.id // 同步到表单数据
}


/** 提交表单（修改：包含ccQuestId） */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 计算总秒数
    const ccTime = formData.value.ccHours * 3600 + formData.value.ccMinutes * 60 + formData.value.ccSeconds
    formData.value.ccTime = ccTime
    
    const data = formData.value as unknown as BlocklyConfigVO
    if (formType.value === 'create') {
      await BlocklyConfigApi.createCourseConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await BlocklyConfigApi.updateCourseConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单（重置试题相关状态） */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ccCourseId: undefined,
    courseName: undefined,
    ccTime: 0,
    ccHours: 0,
    ccMinutes: 0,
    ccSeconds: 0,
    ccAnswerJudge: undefined,
    ccQuestId: undefined, // 选择的试题id
    ccQuestSource: '0', // 问题呈现类型
    ccQuestContent: undefined,  // 问题内容
    ccQuestOption: undefined,  // 问题选项
    ccAiQuestTip: undefined,  // AI问题提示
    ccAiAnswer: undefined,  // AI答案
    ccAnswer: undefined,  // 答案,
    tenantId: undefined,
  }
  formRef.value?.resetFields()
  selectedQuestIds.value = []
  questionList.value = []
}

defineExpose({ open })
</script>
