<route lang="yaml">
meta:
  enabled: false
</route>

<script lang="ts" setup name="Model">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createModel, getModelById, updateModel } from '@/api/model/modelApi'
const emit = defineEmits(['success'])

const formRef = ref<FormInstance>()
const formRules = ref<FormRules>({
  modelTitle: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  modelDesc: [
    { required: false, message: '请输入描述', trigger: 'blur' },
  ],
})

const state = reactive({
  title: '',
  dialogVisible: false,
  loading: false,
  formData: {
    modelId: 1,
    modelTitle: '',
    modelDesc: '',
  },
  actionType: 1,
})

onMounted(() => {})

const getData = async (modelId: number) => {
  state.loading = true
  const { data } = await getModelById(modelId)
  state.loading = false
  state.formData = data
}

function onSubmit() {
  formRef.value && formRef.value.validate(async (valid) => {
    if (valid) {
      if (state.actionType === 1) {
        const { msg } = await createModel(state.formData)
        ElMessage.success(msg)
        state.dialogVisible = false
        emit('success')
      }
      else {
        const { msg } = await updateModel(state.formData)
        ElMessage.success(msg)
        state.dialogVisible = false
        emit('success')
      }
    }
  })
}

function onCancel() {
  state.dialogVisible = false
}

function resetFormData() {
  state.formData = {
    modelId: -1,
    modelTitle: '',
    modelDesc: '',
  }
}

defineExpose({
  showAddModel() {
    resetFormData()
    state.title = '新增数据模型'
    state.actionType = 1
    state.dialogVisible = true
  },
  showEditModel(modelId: any) {
    resetFormData()
    state.title = '编辑数据模型'
    state.actionType = 2
    state.dialogVisible = true
    getData(modelId)
  },
})
</script>

<template>
  <el-drawer v-model="state.dialogVisible" :title="state.title" size="30%">
    <el-scrollbar class="form-el-scrollbar">
      <el-form ref="formRef" :model="state.formData" :rules="formRules" label-width="120px" label-suffix="：">
        <el-form-item label="模型名称" prop="modelTitle">
          <el-input v-model="state.formData.modelTitle" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="简要说明" prop="modelDesc">
          <el-input v-model="state.formData.modelDesc" type="textarea" rows="10" placeholder="请输入标题" />
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <template #footer>
      <div style="flex: auto">
        <el-button size="large" @click="onCancel">
          取消
        </el-button>
        <el-button type="primary" size="large" @click="onSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>
