<template>
  <view class="withdraw-container">
    <!-- 顶部卡片 -->
    <view class="top-card">
      <text class="page-title">{{ stationName }} - 提现管理</text>
    </view>
    
    <!-- 账户信息卡片 -->
    <view class="section">
      <view class="section-title">账户信息</view>
      <view class="info-cards">
        <view class="info-card blue">
          <text class="info-label">可提现余额</text>
          <text class="info-value">¥{{ formatAmount(availableBalance || 0) }}</text>
        </view>
        <view class="info-card pink">
          <text class="info-label">待审核金额</text>
          <text class="info-value">¥{{ formatAmount(pendingAmount || 0) }}</text>
        </view>
        <view class="info-card green">
          <text class="info-label">累计提现</text>
          <text class="info-value">¥{{ formatAmount(totalWithdrawn || 0) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 申请提现表单 -->
    <view class="section">
      <view class="section-title">申请提现</view>
      <view class="apply-form">
        <view class="form-item">
          <text class="form-label">提现金额</text>
          <view class="form-input">
            <input 
              type="number" 
              v-model="withdrawForm.amount" 
              placeholder="请输入提现金额" 
              step="0.01"
              min="0.01"
              :max="formatAmount(availableBalance, true)"
            />
            <text class="balance-tip">最小提现金额：0.01元</text>
          </view>
        </view>
        <view class="form-item">
          <text class="form-label">提现账户</text>
          <view class="form-input">
            <input 
              type="text" 
              v-model="withdrawForm.account" 
              placeholder="请输入提现账户"
            />
          </view>
        </view>
        <view class="form-item">
          <text class="form-label">备注（选填）</text>
          <view class="form-input">
            <input 
              type="text"
              v-model="withdrawForm.remark" 
              placeholder="请输入备注信息"
              maxlength="50"
            />
          </view>
        </view>
        <button class="apply-btn" @click="handleApplyWithdraw" :disabled="!canApply">
          提交提现申请
        </button>
      </view>
    </view>
    
    <!-- 提现记录 -->
    <view class="section">
      <view class="section-title">提现记录</view>
      <view class="records-filter">
        <view class="segmented-control">
          <view 
            v-for="(option, index) in filterOptions" 
            :key="index"
            class="segment-item"
            :class="{ 'active': activeFilter === index }"
            @click="activeFilter = index; handleFilterChange(index)"
          >
            <text>{{ option }}</text>
          </view>
        </view>
      </view>
      
      <view class="records-list">
        <view 
          v-for="record in withdrawRecords" 
          :key="record.id" 
          class="record-item"
        >
          <view class="record-header">
            <view class="record-info">
              <text class="record-no">提现编号: {{ record.withdrawNo }}</text>
              <text class="record-time">{{ formatTime(record.createTime) }}</text>
            </view>
            <text class="record-status" :class="getStatusClass(record.status)">
              {{ getStatusText(record.status) }}
            </text>
          </view>
          <view class="record-content">
            <view class="record-amount">
              <text class="amount-label">提现金额:</text>
              <text class="amount-value">¥{{ formatAmount(record.amount || 0) }}</text>
            </view>
            <view class="record-account">
              <text class="account-label">提现账户:</text>
              <text class="account-value">{{ record.account || '未填写' }}</text>
            </view>
          </view>
          <view class="record-footer" v-if="record.remark">
            <view class="record-remark">
              <text class="remark-label">备注:</text>
              <text class="remark-value">{{ record.remark }}</text>
            </view>
          </view>
          <view class="record-actions" v-if="record.status === 0">
            <button class="approve-btn" @click="handleApprove(record.id)">
              审核通过
            </button>
            <button class="reject-btn" @click="handleReject(record.id)">
              拒绝
            </button>
          </view>
        </view>
      </view>
      
      <view class="empty-state" v-if="withdrawRecords.length === 0">
        <text class="empty-icon">📭</text>
        <text>暂无提现记录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getWithdrawnRecords, reviewWithdrawn, applyWithdrawn, getStationAccounts } from '../../api/finance.js'
import { formatTime, showToast, formatAmount } from '../../utils/index.js'

const stationId = ref('')
const stationName = ref('')

// 真实数据
const availableBalance = ref(0.00)
const pendingAmount = ref(0.00)
const totalWithdrawn = ref(0.00)
const loading = ref(false)
const page = ref(1)

const withdrawForm = ref({
  amount: '',
  account: '',
  remark: ''
})

const activeFilter = ref(0)
const filterOptions = ['全部', '待审核', '已通过', '已拒绝']
const withdrawRecords = ref([])

onLoad((options) => {
  stationId.value = options.stationId || ''
  stationName.value = options.stationName || '站点'
  loadAccountData()
  loadWithdrawRecords()
})

// 加载账户数据
const loadAccountData = async () => {
  loading.value = true
  try {
    console.log('开始加载账户数据，stationId:', stationId.value)
    
    // 获取站点账户详情
    const res = await getStationAccounts({ stationId: stationId.value, page: 1, pageSize: 1 })
    console.log('获取站点账户API返回:', res)
    
    if (res && res.code === 200 && res.data) {
      // 适配不同的数据结构
      const records = res.data.records || res.data.list || (Array.isArray(res.data) ? res.data : [])
      
      if (records.length > 0) {
        const account = records[0]
        availableBalance.value = account.balance || 0
        console.log('设置可用余额:', availableBalance.value)
      } else {
        console.warn('站点账户数据为空')
        availableBalance.value = 0
      }
    } else {
      console.warn('获取站点账户失败:', res)
      availableBalance.value = 0
    }
    
    // 获取提现统计数据
    const withdrawRes = await getWithdrawnRecords({ stationId: stationId.value })
    console.log('获取提现记录API返回:', withdrawRes)
    
    if (withdrawRes && withdrawRes.code === 200 && withdrawRes.data) {
      // 适配不同的数据结构
      const records = withdrawRes.data.records || withdrawRes.data.list || (Array.isArray(withdrawRes.data) ? withdrawRes.data : [])
      
      if (Array.isArray(records)) {
        // 计算待审核金额
        pendingAmount.value = records
          .filter(record => record.status === 0)
          .reduce((sum, record) => sum + (record.amount || 0), 0)
        
        // 计算累计提现金额
        totalWithdrawn.value = records
          .filter(record => record.status === 1)
          .reduce((sum, record) => sum + (record.amount || 0), 0)
        
        console.log('待审核金额:', pendingAmount.value, '累计提现:', totalWithdrawn.value)
      } else {
        console.warn('提现记录数据格式异常')
        pendingAmount.value = 0
        totalWithdrawn.value = 0
      }
    } else {
      console.warn('获取提现记录失败:', withdrawRes)
      pendingAmount.value = 0
      totalWithdrawn.value = 0
    }
  } catch (error) {
    console.error('加载账户数据失败:', error)
    showToast('加载账户数据失败')
    // 设置默认值，防止页面崩溃
    availableBalance.value = 0
    pendingAmount.value = 0
    totalWithdrawn.value = 0
  } finally {
    loading.value = false
  }
}

const canApply = computed(() => {
  const amountYuan = parseFloat(withdrawForm.value.amount)
  if (isNaN(amountYuan)) return false
  
  // 将用户输入的元转换为分，与 availableBalance（分）进行比较
  const amountCent = amountYuan * 100
  return amountYuan > 0 && amountCent <= availableBalance.value && withdrawForm.value.account
})

const loadWithdrawRecords = async (isLoadMore = false) => {
  loading.value = true
  try {
    const params = {
      stationId: stationId.value,
      status: activeFilter.value === 0 ? '' : getStatusValue(activeFilter.value),
      page: isLoadMore ? page.value + 1 : 1,
      pageSize: 10
    }
    const res = await getWithdrawnRecords(params)
    console.log('提现记录API返回数据:', res)
    if (res && res.code === 200) {
      const data = res.data
      // 适配不同的数据结构
      const records = data.records || data.list || data
      if (isLoadMore) {
        withdrawRecords.value = [...withdrawRecords.value, ...records]
      } else {
        withdrawRecords.value = records
      }
      page.value = params.page
    }
  } catch (error) {
    console.error('获取提现记录失败:', error)
    showToast('获取提现记录失败')
  } finally {
    loading.value = false
  }
}

const handleApplyWithdraw = async () => {
  try {
    await applyWithdrawn({
      stationId: stationId.value,
      amount: parseFloat(withdrawForm.value.amount) * 100, // 将元转换为分
      account: withdrawForm.value.account,
      remark: withdrawForm.value.remark
    })
    showToast('提现申请已提交，等待审核', 'success')
    // 重置表单
    withdrawForm.value = {
      amount: '',
      account: '',
      remark: ''
    }
    // 刷新数据
    loadAccountData()
    loadWithdrawRecords()
  } catch (error) {
    console.error('提交提现申请失败:', error)
    showToast('提交提现申请失败')
  }
}

const handleFilterChange = (index) => {
  activeFilter.value = index
  loadWithdrawRecords()
}

const handleApprove = async (recordId) => {
  try {
    await reviewWithdrawn({ id: recordId, status: 1 })
    showToast('审核通过', 'success')
    loadWithdrawRecords()
  } catch (error) {
    console.error('审核失败:', error)
    showToast('审核失败')
  }
}

const handleReject = async (recordId) => {
  try {
    await reviewWithdrawn({ id: recordId, status: 2 })
    showToast('审核失败', 'success')
    loadWithdrawRecords()
  } catch (error) {
    console.error('拒绝失败:', error)
    showToast('拒绝失败')
  }
}

// 从字典获取提现状态文本
const getStatusText = (status) => {
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Withdraw.status']) {
      console.warn('字典数据未加载或不存在 Withdraw.status')
      // 降级处理：使用默认映射
      const statusMap = {
        0: '待审核',
        1: '审核通过',
        2: '审核失败'
      }
      return statusMap[status] || '未知状态'
    }
    
    const withdrawStatusDict = dicts['Withdraw.status']
    const dictItem = withdrawStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : '未知状态'
  } catch (error) {
    console.error('获取提现状态文本失败:', error)
    return '未知状态'
  }
}

