<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="500"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    title="编辑表单模板"
    :body-style="{ paddingBottom: '8px', height: '400px', overflowY: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="表单模板名称:" name="templateName">
        <a-input v-model:value="form.templateName" allow-clear placeholder="请输入表单模板名称" />
      </a-form-item>
      <a-form-item label="表单模板编码:" name="templateCode">
        <a-input v-model:value="form.templateCode" allow-clear placeholder="请输入表单模板编码" />
      </a-form-item>
      <a-form-item label="排序:" name="templateSort">
        <a-input-number
          v-model:value="form.templateSort"
          :min="0"
          style="width: 100%"
          placeholder="请输入排序"
          allow-clear
          autocomplete="off"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup name="TemplateManagerEdit">
import { ref, onMounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { TemplateManagerApi } from './api/TemplateManagerApi';

const props = defineProps({
  visible: Boolean,
  data: Object
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 表单数据
const form = ref({});
// 验证规则
const rules = reactive({
  templateName: [{ required: true, message: '请输入表单模板名称', type: 'string', trigger: 'blur' }],
  templateCode: [{ required: true, message: '请输入表单模板编码', type: 'string', trigger: 'blur' }],
  templateSort: [{ required: true, message: '请输入排序', type: 'number', trigger: 'blur' }]
});
// ref
const formRef = ref(null);

onMounted(async () => {
  getDetail();
});

// 获取详情
const getDetail = () => {
  TemplateManagerApi.detail({ id: props.data.id }).then(res => {
    form.value = Object.assign({}, res);
  });
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  formRef.value.validate().then(async valid => {
    if (valid) {
      // 修改加载框为正在加载
      loading.value = true;
      TemplateManagerApi.edit(form.value)
        .then(async result => {
          // 移除加载框
          loading.value = false;

          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);

          // 触发父组件done事件
          emits('done');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style></style>
