<script lang="ts" setup>
import type { AgentApi } from '#/api/agent';

import { ref } from 'vue';

import { Button, InputNumber } from 'ant-design-vue';

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

import { updateAgentProductionConfig } from '#/api/agent';

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

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

const formData = ref<AgentApi.AgentProductionConfigItem>();
const id = ref<number>();

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});
const drawerTitle = ref('产品配置');

const [Drawer, drawerApi] = useVbenDrawer({
  title: drawerTitle.value,
  destroyOnClose: true,
  async onConfirm() {
    const valid = await formApi.validate();
    if (!valid || !id.value) return;

    const values = await formApi.getValues();
    const params: AgentApi.UpdateAgentProductionConfigParams = {
      id: id.value,
      base_price: values.base_price,
      price_range_max: values.price_range_max,
      price_threshold: values.price_threshold ?? undefined,
      price_fee_rate: values.price_fee_rate ? values.price_fee_rate / 100 : undefined,
    };

    await updateAgentProductionConfig(params);

    emit('success');
    drawerApi.close();
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<AgentApi.AgentProductionConfigItem>();
      formApi.resetForm();
      if (data) {
        formData.value = data;
        id.value = data.id;
        formApi.setValues({
          ...data,
          price_threshold: data.price_threshold ?? undefined,
          price_fee_rate: data.price_fee_rate ? data.price_fee_rate * 100 : undefined,
        });
      } else {
        id.value = undefined;
      }
    }
  },
});
</script>

<template>
  <Drawer :title="drawerTitle">
    <Form>
      <template #price_threshold="slotProps">
        <div class="flex items-center gap-2">
          <InputNumber :value="slotProps.componentField.modelValue" :min="0" :precision="2" :step="0.01"
            placeholder="可选，不设置则不限制" class="flex-1" @update:value="slotProps.componentField['onUpdate:modelValue']" />
          <Button type="link" size="small" @click="() => {
            formApi.setFieldValue('price_threshold', undefined);
            formApi.setFieldValue('price_fee_rate', undefined);
          }">
            不设置
          </Button>
        </div>
      </template>
      <template #price_fee_rate="slotProps">
        <div class="flex items-center gap-2">
          <InputNumber :value="slotProps.componentField.modelValue" :min="0" :max="100" :precision="4" :step="0.01"
            addon-after="%" placeholder="可选，不设置则不收费" class="flex-1"
            @update:value="slotProps.componentField['onUpdate:modelValue']" />
          <Button type="link" size="small" @click="() => {
            formApi.setFieldValue('price_fee_rate', undefined);
          }">
            不设置
          </Button>
        </div>
      </template>
    </Form>
  </Drawer>
</template>