const getStatusClass = (status) => {
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Withdraw.status']) {
      // 降级处理：使用默认映射
      const statusClassMap = {
        0: 'status-pending',
        1: 'status-approved',
        2: 'status-rejected'
      }
      return statusClassMap[status] || ''
    }
    
    const withdrawStatusDict = dicts['Withdraw.status']
    const dictItem = withdrawStatusDict.find(item => item.value == status)
    
    // 如果字典项有颜色，返回自定义样式类名
    if (dictItem && dictItem.color) {
      return 'status-custom'
    }
    
    // 降级处理：使用默认映射
    const statusClassMap = {
      0: 'status-pending',
      1: 'status-approved',
      2: 'status-rejected'
    }
    return statusClassMap[status] || ''
  } catch (error) {
    console.error('获取提现状态样式失败:', error)
    return ''
  }
}

// 从字典获取提现状态值（用于过滤）
const getStatusValue = (filterIndex) => {
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Withdraw.status']) {
      console.warn('字典数据未加载或不存在 Withdraw.status')
      // 降级处理：使用默认映射
      const statusMap = {
        1: 0, // 待审核
        2: 1, // 审核通过
        3: 2  // 审核失败
      }
      return statusMap[filterIndex] || ''
    }
    
    // 跳过"全部"选项（index 0）
    if (filterIndex === 0) {
      return ''
    }
    
    const withdrawStatusDict = dicts['Withdraw.status']
    // 从字典中获取对应索引的状态值
    // 注意：需要确保filterOptions与字典数据顺序一致
    const dictItem = withdrawStatusDict[filterIndex - 1]
    
    return dictItem ? dictItem.value : ''
  } catch (error) {
    console.error('获取提现状态值失败:', error)
    // 降级处理：使用默认映射
    const statusMap = {
      1: 0, // 待审核
      2: 1, // 审核通过
      3: 2  // 审核失败
    }
    return statusMap[filterIndex] || ''
  }
}
</script>

