<script lang="ts" setup>
/**
 * VIP 等级新增/编辑弹窗
 * permissions 从 VIP 功能字典 option 多选
 */
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getVipFeatureOption } from '#/views/system/vip/feature/api';

import { createVipLevel, updateVipLevel } from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
const [Form, formApi] = useVbenForm(modalFormProps);
const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    modalApi.setState({ confirmLoading: true });
    try {
      const api = isUpdate.value ? updateVipLevel : createVipLevel;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    // 打开时拉取功能字典，注入 permissions 下拉
    try {
      const opts = await getVipFeatureOption();
      formApi.updateSchema([
        {
          fieldName: 'permissions',
          componentProps: {
            mode: 'multiple',
            allowClear: true,
            optionFilterProp: 'label',
            placeholder: '从功能字典多选',
            options: Array.isArray(opts) ? opts : [],
          },
        },
      ]);
    } catch (e) {
      console.error('加载 VIP 功能字典失败', e);
    }
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    if (values && update) {
      formApi.setValues({
        ...values,
        permissions: Array.isArray(values.permissions) ? values.permissions : [],
      });
    } else {
      formApi.resetForm();
      formApi.setValues({
        tier_group: 0,
        level_weight: 0,
        price: 0,
        sort: 0,
        status: 1,
        permissions: [],
        badge_url: '',
      });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}VIP等级`" class="w-[640px]">
    <Form />
  </Modal>
</template>
