<template>
  <div class="withdrawals-container">
    <!-- Search and Filter Bar -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="搜索">
          <el-input
            v-model="filters.search"
            placeholder="提现单号/用户名/手机号"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="待审核" value="waiting" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Withdrawal Table -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="withdrawals"
        stripe
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="withdrawalNo" label="提现单号" width="180" show-overflow-tooltip />
        <el-table-column label="用户信息" min-width="150">
          <template #default="{ row }">
            <div class="user-info">
              <span class="nickname">{{ row.user?.nickname || row.user?.realName || '-' }}</span>
              <span class="phone">{{ row.user?.phone || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="提现金额" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPaymentMethodType(row.paymentMethod)" size="small">
              {{ getPaymentMethodLabel(row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收款信息" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ formatPaymentDetails(row.paymentMethod, row.paymentDetails) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" width="170" sortable="custom">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleViewDetails(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <template v-if="row.status === 'waiting'">
              <el-button type="success" link size="small" @click="handleApprove(row)">
                <el-icon><Check /></el-icon>
                批准
              </el-button>
              <el-button type="danger" link size="small" @click="handleReject(row)">
                <el-icon><Close /></el-icon>
                拒绝
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- Withdrawal Details Dialog -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="提现详情"
      width="600px"
      destroy-on-close
    >
      <div v-loading="detailsLoading" class="withdrawal-details">
        <template v-if="withdrawalDetails">
          <!-- Basic Info -->
          <el-descriptions title="提现信息" :column="2" border>
            <el-descriptions-item label="提现单号">
              {{ withdrawalDetails.withdrawalNo }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(withdrawalDetails.status)" size="small">
                {{ getStatusLabel(withdrawalDetails.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="提现金额">
              <span class="amount-large">¥{{ withdrawalDetails.amount }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              <el-tag :type="getPaymentMethodType(withdrawalDetails.paymentMethod)" size="small">
                {{ getPaymentMethodLabel(withdrawalDetails.paymentMethod) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="收款信息" :span="2">
              {{ formatPaymentDetailsLong(withdrawalDetails.paymentMethod, withdrawalDetails.paymentDetails) }}
            </el-descriptions-item>
            <el-descriptions-item label="收款码" :span="2" v-if="getQrcodeUrl(withdrawalDetails.paymentDetails)">
              <el-image
                :src="getQrcodeUrl(withdrawalDetails.paymentDetails)"
                :preview-src-list="[getQrcodeUrl(withdrawalDetails.paymentDetails)]"
                fit="contain"
                style="width: 200px; height: 200px; cursor: pointer;"
                :preview-teleported="true"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
            </el-descriptions-item>
            <el-descriptions-item label="申请时间">
              {{ formatDate(withdrawalDetails.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="审核时间">
              {{ withdrawalDetails.reviewedAt ? formatDate(withdrawalDetails.reviewedAt) : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="完成时间" v-if="withdrawalDetails.completedAt">
              {{ formatDate(withdrawalDetails.completedAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="拒绝原因" :span="2" v-if="withdrawalDetails.rejectionReason">
              <span class="rejection-reason">{{ withdrawalDetails.rejectionReason }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <!-- User Info -->
          <el-descriptions title="用户信息" :column="2" border class="mt-20" v-if="withdrawalDetails.user">
            <el-descriptions-item label="用户昵称">
              {{ withdrawalDetails.user.nickname || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="真实姓名">
              {{ withdrawalDetails.user.realName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ withdrawalDetails.user.phone || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="WhatsApp">
              {{ withdrawalDetails.user.whatsapp || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="微信号">
              {{ withdrawalDetails.user.wechatId || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="当前余额">
              <span class="balance">¥{{ withdrawalDetails.user.balance }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </div>
      <template #footer>
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
        <template v-if="withdrawalDetails && withdrawalDetails.status === 'waiting'">
          <el-button type="success" @click="handleApproveFromDetails">
            <el-icon><Check /></el-icon>
            批准
          </el-button>
          <el-button type="danger" @click="handleRejectFromDetails">
            <el-icon><Close /></el-icon>
            拒绝
          </el-button>
        </template>
      </template>
    </el-dialog>

    <!-- Approve Confirmation Dialog -->
    <el-dialog
      v-model="approveDialogVisible"
      title="批准提现"
      width="450px"
      destroy-on-close
    >
      <div class="approve-dialog-content">
        <el-alert
          title="确认批准此提现申请？"
          type="warning"
          :closable="false"
          show-icon
        >
          <template #default>
            <div class="alert-content">
              <p>提现单号：<strong>{{ approveForm.withdrawalNo }}</strong></p>
              <p>提现金额：<strong class="amount">¥{{ approveForm.amount }}</strong></p>
              <p>用户：<strong>{{ approveForm.userName }}</strong></p>
            </div>
          </template>
        </el-alert>
        <el-form :model="approveForm" label-width="80px" class="mt-20">
          <el-form-item label="备注">
            <el-input
              v-model="approveForm.notes"
              type="textarea"
              :rows="3"
              placeholder="可选，添加审核备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmApprove" :loading="approving">
          确认批准
        </el-button>
      </template>
    </el-dialog>

    <!-- Reject Dialog -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝提现"
      width="450px"
      destroy-on-close
    >
      <div class="reject-dialog-content">
        <el-alert
          title="确认拒绝此提现申请？"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <div class="alert-content">
              <p>提现单号：<strong>{{ rejectForm.withdrawalNo }}</strong></p>
              <p>提现金额：<strong class="amount">¥{{ rejectForm.amount }}</strong></p>
              <p>用户：<strong>{{ rejectForm.userName }}</strong></p>
            </div>
          </template>
        </el-alert>
        <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="80px" class="mt-20">
          <el-form-item label="拒绝原因" prop="reason">
            <el-input
              v-model="rejectForm.reason"
              type="textarea"
              :rows="3"
              placeholder="请填写拒绝原因（必填）"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject" :loading="rejecting">
          确认拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import api from '@/utils/api'

// State
const loading = ref(false)
const withdrawals = ref([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
  totalPages: 0
})
const filters = reactive({
  search: '',
  status: ''
})
const sortConfig = reactive({
  sortBy: 'createdAt',
  sortOrder: 'DESC'
})

// Details dialog state
const detailsDialogVisible = ref(false)
const detailsLoading = ref(false)
const withdrawalDetails = ref(null)

// Approve dialog state
const approveDialogVisible = ref(false)
const approving = ref(false)
const approveForm = reactive({
  withdrawalId: '',
  withdrawalNo: '',
  amount: '',
  userName: '',
  notes: ''
})

// Reject dialog state
const rejectDialogVisible = ref(false)
const rejecting = ref(false)
const rejectFormRef = ref(null)
const rejectForm = reactive({
  withdrawalId: '',
  withdrawalNo: '',
  amount: '',
  userName: '',
  reason: ''
})
const rejectRules = {
  reason: [
    { required: true, message: '请填写拒绝原因', trigger: 'blur' },
    { min: 2, message: '拒绝原因至少2个字符', trigger: 'blur' }
  ]
}

// Fetch withdrawal list
async function fetchWithdrawals() {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...filters,
      ...sortConfig
    }
    // Remove empty params
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await api.get('/api/v1/admin/withdrawals', { params })
    if (response.data.code === 0) {
      withdrawals.value = response.data.data.withdrawals
      pagination.total = response.data.data.pagination.total
      pagination.totalPages = response.data.data.pagination.totalPages
    }
  } catch (error) {
    console.error('Failed to fetch withdrawals:', error)
    ElMessage.error('获取提现列表失败')
  } finally {
    loading.value = false
  }
}

// Fetch withdrawal details
async function fetchWithdrawalDetails(withdrawalId) {
  detailsLoading.value = true
  try {
    const response = await api.get(`/api/v1/admin/withdrawals/${withdrawalId}`)
    if (response.data.code === 0) {
      withdrawalDetails.value = response.data.data
    }
  } catch (error) {
    console.error('Failed to fetch withdrawal details:', error)
    ElMessage.error('获取提现详情失败')
  } finally {
    detailsLoading.value = false
  }
}

// Handle search
function handleSearch() {
  pagination.page = 1
  fetchWithdrawals()
}

// Handle reset
function handleReset() {
  filters.search = ''
  filters.status = ''
  pagination.page = 1
  fetchWithdrawals()
}

// Handle page change
function handlePageChange(page) {
  pagination.page = page
  fetchWithdrawals()
}

// Handle page size change
function handleSizeChange(size) {
  pagination.limit = size
  pagination.page = 1
  fetchWithdrawals()
}

// Handle sort change
function handleSortChange({ prop, order }) {
  if (prop && order) {
    sortConfig.sortBy = prop
    sortConfig.sortOrder = order === 'ascending' ? 'ASC' : 'DESC'
  } else {
    sortConfig.sortBy = 'createdAt'
    sortConfig.sortOrder = 'DESC'
  }
  fetchWithdrawals()
}

// Handle view details
function handleViewDetails(row) {
  withdrawalDetails.value = null
  detailsDialogVisible.value = true
  fetchWithdrawalDetails(row.id)
}

// Handle approve
function handleApprove(row) {
  approveForm.withdrawalId = row.id
  approveForm.withdrawalNo = row.withdrawalNo
  approveForm.amount = row.amount
  approveForm.userName = row.user?.nickname || row.user?.realName || '-'
  approveForm.notes = ''
  approveDialogVisible.value = true
}

// Handle approve from details dialog
function handleApproveFromDetails() {
  if (withdrawalDetails.value) {
    handleApprove(withdrawalDetails.value)
  }
}

// Confirm approve
async function confirmApprove() {
  approving.value = true
  try {
    const response = await api.put(`/api/v1/admin/withdrawals/${approveForm.withdrawalId}/approve`, {
      notes: approveForm.notes
    })

    if (response.data.code === 0) {
      ElMessage.success('提现已批准')
      approveDialogVisible.value = false
      detailsDialogVisible.value = false
      fetchWithdrawals()
    }
  } catch (error) {
    console.error('Failed to approve withdrawal:', error)
    ElMessage.error(error.response?.data?.error?.message || '批准提现失败')
  } finally {
    approving.value = false
  }
}

// Handle reject
function handleReject(row) {
  rejectForm.withdrawalId = row.id
  rejectForm.withdrawalNo = row.withdrawalNo
  rejectForm.amount = row.amount
  rejectForm.userName = row.user?.nickname || row.user?.realName || '-'
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

// Handle reject from details dialog
function handleRejectFromDetails() {
  if (withdrawalDetails.value) {
    handleReject(withdrawalDetails.value)
  }
}

// Confirm reject
async function confirmReject() {
  if (!rejectFormRef.value) return
  
  await rejectFormRef.value.validate(async (valid) => {
    if (!valid) return

    rejecting.value = true
    try {
      const response = await api.put(`/api/v1/admin/withdrawals/${rejectForm.withdrawalId}/reject`, {
        reason: rejectForm.reason
      })

      if (response.data.code === 0) {
        ElMessage.success('提现已拒绝')
        rejectDialogVisible.value = false
        detailsDialogVisible.value = false
        fetchWithdrawals()
      }
    } catch (error) {
      console.error('Failed to reject withdrawal:', error)
      ElMessage.error(error.response?.data?.error?.message || '拒绝提现失败')
    } finally {
      rejecting.value = false
    }
  })
}

// Helper functions
function formatDate(dateStr) {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

function getStatusLabel(status) {
  const labels = {
    waiting: '待审核',
    processing: '处理中',
    completed: '已完成',
    rejected: '已拒绝'
  }
  return labels[status] || status
}

function getStatusTagType(status) {
  const types = {
    waiting: 'warning',
    processing: '',
    completed: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

function getPaymentMethodLabel(method) {
  const labels = {
    wechat: '微信',
    alipay: '支付宝',
    bank: '银行卡'
  }
  return labels[method] || method
}

function getPaymentMethodType(method) {
  const types = {
    wechat: 'success',
    alipay: 'primary',
    bank: ''
  }
  return types[method] || 'info'
}

function formatPaymentDetails(method, details) {
  if (!details) return '-'
  try {
    const parsed = typeof details === 'string' ? JSON.parse(details) : details
    switch (method) {
      case 'wechat':
        return parsed.wechatId || parsed.account || '-'
      case 'alipay':
        return parsed.alipayAccount || parsed.account || '-'
      case 'bank':
        return parsed.bankAccount ? `****${parsed.bankAccount.slice(-4)}` : '-'
      default:
        return '-'
    }
  } catch {
    return '-'
  }
}

function formatPaymentDetailsLong(method, details) {
  if (!details) return '-'
  try {
    const parsed = typeof details === 'string' ? JSON.parse(details) : details
    switch (method) {
      case 'wechat':
        return `微信号: ${parsed.wechatId || parsed.account || '-'}`
      case 'alipay':
        return `支付宝账号: ${parsed.alipayAccount || parsed.account || '-'}`
      case 'bank':
        const bankName = parsed.bankName || '银行'
        const account = parsed.bankAccount || '-'
        const name = parsed.accountName || '-'
        return `${bankName} | 账号: ${account} | 户名: ${name}`
      default:
        return JSON.stringify(parsed)
    }
  } catch {
    return '-'
  }
}

// Get QR code URL from payment details
function getQrcodeUrl(details) {
  if (!details) return null
  try {
    const parsed = typeof details === 'string' ? JSON.parse(details) : details
    const qrcodeUrl = parsed.qrcodeUrl
    if (!qrcodeUrl) return null
    
    // If it's already a full URL, return as is
    if (qrcodeUrl.startsWith('http://') || qrcodeUrl.startsWith('https://')) {
      return qrcodeUrl
    }
    
    // Convert relative path to full URL using API base URL
    const baseUrl = import.meta.env.VITE_API_BASE_URL || window.location.origin
    return `${baseUrl}${qrcodeUrl}`
  } catch {
    return null
  }
}

// Initialize
onMounted(() => {
  fetchWithdrawals()
})
</script>


<style lang="scss" scoped>
.withdrawals-container {
  .filter-card {
    margin-bottom: 20px;
    
    .filter-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .user-info {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .nickname {
      font-weight: 500;
      color: #303133;
    }

    .phone {
      font-size: 12px;
      color: #909399;
    }
  }

  .amount {
    font-weight: 600;
    color: #409eff;
  }

  .withdrawal-details {
    .mt-20 {
      margin-top: 20px;
    }

    .amount-large {
      font-weight: 600;
      color: #409eff;
      font-size: 18px;
    }

    .balance {
      font-weight: 600;
      color: #67c23a;
    }

    .rejection-reason {
      color: #f56c6c;
    }

    .image-error {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 200px;
      background: #f5f7fa;
      color: #909399;
      font-size: 14px;
      
      .el-icon {
        font-size: 30px;
        margin-bottom: 8px;
      }
    }
  }

  .approve-dialog-content,
  .reject-dialog-content {
    .alert-content {
      margin-top: 8px;
      
      p {
        margin: 4px 0;
        font-size: 14px;
        
        .amount {
          color: #409eff;
          font-size: 16px;
        }
      }
    }

    .mt-20 {
      margin-top: 20px;
    }
  }
}
</style>
