<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="父级类型" prop="ctParentId">
        <el-tree-select
          :disabled="formType === 'update'"
          v-model="formData.ctParentId"
          :data="aiCourseTypeTree"
          :props="{...defaultProps,
            label: (node) => `${node.ctType}${node.ctTypeNode === '0' ? '（主题）' : '（类型）'}`,
            disabled: (node) => node.id !== 0 && node.ctTypeNode !== '0'
            }"
          :default-expanded-keys="[0]"
          check-strictly
          default-expand-all
          placeholder="请选择课程父级类型"
          @change="handleParentChange"
        />
      </el-form-item>
      <el-form-item label="课程类型节点" prop="ctTypeNode">
        <el-segmented 
          :disabled="formType === 'update'"
          v-model="formData.ctTypeNode"
          :options="segmentedOptions"
        />
      </el-form-item>
      <el-form-item label="课程类型名称" prop="ctType">
        <el-input v-model="formData.ctType" placeholder="请输入课程类型名称" />
      </el-form-item>
      <el-form-item label="课程封面" prop="ctTypeImage">
        <UploadImg v-model="formData.ctTypeImage" />
      </el-form-item>
      <el-form-item label="课程类型描述" prop="ctTypeDescribe">
        <el-input
          type="textarea"
          v-model="formData.ctTypeDescribe"
          placeholder="请输入课程类型描述"
        />
      </el-form-item>
      <el-form-item label="课程类型排序" prop="ctTypeSort">
        <el-input-number v-model="formData.ctTypeSort" :step="1" step-strictly placeholder="请输入课程类型排序"
                 class="!w-100%"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <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 { AiCourseTypeApi, AiCourseTypeVO } from '@/api/aiCourse/aiCourseType'
import { defaultProps, handleTree } from '@/utils/tree'

/** 课程-类型 表单 */
defineOptions({ name: 'AiCourseTypeForm' })

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 formData = ref({
  id: undefined,
  ctType: undefined,
  ctTypeImage: undefined,
  ctTypeNode: 0,
  ctTypeSort: undefined,
  ctParentId: 0,
  ctTypeDescribe: undefined,
  tenantId: undefined,
})
const formRules = reactive({
  ctParentId: [{ required: true, message: '父级节点不能为空', trigger: 'blur' }],
  ctTypeNode: [{ required: true, message: '节点类型不能为空', trigger: 'blur' }],
  ctType: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
  ctTypeSort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const aiCourseTypeTree = ref() // 树形结构

// 计算属性：判断父级ID是否为根节点（0）
const isRootParent = computed(() => {
  return formData.value.ctParentId === 0 || formData.value.ctParentId === '0'
})

// 分段控件选项（根据父级ID动态配置禁用状态）
const segmentedOptions = computed(() => {
  return [
    { label: '主题', value: '0', disabled: !isRootParent.value },  // 非根节点时禁用主题
    { label: '类型', value: '1', disabled: isRootParent.value },   // 根节点时禁用类型
  ]
})

// 处理父级类型变更
const handleParentChange = () => {
  if (isRootParent.value) {
    // 当父级是根节点时，强制设置为主题类型
    formData.value.ctTypeNode = '0'
  } else {
    // 当父级不是根节点时，如果当前类型是主题，则改为类型
    if (formData.value.ctTypeNode === '0' || formData.value.ctTypeNode === 0) {
      formData.value.ctTypeNode = '1'
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number, parentId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (parentId) {
    formData.value.ctParentId = parentId
    // 根据父级ID设置默认的类型节点
    if (parentId !== 0 && parentId !== '0') {
      formData.value.ctTypeNode = '1' // 非根节点时默认类型
    } else {
      formData.value.ctTypeNode = '0' // 根节点时默认主题
    }
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AiCourseTypeApi.getAiCourseType(id)
      // 确保类型与父级ID匹配
      if (isRootParent.value && formData.value.ctTypeNode !== '0') {
        formData.value.ctTypeNode = '0'
      } else if (!isRootParent.value && formData.value.ctTypeNode === '0') {
        formData.value.ctTypeNode = '1'
      }
    } finally {
      formLoading.value = false
    }
  }
  await getAiCourseTypeTree()
}
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 AiCourseTypeVO
    if (formType.value === 'create') {
      await AiCourseTypeApi.createAiCourseType(data)
      message.success(t('common.createSuccess'))
    } else {
      await AiCourseTypeApi.updateAiCourseType(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ctType: undefined,
    ctTypeNode: 0,
    ctTypeSort: undefined,
    ctParentId: 0,
    ctTypeDescribe: undefined,
    tenantId: undefined,
  }
  formRef.value?.resetFields()
}

/** 获得课程-类型树 */
const getAiCourseTypeTree = async () => {
  aiCourseTypeTree.value = []
  const data = await AiCourseTypeApi.getAiCourseTypeSimpleList()

  const filteredData = data.filter(item => item.ctTypeNode === '0')
  const root: Tree = { id: 0, ctType: '课程类型', children: [] }
  root.children = handleTree(filteredData, 'id', 'ctParentId')
  aiCourseTypeTree.value.push(root)
}
</script>
