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

import { computed, ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { auditWithdrawal, getAgentWithdrawalList } from '#/api/agent';

import { useWithdrawalColumns, useWithdrawalFormSchema } from './data';

interface Props {
  agentId?: number;
}

interface QueryParams {
  currentPage: number;
  pageSize: number;
  [key: string]: any;
}

const props = defineProps<Props>();

const queryParams = computed(() => ({
  ...(props.agentId ? { agent_id: props.agentId } : {}),
}));

const auditRemark = ref('');
const auditModalVisible = ref(false);
const detailModalVisible = ref(false);
// 使用 any 以兼容后端新增字段（withdrawal_type、bank_card_no、bank_name 等）
const currentWithdrawal = ref<any | null>(null);

const statusLabelMap: Record<number, string> = {
  1: '待审核',
  2: '审核通过',
  3: '审核拒绝',
  4: '提现中',
  5: '提现成功',
  6: '提现失败',
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useWithdrawalFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useWithdrawalColumns(),
    proxyConfig: {
      ajax: {
        query: async ({
          page,
          form,
        }: {
          page: QueryParams;
          form: Record<string, any>;
        }) => {
          return await getAgentWithdrawalList({
            ...queryParams.value,
            ...form,
            page: page.currentPage,
            pageSize: page.pageSize,
          });
        },
      },
      props: {
        result: 'items',
        total: 'total',
      },
    },
  },
});

// 审核提现
function handleAudit(row: AgentApi.AgentWithdrawalListItem) {
  currentWithdrawal.value = row;
  auditRemark.value = '';
  auditModalVisible.value = true;
}

// 查看详情
function handleViewDetail(row: AgentApi.AgentWithdrawalListItem) {
  currentWithdrawal.value = row;
  detailModalVisible.value = true;
}

// 确认审核
async function confirmAudit(status: number) {
  if (!currentWithdrawal.value) return;

  try {
    await auditWithdrawal({
      withdrawal_id: currentWithdrawal.value.id,
      status,
      remark: auditRemark.value || '',
    });
    message.success('审核成功');
    auditModalVisible.value = false;
    gridApi.query();
  } catch (error) {
    console.error('审核失败:', error);
  }
}

// 取消审核
function cancelAudit() {
  auditModalVisible.value = false;
  auditRemark.value = '';
  currentWithdrawal.value = null;
}
</script>

<template>
  <Page :auto-content-height="!agentId">
    <Grid :table-title="agentId ? '提现记录列表' : '所有提现记录'">
      <template #operation="{ row }">
        <Space>
          <Button v-if="row.status === 1" type="link" size="small" @click="handleAudit(row)">
            审核
          </Button>
          <Button v-else type="link" size="small" @click="handleViewDetail(row)">
            详情
          </Button>
        </Space>
      </template>
    </Grid>

    <Modal v-model:open="auditModalVisible" title="审核提现" :width="600" @cancel="cancelAudit">
      <div v-if="currentWithdrawal" class="audit-info">
        <p><strong>提现单号：</strong>{{ currentWithdrawal.withdraw_no }}</p>
        <p>
          <strong>提现方式：</strong>
          <span v-if="currentWithdrawal.withdrawal_type === 1" style="color: #1890ff;">支付宝</span>
          <span v-else-if="currentWithdrawal.withdrawal_type === 2" style="color: #52c41a;">银行卡</span>
        </p>
        <p>
          <strong>提现金额：</strong>¥{{ currentWithdrawal.amount.toFixed(2) }}
        </p>
        <p>
          <strong>税费金额：</strong>¥{{ currentWithdrawal.tax_amount?.toFixed(2) ?? '0.00' }}
        </p>
        <p>
          <strong>实际到账金额：</strong>¥{{ currentWithdrawal.actual_amount?.toFixed(2) ?? '0.00' }}
        </p>
        <p v-if="currentWithdrawal.withdrawal_type === 1">
          <strong>支付宝账号：</strong>{{ currentWithdrawal.payee_account }}
        </p>
        <template v-else-if="currentWithdrawal.withdrawal_type === 2">
          <p><strong>银行卡号：</strong>{{ currentWithdrawal.bank_card_no || currentWithdrawal.payee_account }}</p>
          <p><strong>开户行：</strong>{{ currentWithdrawal.bank_name }}</p>
        </template>
        <p><strong>收款人姓名：</strong>{{ currentWithdrawal.payee_name }}</p>
        <p v-if="currentWithdrawal.withdrawal_type === 2" style="color: #ff4d4f; font-size: 12px; margin-top: 8px;">
          ⚠️ 请在确认已完成银行卡打款后再点击“通过”，审核通过后将直接记为提现成功
        </p>
      </div>
      <div class="audit-remark">
        <p><strong>审核备注：</strong></p>
        <Input.TextArea v-model:value="auditRemark" :rows="4" placeholder="请输入审核备注" />
      </div>
      <template #footer>
        <Button @click="cancelAudit">取消</Button>
        <Button type="primary" danger @click="confirmAudit(3)">
          拒绝
        </Button>
        <Button type="primary" @click="confirmAudit(2)">通过</Button>
      </template>
    </Modal>

    <!-- 提现详情弹窗 -->
    <Modal v-model:open="detailModalVisible" title="提现详情" :width="600" :footer="null"
      @cancel="detailModalVisible = false">
      <div v-if="currentWithdrawal" class="audit-info">
        <p><strong>提现单号：</strong>{{ currentWithdrawal.withdraw_no }}</p>
        <p><strong>代理ID：</strong>{{ currentWithdrawal.agent_id }}</p>
        <p>
          <strong>提现方式：</strong>
          <span v-if="currentWithdrawal.withdrawal_type === 1" style="color: #1890ff;">支付宝</span>
          <span v-else-if="currentWithdrawal.withdrawal_type === 2" style="color: #52c41a;">银行卡</span>
        </p>
        <p>
          <strong>提现金额：</strong>¥{{ currentWithdrawal.amount.toFixed(2) }}
        </p>
        <p>
          <strong>税费金额：</strong>¥{{ currentWithdrawal.tax_amount?.toFixed(2) ?? '0.00' }}
        </p>
        <p>
          <strong>实际到账金额：</strong>¥{{ currentWithdrawal.actual_amount?.toFixed(2) ?? '0.00' }}
        </p>
        <p v-if="currentWithdrawal.withdrawal_type === 1">
          <strong>支付宝账号：</strong>{{ currentWithdrawal.payee_account }}
        </p>
        <template v-else-if="currentWithdrawal.withdrawal_type === 2">
          <p><strong>银行卡号：</strong>{{ currentWithdrawal.bank_card_no || currentWithdrawal.payee_account }}</p>
          <p><strong>开户行：</strong>{{ currentWithdrawal.bank_name }}</p>
        </template>
        <p><strong>收款人姓名：</strong>{{ currentWithdrawal.payee_name }}</p>
        <p>
          <strong>状态：</strong>{{ statusLabelMap[currentWithdrawal.status] ?? currentWithdrawal.status }}
        </p>
        <p><strong>备注：</strong>{{ currentWithdrawal.remark }}</p>
        <p><strong>创建时间：</strong>{{ currentWithdrawal.create_time }}</p>
      </div>
    </Modal>
  </Page>
</template>

<style lang="less" scoped>
.audit-info {
  margin-bottom: 16px;

  p {
    margin-bottom: 8px;
  }
}

.audit-remark {
  margin-top: 16px;

  p {
    margin-bottom: 8px;
  }
}
</style>
