<script lang="ts" setup>
import { computed, ref } from 'vue';

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

import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { getAgentWallet, updateAgentWalletBalance } from '#/api/agent';
import type { AgentApi } from '#/api/agent';

interface ModalData {
  agentId: number;
}

// 钱包信息
const walletInfo = ref<AgentApi.AgentWalletInfo>({
  balance: 0,
  frozen_balance: 0,
  total_earnings: 0,
});

const loading = ref(false);

const emit = defineEmits<{
  (e: 'success'): void;
}>();

const [ModalComponent, modalApi] = useVbenModal({
  title: '修改余额',
  destroyOnClose: true,
  onOpenChange(isOpen) {
    if (isOpen) {
      fetchWalletInfo();
      // 重置表单
      formApi.setValues({
        operation_type: 'add',
        amount: undefined,
      });
    }
  },
});

const modalData = computed(() => modalApi.getData<ModalData>());

// 获取钱包信息
async function fetchWalletInfo() {
  const agentId = modalData.value?.agentId;
  if (!agentId) return;

  try {
    loading.value = true;
    const data = await getAgentWallet(agentId);
    walletInfo.value = data;
  } catch (error: any) {
    message.error(error.message || '获取钱包信息失败');
  } finally {
    loading.value = false;
  }
}

// 表单引用
const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'RadioGroup',
      fieldName: 'operation_type',
      label: '操作类型',
      componentProps: {
        options: [
          { label: '增加余额', value: 'add' },
          { label: '减少余额', value: 'subtract' },
        ],
      },
      rules: 'required',
      defaultValue: 'add',
    },
    {
      component: 'InputNumber',
      fieldName: 'amount',
      label: '金额',
      componentProps: {
        precision: 2,
        min: 0.01,
        placeholder: '请输入金额',
        style: { width: '100%' },
      },
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

// 提交前确认
async function handleSubmit() { 
  try {
    const { valid } = await formApi.validate();
    if (!valid) return;

    const values = await formApi.getValues();
    if (!values) return;

    // 根据操作类型确定金额正负
    const finalAmount = values.operation_type === 'subtract' ? -Math.abs(values.amount) : Math.abs(values.amount);

    // 二次确认
    Modal.confirm({
      title: '确认修改余额',
      content: `您确定要${values.operation_type === 'add' ? '增加' : '减少'} ¥${Math.abs(values.amount).toFixed(2)} 的余额吗？`,
      onOk: async () => {
        try {
          await updateAgentWalletBalance({
            agent_id: modalData.value?.agentId || 0,
            amount: finalAmount,
          });

          message.success('修改余额成功');
          modalApi.close();
          emit('success');
        } catch (error: any) {
          message.error(error.message || '修改余额失败');
        }
      },
    });
  } catch (error) {
    // 表单验证失败，不处理
  }
}

// 重置表单
function handleReset() {
  formApi.setValues({
    operation_type: 'add',
    amount: undefined,
  });
}
</script>

<template>
  <ModalComponent width="500px" :footer="false">
    <div class="balance-modal">
      <Form />
      <div class="form-actions">
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleSubmit">确认修改</a-button>
      </div>
    </div>
  </ModalComponent>
</template>

<style lang="less" scoped>
.balance-modal {
  padding: 16px 0;

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
  }
}
</style>
