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

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

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

import { useVbenForm } from '#/adapter/form';
import { reviewBankCardWithdrawal } from '#/api/agent';
import type { VbenFormSchema } from '#/adapter/form';

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

const formData = ref<any>(null);
// 用于纯文字展示与实时计算：当前选择的审核操作、扣税比例
const currentAction = ref<1 | 2>(1);
const currentTaxRatePercent = ref(6);

const typeMap: Record<number, string> = {
  1: '支付宝',
  2: '银行卡',
};

// 根据当前扣税比例与提现金额实时计算
const previewTaxAmount = computed(() => {
  const amount = formData.value?.amount;
  if (amount == null || typeof amount !== 'number') return 0;
  const rate = currentTaxRatePercent.value / 100;
  return Math.round(amount * rate * 100) / 100;
});
const previewActualAmount = computed(() => {
  const amount = formData.value?.amount;
  if (amount == null || typeof amount !== 'number') return 0;
  return Math.round((amount - previewTaxAmount.value) * 100) / 100;
});

// 表单只保留：审核操作、扣税比例、备注
const getFormSchema = (): VbenFormSchema[] => [
  {
    component: 'RadioGroup',
    fieldName: 'action',
    label: '审核操作',
    defaultValue: 1,
    componentProps: {
      options: [
        { label: '确认提现', value: 1 },
        { label: '拒绝提现', value: 2 },
      ],
      onChange: (v: number) => {
        currentAction.value = v as 1 | 2;
      },
    },
    rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'tax_rate_percent',
    label: '扣税比例（%）',
    defaultValue: 6,
    componentProps: {
      min: 0,
      max: 100,
      step: 0.5,
      precision: 1,
      style: { width: '100%' },
      addonAfter: '%',
      placeholder: '默认 6',
      onChange: (v: number | null) => {
        currentTaxRatePercent.value = v ?? 6;
      },
    },
    dependencies: {
      show: (values) => values.action === 1,
      triggerFields: ['action'],
    },
  },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '备注',
    componentProps: {
      rows: 4,
      placeholder: '拒绝提现时，请填写拒绝原因',
      maxLength: 200,
      showCount: true,
      style: { width: '100%' },
    },
  },
];

const [Form, formApi] = useVbenForm({
  schema: getFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'agent-withdrawal-form-wrapper',
});

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'agent-withdrawal-review-drawer',
  async onConfirm() {
    if (formData.value?._isDetailView) {
      drawerApi.close();
      return;
    }
    const { valid } = await formApi.validate();
    if (!valid) return;

    if (!formData.value?.id) {
      message.error('提现记录ID不存在');
      return;
    }

    const values = await formApi.getValues<{
      action: 1 | 2;
      remark: string;
      tax_rate_percent?: number;
    }>();

    // 验证拒绝时必须填写原因
    if (values.action === 2 && !values.remark?.trim()) {
      message.error('拒绝提现必须填写拒绝原因');
      return;
    }

    // 确认时：扣税比例（%）转成小数，如 6 -> 0.06，不传则默认 6%
    const taxRate =
      values.action === 1 && values.tax_rate_percent != null
        ? Number(values.tax_rate_percent) / 100
        : undefined;

    try {
      await reviewBankCardWithdrawal({
        action: values.action,
        remark: values.remark || '',
        withdrawal_id: formData.value.id,
        ...(taxRate != null && { tax_rate: taxRate }),
      });
      message.success(values.action === 1 ? '确认提现成功' : '拒绝提现成功');
      drawerApi.close();
      emit('success');
    } catch (error: any) {
      message.error(error?.message || '操作失败');
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<any>();
      formApi.resetForm();
      if (data) {
        formData.value = data;
        currentAction.value = 1;
        currentTaxRatePercent.value = 6;
        if (!data._isDetailView) {
          const initialValues: any = {
            action: 1,
            tax_rate_percent: 6,
            remark: '',
          };
          formApi.setValues(initialValues);
        }
      }
    }
  },
});

