<template>
  <el-dialog class="api-edit" v-model="showDialog" :title="`${formData?.id ? '编辑属性' : '新增属性'}`" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
    <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="属性KEY" prop="key">
        <el-input v-model.trim="formData.key" placeholder="输入属性名称" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model.trim="formData.unit" 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>
  </el-dialog>
</template>

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

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

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

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

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

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

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

  const theApi = formData.id ? api.template.attr.edit : api.template.attr.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 open = async (code: string, row?: any) => {
  resetForm();
  showDialog.value = true;
  formData.templateseCode = code

  if (row) {
    formData.id = row.id
    formData.name = row.name
    formData.key = row.key
    formData.unit = row.unit
  }
};

function cancel() {
  showDialog.value = false;
}

defineExpose({ open });
</script>
