<template>
  <el-form ref="formRef" :model="formData" :rules="ruleForm" label-width="80px">
    <el-form-item label="模板名称" prop="name">
      <el-input v-model.trim="formData.name" placeholder="输入模板名称" />
    </el-form-item>
    <el-form-item label="" prop="">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue';
import api from '/@/api/projects';
import { ruleRequired } from '/@/utils/validator';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['getList', 'cancel']);

const showDialog = ref(false);
const formRef = ref();

const baseForm = {
  id: undefined,
  name: '',
};

const formData = reactive({
  ...baseForm,
});

const ruleForm = {
  name: [ruleRequired('不能为空')],
};

const onSubmit = async () => {
  await formRef.value.validate();

  const theApi = formData.id ? api.template.edit : api.template.add;

  await theApi(formData);

  ElMessage.success('操作成功');
  // resetForm();
  showDialog.value = false;
  emit('getList');
};

const resetForm = async () => {
  Object.assign(formData, { ...baseForm });
  formRef.value && formRef.value.resetFields();
};

const cancel = () => {
  emit('cancel');
};

const open = async (row?: any) => {
  resetForm();
  showDialog.value = true;
  if (row) {
    console.log(row)
    Object.assign(formData, { ...row });
  }
};

defineExpose({ open });
</script>