const getDrawerTitle = computed(() => {
  const typeMap: Record<number, string> = {
    1: '支付宝',
    2: '银行卡',
  };
  const typeName = typeMap[formData.value?.withdraw_type] || '未知';
  const suffix = formData.value?._isDetailView ? '详情' : '审核';
  return `${typeName}提现${suffix} ${formData.value?.withdraw_no || ''}`;
});

const isDetailView = computed(() => !!formData.value?._isDetailView);

const statusMap: Record<number, string> = {
  1: '申请中',
  2: '成功',
  3: '失败',
};
</script>

<template>
  <Drawer :title="getDrawerTitle" :width="800">
    <div class="agent-withdrawal-review-content">
      <!-- 只读信息：纯文字展示 -->
      <div v-if="formData" class="review-info-block">
        <div class="info-row">
          <span class="info-label">提现单号：</span>
          <span class="info-value">{{ formData.withdraw_no ?? '-' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">提现类型：</span>
          <span class="info-value">{{ typeMap[formData.withdraw_type] ?? '未知' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">状态：</span>
          <span class="info-value">{{ statusMap[formData.status] ?? '未知' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">提现金额：</span>
          <span class="info-value">¥{{ (formData.amount ?? 0).toFixed(2) }}</span>
        </div>
        <!-- 详情模式：展示已保存的扣税/实际到账 -->
        <template v-if="isDetailView">
          <div class="info-row">
            <span class="info-label">扣税比例：</span>
            <span class="info-value">{{ formData.tax_rate != null ? ((formData.tax_rate * 100).toFixed(1) + '%') : '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">扣税金额：</span>
            <span class="info-value">¥{{ (formData.tax_amount ?? 0).toFixed(2) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">实际转账金额：</span>
            <span class="info-value">¥{{ (formData.actual_amount ?? 0).toFixed(2) }}</span>
          </div>
        </template>
        <!-- 审核模式：随扣税比例实时计算 -->
        <template v-else-if="currentAction === 1">
          <div class="info-row highlight">
            <span class="info-label">扣税金额：</span>
            <span class="info-value">¥{{ previewTaxAmount.toFixed(2) }}</span>
            <span class="info-hint">（随扣税比例实时计算）</span>
          </div>
          <div class="info-row highlight">
            <span class="info-label">实际转账金额：</span>
            <span class="info-value">¥{{ previewActualAmount.toFixed(2) }}</span>
            <span class="info-hint">（随扣税比例实时计算）</span>
          </div>
        </template>
        <div class="info-row">
          <span class="info-label">收款账号：</span>
          <span class="info-value">{{
            formData.withdraw_type === 2 ? (formData.bank_card_no ?? '-') : (formData.payee_account ?? '-')
          }}</span>
        </div>
        <template v-if="formData.withdraw_type === 2">
          <div class="info-row">
            <span class="info-label">开户支行：</span>
            <span class="info-value">{{ formData.bank_name ?? '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">收款人姓名：</span>
            <span class="info-value">{{ formData.payee_name ?? '-' }}</span>
          </div>
        </template>
        <div v-if="isDetailView && formData.remark" class="info-row">
          <span class="info-label">备注：</span>
          <span class="info-value">{{ formData.remark }}</span>
        </div>
      </div>

      <Form v-if="!isDetailView" />
    </div>
  </Drawer>
</template>

<style scoped>
.agent-withdrawal-review-content {
  padding: 0 4px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}

.review-info-block {
  margin-bottom: 20px;
  padding: 16px;
  background: var(--ant-color-fill-quaternary);
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row.highlight .info-value {
  font-weight: 600;
  color: var(--ant-color-primary);
}

.info-label {
  flex-shrink: 0;
  width: 120px;
  color: var(--ant-color-text-secondary);
}

.info-value {
  flex: 1;
  color: var(--ant-color-text);
}

.info-hint {
  margin-left: 8px;
  font-size: 12px;
  color: var(--ant-color-text-tertiary);
}

.agent-withdrawal-review-content :deep(.ant-form-item) {
  margin-bottom: 16px;
}

.agent-withdrawal-review-content :deep(.ant-form-item-label) {
  padding-bottom: 4px;
}
</style>
