import type { Ref } from 'vue'
import { getExperimentExample } from '../api'

// 定义案例步骤类型
interface CaseStep {
  id: string
  type: number
  name: string
  content?: string
  config?: {
    operationSteps?: Array<{
      id: number
      content: string
      relatedFunction?: {
        id: number
        name: string
        path: string
      }
    }>
  }
}

// 定义案例详情类型
interface CaseDetail {
  id: string
  name: string
  times: string
  type: string
  status: string
  created_operator: string
  created_time: string
  updated_operator: string
  updated_time: string
  content: CaseStep[]
  delete_time: string
  status_name: string
  created_operator_name: string
  updated_operator_name: string
  type_name: string
}

export function useExample(experimentId: Ref<string>, emits: any) {
  const example = ref<CaseDetail>()
  const selectedTask = ref('task1')
  const selectedStep = ref(1)

  const tasks = computed(() => example.value?.content.filter((item) => item.type === 2) || [])

  const currentTask = computed(() => {
    return example.value?.content.find((item) => item.id === selectedTask.value)
  })

  const operationSteps = computed(() => {
    return currentTask.value?.config?.operationSteps || []
  })

  const currentStep = computed(() => {
    return operationSteps.value.find((item) => item.id === selectedStep.value)
  })

  const fetchExample = async () => {
    const res = await getExperimentExample({ experiment_id: experimentId.value })
    if (res.data.detail) {
      // 解析案例内容
      try {
        const content = JSON.parse(res.data.detail.content || '[]')
        example.value = { ...res.data.detail, content: content }
        selectedTask.value = tasks.value[0].id
        selectedStep.value = operationSteps.value[0].id
      } catch (error) {
        console.error('获取案例数据失败:', error)
      }
    } else {
      example.value = undefined
      emits('empty')
    }
  }

  watchEffect(() => {
    if (experimentId.value) {
      fetchExample()
    }
  })

  // 切换任务
  const switchTask = (taskId: string) => {
    selectedTask.value = taskId
    selectedStep.value = 1
  }

  // 切换操作步骤
  const switchStep = (stepId: number) => {
    selectedStep.value = stepId
  }

  return {
    example,
    tasks,
    currentTask,
    operationSteps,
    selectedTask,
    selectedStep,
    currentStep,
    switchTask,
    switchStep,
  }
}
