<script setup lang="ts">
import type { EventProp, ConnectionOptionProp } from '../types'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createMetaEvent, updateMetaEvent } from '../api'

interface Props {
  data?: EventProp
  option: ConnectionOptionProp[]
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const isUpdate = $computed(() => {
  return !!props.data?.id
})
const title = $computed(() => {
  return isUpdate ? '修改事件属性' : '新建事件属性'
})

const formRef = $ref<FormInstance>()
const form = reactive(
  props.data || {
    name: '',
    english_name: '',
    experiment_connection_id: '',
    status: '1'
  }
)

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入' }],
  english_name: [{ required: true, message: '请输入' }],
  experiment_connection_id: [{ required: true, message: '请选择' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    isUpdate ? handleUpdate() : handleCreate()
  })
}

// 新建
function handleCreate() {
  createMetaEvent(form).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate() {
  updateMetaEvent(form).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="600px" @closed="$emit('update:modelValue', false)">
    <el-form ref="formRef" :model="form" :rules="rules" label-suffix="：" label-width="140px">
      <el-form-item label="事件ID" prop="id" v-if="isUpdate">
        <span>{{ props.data?.id }}</span>
      </el-form-item>
      <el-form-item label="事件英文名称" prop="english_name">
        <el-input v-model="form.english_name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="事件名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所属连接" prop="experiment_connection_id">
        <el-select
          :disabled="isUpdate"
          v-model="form.experiment_connection_id"
          style="width: 100%"
          placeholder="请选择">
          <el-option :label="item.type_name" :value="item.id" :key="item.id" v-for="item in props.option"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-text="生效" inactive-text="失效" active-value="1" inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
