<script lang="ts" setup>
import type { FeatureApi } from '#/api/product-manage';

import { computed, ref } from 'vue';

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

import { useVbenForm } from '#/adapter/form';
import { createFeature, updateFeature } from '#/api/product-manage';

import { useFormSchema } from '../data';

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

const formData = ref<FeatureApi.FeatureItem>();

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});

const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = (await formApi.getValues()) as Record<string, unknown>;
    if (values.no_offline) {
      values.whitelist_price = -1;
    }
    delete values.no_offline;
    drawerApi.lock();
    try {
      const payload = values as unknown as FeatureApi.CreateFeatureRequest & FeatureApi.UpdateFeatureRequest;
      await (id.value
        ? updateFeature(id.value, payload)
        : createFeature(payload));
      emit('success');
      drawerApi.close();
    } catch {
      drawerApi.unlock();
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<FeatureApi.FeatureItem>();
      formApi.resetForm();
      if (data) {
        formData.value = data;
        id.value = data.id;
        const noOffline = (data.whitelist_price ?? 0) < 0;
        formApi.setValues({
          ...data,
          no_offline: noOffline,
          whitelist_price: noOffline ? 0 : (data.whitelist_price ?? 0),
        });
      } else {
        id.value = undefined;
      }
    }
  },
});

const getDrawerTitle = computed(() => {
  return formData.value?.id ? '编辑模块' : '创建模块';
});
</script>

<template>
  <Drawer :title="getDrawerTitle">
    <Form />
  </Drawer>
</template>