<style scoped>
/* 全局容器 */
.withdraw-container {
  min-height: 100vh;
  background: #F8F9FA;
  padding-bottom: 120rpx;
}

/* 顶部卡片 */
.top-card {
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  padding: 40rpx 30rpx;
  border-radius: 0 0 40rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.3);
}

.page-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #FFFFFF;
  display: block;
}

/* 区域样式 */
.section {
  padding: 20rpx 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 20rpx;
  padding-left: 20rpx;
  border-left: 6rpx solid #667EEA;
}

/* 信息卡片 */
.info-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.info-card {
  background: #FFFFFF;
  padding: 30rpx 24rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  text-align: center;
  color: #FFFFFF;
}

.info-card:active {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.info-card.blue {
  background: linear-gradient(135deg, #4FACFE 0%, #00F2FE 100%);
}

.info-card.pink {
  background: linear-gradient(135deg, #F093FB 0%, #F5576C 100%);
}

.info-card.green {
  background: linear-gradient(135deg, #43E97B 0%, #38F9D7 100%);
}

.info-label {
  font-size: 24rpx;
  font-weight: 500;
  margin-bottom: 12rpx;
  display: block;
  opacity: 0.9;
}

.info-value {
  font-size: 40rpx;
  font-weight: 700;
  display: block;
}

/* 移除旧的颜色类 */
/* .info-value.blue { color: #4FACFE; }
.info-value.pink { color: #F093FB; }
.info-value.green { color: #43E97B; } */

/* 申请提现表单 */
.apply-form {
  background: #FFFFFF;
  padding: 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #666666;
  font-weight: 500;
}

.form-input input,
.form-input textarea {
  width: 100%;
  padding: 24rpx 24rpx;
  border: 2rpx solid #E0E0E0;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #1A1A1A;
  background-color: #FFFFFF;
  box-sizing: border-box;
  transition: all 0.3s ease;
  line-height: 1.5;
  min-height: 80rpx;
}

.form-input input:focus,
.form-input textarea:focus {
  border-color: #667EEA;
  outline: none;
  box-shadow: 0 0 0 8rpx rgba(102, 126, 234, 0.1);
}

.balance-tip {
  font-size: 22rpx;
  color: #999999;
  margin-top: 8rpx;
  display: block;
  text-align: center;
}

.apply-btn {
  width: 100%;
  padding: 20rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  color: white;
  border: none;
  border-radius: 20rpx;
  font-size: 28rpx;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
  margin-top: 12rpx;
}

.apply-btn:active:not(:disabled) {
  transform: scale(0.97);
  box-shadow: 0 2rpx 10rpx rgba(102, 126, 234, 0.4);
}

.apply-btn:disabled {
  background: linear-gradient(135deg, #C0C4CC 0%, #909399 100%);
  cursor: not-allowed;
  opacity: 0.6;
  box-shadow: none;
}

/* 记录过滤 */
.records-filter {
  margin-bottom: 20rpx;
}

.segmented-control {
  display: flex;
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 6rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.segment-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999999;
  border-radius: 20rpx;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
}

.segment-item.active {
  color: #667EEA;
  background: linear-gradient(135deg, #E6F7FF 0%, #F0F5FF 100%);
  font-weight: 600;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.record-item {
  padding: 28rpx;
  border-radius: 24rpx;
  background-color: #FFFFFF;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.record-item:active {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;
}

.record-info {
  flex: 1;
}

.record-no {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 6rpx;
  display: block;
}

.record-time {
  font-size: 24rpx;
  color: #999999;
}

.record-status {
  font-size: 24rpx;
  font-weight: 600;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
}

.status-pending {
  color: #FA8C16;
  background-color: #FFF7E6;
}

.status-approved {
  color: #52C41A;
  background-color: #F6FFED;
}

.status-rejected {
  color: #FF4D4F;
  background-color: #FFF1F0;
}

.status-paid {
  color: #1890FF;
  background-color: #E6F7FF;
}

.status-failed {
  color: #BFBFBF;
  background-color: #F5F5F5;
}

.record-content {
  margin-bottom: 20rpx;
}

.record-amount,
.record-account,
.record-remark {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 16rpx;
}

.record-amount:last-child,
.record-account:last-child,
.record-remark:last-child {
  margin-bottom: 0;
}

.amount-label,
.account-label,
.remark-label {
  font-size: 26rpx;
  color: #666666;
  width: 120rpx;
}

.amount-value {
  font-size: 32rpx;
  font-weight: 600;
  color: #52C41A;
}

.account-value,
.remark-value {
  font-size: 26rpx;
  color: #333333;
  flex: 1;
}

.record-footer {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx dashed #E0E0E0;
}

.record-actions {
  display: flex;
  gap: 16rpx;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx dashed #E0E0E0;
}

.approve-btn {
  flex: 1;
  padding: 18rpx;
  background: linear-gradient(135deg, #43E97B 0%, #38F9D7 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 26rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  box-shadow: 0 4rpx 12rpx rgba(67, 233, 123, 0.3);
}

.approve-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(67, 233, 123, 0.4);
}

.reject-btn {
  flex: 1;
  padding: 18rpx;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 26rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
}

.reject-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.4);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #999999;
}

.empty-icon {
  font-size: 128rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-state text {
  font-size: 28rpx;
  color: #666666;
}
</style>