<script lang="ts" setup>
/**
 * 门店 VIP 开通弹窗：选等级、时长预设（含 X 年）、备注；管理员开通实付 0
 */
import { computed, ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';

import { getVipLevelOption } from '../../level/api';
import { getVipDurationPresets, openVipStore } from '../api';

const gridApi = ref();
const storeId = ref(0);
const storeName = ref('');
const levelOptions = ref<{ label: string; value: number }[]>([]);
const presetOptions = ref<{ label: string; value: string }[]>([]);

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: { class: 'w-full' },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenSelect',
      fieldName: 'level_id',
      label: '会员等级',
      rules: 'selectRequired',
      componentProps: { options: [], placeholder: '请选择等级' },
    },
    {
      component: 'VbenSelect',
      fieldName: 'duration_preset',
      label: '开通时长',
      rules: 'selectRequired',
      componentProps: { options: [], placeholder: '请选择时长' },
    },
    {
      component: 'InputNumber',
      fieldName: 'custom_years',
      label: '自定义年数',
      dependencies: {
        show: (values: any) => values.duration_preset === 'xy',
        triggerFields: ['duration_preset'],
      },
      componentProps: { min: 1, max: 99, placeholder: '请输入年数' },
    },
    {
      component: 'VbenInput',
      fieldName: 'remark',
      label: '备注',
      componentProps: { type: 'textarea', rows: 2 },
      defaultValue: '',
    },
  ],
  showDefaultActions: false,
});

const title = computed(() => `开通VIP - ${storeName.value || storeId.value}`);

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();
    if (values.duration_preset === 'xy' && !(Number(values.custom_years) > 0)) {
      message.warning('请填写有效年数');
      return;
    }
    modalApi.setState({ confirmLoading: true });
    try {
      await openVipStore({
        store_id: storeId.value,
        level_id: values.level_id,
        duration_preset: values.duration_preset,
        custom_years: values.custom_years || 0,
        remark: values.remark || '',
      });
      message.success('开通成功');
      gridApi.value?.query();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    gridApi.value = data.gridApi;
    storeId.value = Number(data.store_id || 0);
    storeName.value = data.store_name || '';
    const vip = data.vip || null;
    const code = String(vip?.level_code || 'V0').trim() || 'V0';
    const expireAt = Number(vip?.expire_at || 0);
    // 非普通且未过期（含终身 expire_at=0）可继承剩余时间
    const canKeep =
      !!vip &&
      code !== 'V0' &&
      !(expireAt > 0 && expireAt * 1000 <= Date.now());
    const [levels, presets] = await Promise.all([
      getVipLevelOption(),
      getVipDurationPresets(),
    ]);
    levelOptions.value = (levels || []).map((i: any) => ({
      label: `${i.name}（${i.code}）¥${i.price}`,
      value: i.id,
    }));
    presetOptions.value = (presets || [])
      .filter((i: any) => i.value !== 'keep' || canKeep)
      .map((i: any) => ({
        label: i.label,
        value: i.value,
      }));
    formApi.updateSchema([
      {
        fieldName: 'level_id',
        componentProps: { options: levelOptions.value },
      },
      {
        fieldName: 'duration_preset',
        componentProps: { options: presetOptions.value },
      },
    ]);
    formApi.setValues({
      remark: '',
      custom_years: undefined,
      level_id: vip?.level_id ? Number(vip.level_id) : undefined,
      // 非普通会员默认继承剩余时间，不改动到期
      duration_preset: canKeep ? 'keep' : undefined,
    });
  },
});
</script>
<template>
  <Modal :title="title" class="w-[560px]">
    <Form />
  </Modal>
</template>
