<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { CaseItem, CaseFormData, CaseStep } from '../types'
import { useMapStore } from '@/stores/map'
import CaseSteps from './CaseSteps.vue'
import { pick } from 'lodash-es'

interface Props {
  data?: CaseItem
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'submit', data: any): void
}>()

const router = useRouter()

// 实验类型
const types = useMapStore().getMapValuesByKey('experiment_type')

const formRef = $ref<FormInstance>()
const form = reactive<CaseFormData>({
  name: '',
  times: '',
  type: '',
  content: '',
})

// 步骤数据
const steps = ref<CaseStep[]>([{ id: 'task1', type: 2, name: '任务1' }])

watch(
  () => props.data,
  (value) => {
    if (value) {
      Object.assign(form, value)
      try {
        steps.value = JSON.parse(value.content)
      } catch (error) {
        steps.value = []
        console.error(error)
      }
    }
  }
)

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入案例名称', trigger: 'blur' }],
  times: [{ required: true, message: '请输入案例课时数', trigger: 'blur' }],
  type: [{ required: true, message: '请选择案例所属实验类型', trigger: 'change' }],
})

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const submitData = { ...pick(form, ['name', 'times', 'type']), content: JSON.stringify(steps.value) }
    emit('submit', submitData)
  })
}
</script>

<template>
  <h4>基础信息</h4>
  <el-form ref="formRef" :model="form" :rules="rules" inline>
    <el-form-item label="案例名称" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="案例课时数" prop="times">
      <el-input v-model="form.times"></el-input>
    </el-form-item>
    <el-form-item label="案例所属实验类型" prop="type">
      <el-select v-model="form.type">
        <el-option v-for="item in types" :key="item.id" v-bind="item"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <el-divider />
  <h4>案例步骤</h4>

  <!-- 步骤流程图 -->
  <CaseSteps v-model="steps" />

  <el-row justify="center">
    <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
    <el-button round auto-insert-space @click="router.back()">取消</el-button>
  </el-row>
</template>
