<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="400"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="isUpdate ? '编辑功能包' : '新建功能包'"
    :body-style="{ paddingBottom: '8px', height: '400px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules">
      <a-row :gutter="20">
        <a-col :span="24">
          <a-form-item label="功能包名称:" name="packageName">
            <a-input v-model:value="form.packageName" allow-clear placeholder="请输入功能包名称" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="功能包定价:" name="packagePrice">
            <a-input-number v-model:value="form.packagePrice" style="width: 100%" allow-clear placeholder="请输入功能包定价" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

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

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

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);
// 表单数据
const form = ref({});
// ref
const formRef = ref(null);

// 验证规则
const rules = reactive({
  packageName: [{ required: true, message: '请输入功能包名称', type: 'string', trigger: 'blur' }],
  packagePrice: [{ required: true, message: '请输入功能包定价', type: 'number', trigger: 'blur' }]
});

onMounted(() => {
  if (props.data) {
    isUpdate.value = true;
    form.value = Object.assign({}, props.data);
  } else {
    isUpdate.value = false;
  }
});

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

// 点击保存
const save = async () => {
  await formRef.value.validate();
  // 修改加载框为正在加载
  loading.value = true;
  let result = null;
  // 执行编辑或修改
  if (isUpdate.value) {
    result = PackageApi.edit(form.value);
  } else {
    result = PackageApi.add(form.value);
  }
  result
    .then(async result => {
      // 移除加载框
      loading.value = false;
      // 提示添加成功
      message.success(result.message);
      // 关闭弹框，通过控制visible的值，传递给父组件
      updateVisible(false);
      // 触发父组件done事件
      emits('done');
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>

<style></style>
