<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

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

import { useVbenForm } from '#/adapter/form';
import { getTransferAssistantConfig, updateTransferAssistantConfig } from '../api';

// 表单配置
const assistantFormProps = {
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  showDefaultActions: false,
  schema: [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入助理名字',
        maxlength: 100,
      },
      fieldName: 'name',
      label: '助理名字',
      rules: 'required',
    },
    {
      component: 'Avatar',
      componentProps: {
        maxCount: 1,
      },
      fieldName: 'avatar',
      label: '助理头像',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入回复延迟时间（秒）',
        min: 0,
        max: 10,
        step: 0.1,
        precision: 2,
      },
      fieldName: 'reply_delay',
      label: '回复延迟时间（秒）',
      defaultValue: 1.00,
      rules: 'required',
    },
  ],
};

const [Form, formApi] = useVbenForm(assistantFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        updateTransferAssistantConfig(values)
          .then(() => {
            message.success('保存成功');
            modalApi.close();
          })
          .catch((error) => {
            message.error(error?.message || '保存失败');
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 打开时加载当前配置
      loadConfig();
    }
  },
});

// 加载配置
const loadConfig = async () => {
  try {
    const res = await getTransferAssistantConfig();
    // 接口返回的数据结构：{ data: { code: 0, result: {...}, message: '...' } }
    // 用户说接口返回的已经是 result 中的数据，所以直接使用 res.data.result
    const result = res;
    if (result) {
      formApi.setValues(result);
    }
  } catch (error) {
    console.error('加载助理配置失败:', error);
  }
};
</script>

<template>
  <Modal
    title="配置助理信息"
    class="w-[60%]"
  >
    <Form />
  </Modal>
</template>
