<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Wallet, Money } from '@element-plus/icons-vue'

import {
  fetchPaymentAccounts,
  createWithdrawal,
  fetchWithdrawals,
  cancelWithdrawal,
  type PaymentAccount,
  type WithdrawalRequest,
} from '../api/withdrawal'
import { fetchWalletBalance, type WalletAccount } from '../api/wallet'
import { formatMoney, formatMoneyWithSymbol, formatCent, yuanToCent } from '@/shared/utils/money'

const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const account = ref<WalletAccount | null>(null)
const paymentAccounts = ref<PaymentAccount[]>([])
const withdrawals = ref<WithdrawalRequest[]>([])

const withdrawForm = ref({
  payment_account_id: 0,
  amount: 0,
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const MIN_AMOUNT = 10
const MAX_AMOUNT = 5000

onMounted(() => {
  loadData()
})

async function loadData() {
  loading.value = true
  try {
    const [balanceData, accountsData, withdrawalsData] = await Promise.all([
      fetchWalletBalance(),
      fetchPaymentAccounts(1, 100),
      fetchWithdrawals(currentPage.value, pageSize.value),
    ])
    account.value = balanceData
    paymentAccounts.value = accountsData.items
    withdrawals.value = withdrawalsData.items
    total.value = withdrawalsData.total

    // 自动选择默认账号
    const defaultAccount = paymentAccounts.value.find(a => a.is_default)
    if (defaultAccount) {
      withdrawForm.value.payment_account_id = defaultAccount.id
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

const selectedAccount = computed(() => {
  return paymentAccounts.value.find(a => a.id === withdrawForm.value.payment_account_id)
})

const canWithdraw = computed(() => {
  return (
    withdrawForm.value.payment_account_id > 0 &&
    withdrawForm.value.amount >= MIN_AMOUNT &&
    withdrawForm.value.amount <= MAX_AMOUNT &&
    account.value &&
    yuanToCent(withdrawForm.value.amount) <= account.value.available_balance_cent
  )
})

async function handleSubmit() {
  if (!canWithdraw.value) {
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认提现 ${formatMoneyWithSymbol(withdrawForm.value.amount)} 到 ${selectedAccount.value?.account_name} (${selectedAccount.value?.account_no}) ?`,
      '确认提现',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    submitting.value = true
    await createWithdrawal({
      payment_account_id: withdrawForm.value.payment_account_id,
      amount_cent: yuanToCent(withdrawForm.value.amount),
    })
    ElMessage.success('提现申请已提交')
    withdrawForm.value.amount = 0
    await loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '提现申请失败')
    }
  } finally {
    submitting.value = false
  }
}

async function handleCancel(withdrawal: WithdrawalRequest) {
  try {
    await ElMessageBox.confirm('确定要取消此提现申请吗？', '取消提现', {
      confirmButtonText: '确认取消',
      cancelButtonText: '返回',
      type: 'warning',
    })
    await cancelWithdrawal(withdrawal.id)
    ElMessage.success('已取消提现')
    await loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '取消失败')
    }
  }
}

function goToPaymentAccounts() {
  router.push('/wallet/payment-accounts')
}

function statusLabel(status: string) {
  const labels: Record<string, string> = {
    pending: '待审核',
    processing: '处理中',
    completed: '已完成',
    rejected: '已拒绝',
    cancelled: '已取消',
  }
  return labels[status] || status
}

function statusType(status: string) {
  const types: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    rejected: 'danger',
    cancelled: 'info',
  }
  return types[status] || 'info'
}

function accountTypeLabel(type: string) {
  const labels: Record<string, string> = {
    alipay: '支付宝',
    wechat: '微信',
    bank: '银行卡',
  }
  return labels[type] || type
}
</script>

<template>
  <div class="withdrawal-page">
    <div class="page-header">
      <h2>提现</h2>
      <p class="page-desc">将钱包余额提现到您的收款账号</p>
    </div>

    <!-- 余额卡片 -->
    <el-card class="balance-card" shadow="never">
      <div class="balance-info">
        <div class="balance-item">
          <div class="balance-label">
            <el-icon><Wallet /></el-icon>
            可用余额
          </div>
          <div class="balance-value">¥{{ formatCent(account?.available_balance_cent) }}</div>
        </div>
        <div class="balance-item">
          <div class="balance-label">
            <el-icon><Money /></el-icon>
            冻结余额
          </div>
          <div class="balance-value frozen">¥{{ formatCent(account?.frozen_balance_cent) }}</div>
        </div>
      </div>
    </el-card>

    <!-- 提现表单 -->
    <el-card class="withdraw-form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>申请提现</span>
        </div>
      </template>

      <div v-if="paymentAccounts.length === 0" class="no-accounts">
        <el-empty description="还没有收款账号">
          <el-button type="primary" @click="goToPaymentAccounts"> 添加收款账号 </el-button>
        </el-empty>
      </div>

      <div v-else>
        <el-form :model="withdrawForm" label-width="100px" label-position="left">
          <el-form-item label="收款账号" required>
            <el-select
              v-model="withdrawForm.payment_account_id"
              placeholder="请选择收款账号"
              style="width: 100%"
            >
              <el-option
                v-for="acc in paymentAccounts"
                :key="acc.id"
                :label="`${accountTypeLabel(acc.account_type)} - ${acc.account_name} (${acc.account_no})`"
                :value="acc.id"
              >
                <div style="display: flex; justify-content: space-between; align-items: center">
                  <span>
                    <el-tag size="small" style="margin-right: 8px">{{
                      accountTypeLabel(acc.account_type)
                    }}</el-tag>
                    {{ acc.account_name }} ({{ acc.account_no }})
                  </span>
                  <el-tag v-if="acc.is_default" type="warning" size="small">默认</el-tag>
                </div>
              </el-option>
            </el-select>
            <div style="margin-top: 8px; display: flex; gap: 8px">
              <el-button size="small" @click="goToPaymentAccounts"> 添加收款账号 </el-button>
              <el-button size="small" text @click="goToPaymentAccounts"> 管理收款账号 </el-button>
            </div>
          </el-form-item>

          <el-form-item label="提现金额" required>
            <el-input
              v-model.number="withdrawForm.amount"
              type="number"
              placeholder="请输入提现金额"
              :min="MIN_AMOUNT"
              :max="MAX_AMOUNT"
            >
              <template #prefix>¥</template>
            </el-input>
            <div style="margin-top: 8px; font-size: 13px; color: #999">
              单笔限额：¥{{ MIN_AMOUNT }} - ¥{{ MAX_AMOUNT }}，手续费：0%
            </div>
          </el-form-item>

          <el-form-item label="到账金额">
            <div class="actual-amount">
              ¥{{ formatMoney(withdrawForm.amount > 0 ? withdrawForm.amount : 0) }}
            </div>
          </el-form-item>

          <el-alert
            v-if="
              withdrawForm.amount > 0 &&
              account &&
              yuanToCent(withdrawForm.amount) > account.available_balance_cent
            "
            type="error"
            :closable="false"
            show-icon
            style="margin-bottom: 16px"
          >
            余额不足，可用余额：¥{{ formatCent(account.available_balance_cent) }}
          </el-alert>

          <el-alert type="info" :closable="false" show-icon style="margin-bottom: 16px">
            <template #title>
              <div style="font-size: 13px">
                <strong>提现说明</strong>
                <ul style="margin: 8px 0 0; padding-left: 20px">
                  <li>提现申请提交后，将冻结相应金额</li>
                  <li>财务审核通过后，将手动转账到您的收款账号</li>
                  <li>正常情况下，1-3个工作日内完成转账</li>
                  <li>待审核状态下可取消提现申请</li>
                </ul>
              </div>
            </template>
          </el-alert>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="submitting"
              :disabled="!canWithdraw"
              @click="handleSubmit"
            >
              提交申请
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 提现记录 -->
    <el-card class="withdrawal-records-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>提现记录</span>
        </div>
      </template>

      <el-table v-loading="loading" :data="withdrawals" stripe>
        <el-table-column prop="withdraw_no" label="提现单号" min-width="180" />
        <el-table-column label="提现金额" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: 600">
              ¥{{ formatCent(row.amount_cent) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="收款方式" width="150">
          <template #default="{ row }">
            <div>{{ accountTypeLabel(row.account_type) }}</div>
            <div style="font-size: 12px; color: #999">{{ row.account_no }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">
              {{ statusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="review_remark" label="备注" min-width="150" />
        <el-table-column label="申请时间" width="160">
          <template #default="{ row }">
            {{ new Date(row.created_at).toLocaleString('zh-CN') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              size="small"
              type="danger"
              text
              @click="handleCancel(row)"
            >
              取消
            </el-button>
            <span v-else style="color: #999">-</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > pageSize"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        style="margin-top: 16px; justify-content: center"
        @current-change="loadData"
      />
    </el-card>
  </div>
</template>

<style scoped>
.withdrawal-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 600;
}

.page-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.balance-card {
  margin-bottom: 20px;
}

.balance-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
}

.balance-item {
  text-align: center;
}

.balance-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.balance-value {
  font-size: 32px;
  font-weight: 600;
  color: #67c23a;
}

.balance-value.frozen {
  color: #909399;
}

.withdraw-form-card,
.withdrawal-records-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}

.no-accounts {
  padding: 40px 0;
  text-align: center;
}

.actual-amount {
  font-size: 28px;
  font-weight: 600;
  color: #67c23a;
}
</style>
