<template>
  <view class="withdraw-container">
    <!-- 账户概览 -->
    <view class="section">
      <view class="section-title">账户信息</view>
      <view class="info-cards">
        <view class="info-card">
          <text class="info-label">可提现余额</text>
          <text class="info-value accent-blue">¥{{ formatAmount(availableBalance || 0) }}</text>
        </view>
        <view class="info-card">
          <text class="info-label">待审核金额</text>
          <text class="info-value accent-warning">¥{{ formatAmount(pendingAmount || 0) }}</text>
        </view>
        <view class="info-card">
          <text class="info-label">累计提现</text>
          <text class="info-value accent-success">¥{{ 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.label }}</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" :style="getStatusStyle(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="isPendingStatus(record.status)">
            <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">
        <view class="empty-icon-wrapper"><AppIcon name="inbox" :size="80" color="#B0B0B0" /></view>
        <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, fmtDictName, getDictColor } from '../../utils/index.js'
import dictUtil, { loadDicts } from '../../utils/dict.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 = computed(() => dictUtil.getDictFilterOptions('WithdrawnRecord.status'))
const withdrawRecords = ref([])

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

// 加载账户数据
const loadAccountData = async () => {
  loading.value = true
  try {
    // 获取站点账户详情
    const res = await getStationAccounts({ stationId: stationId.value, page: 1, pageSize: 1 })

    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
      } else {
        availableBalance.value = 0
      }
    } else {
      availableBalance.value = 0
    }

    // 获取提现统计数据
    const withdrawRes = await getWithdrawnRecords({ stationId: stationId.value })

    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 => isPendingStatus(record.status))
          .reduce((sum, record) => sum + (record.amount || 0), 0)

        totalWithdrawn.value = records
          .filter(record => isApprovedStatus(record.status))
          .reduce((sum, record) => sum + (record.amount || 0), 0)
      } else {
        pendingAmount.value = 0
        totalWithdrawn.value = 0
      }
    } else {
      pendingAmount.value = 0
      totalWithdrawn.value = 0
    }
  } catch (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)
    if (res && res.code === 200) {
      const records = res.data.records || res.data.list || res.data
      if (isLoadMore) {
        withdrawRecords.value = [...withdrawRecords.value, ...records]
      } else {
        withdrawRecords.value = records
      }
      page.value = params.page
    }
  } catch (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) {
    showToast('提交提现申请失败')
  }
}

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

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

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

// 从字典获取提现状态文本
const getStatusText = (status) => {
  return fmtDictName('WithdrawnRecord.status', status)
}

// 从字典获取提现状态内联样式
const getStatusStyle = (status) => {
  const color = getDictColor('WithdrawnRecord.status', status)
  if (color) {
    return {
      color: color,
      backgroundColor: `${color}1A`
    }
  }
  return {}
}

// 从字典获取提现状态值（用于过滤）
const getStatusValue = (filterIndex) => {
  if (filterIndex === 0) return ''
  const options = dictUtil.getDictOptions('WithdrawnRecord.status')
  const idx = filterIndex - 1
  return options[idx] ? options[idx].value : ''
}

const isPendingStatus = (status) => {
  return status == dictUtil.getDictValue('WithdrawnRecord.status', '待审核')
}

const isApprovedStatus = (status) => {
  return status == dictUtil.getDictValue('WithdrawnRecord.status', '已通过')
}
</script>

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

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


.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 20rpx;
  padding-left: 24rpx;
  position: relative;
}
.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16rpx;
  height: 16rpx;
  background: #C6171E;
  border-radius: 50%;
}

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

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

.info-label {
  font-size: 22rpx;
  font-weight: 500;
  color: #999999;
  margin-bottom: 8rpx;
  display: block;
}

.info-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #1A1A1A;
  display: block;
}

.info-value.accent-blue {
  color: #2196F3;
}

.info-value.accent-warning {
  color: #FF9800;
}

.info-value.accent-success {
  color: #52C41A;
}

/* 申请提现表单 */
.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: 8rpx;
  margin-bottom: 16rpx;
}

.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: 20rpx 28rpx;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #1A1A1A;
  background-color: #F5F5F5;
  box-sizing: border-box;
  transition: all 0.25s ease;
  line-height: 1.5;
  min-height: 80rpx;
}

.form-input input:focus,
.form-input textarea:focus {
  outline: none;
  box-shadow: 0 0 0 6rpx rgba(198, 23, 30, 0.2);
}

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

.apply-btn {
  width: 100%;
  padding: 20rpx;
  background: #C6171E;
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 28rpx;
  font-weight: 600;
  transition: all 0.25s ease;
  box-shadow: 0 4rpx 16rpx rgba(198, 23, 30, 0.3);
  margin-top: 12rpx;
}

.apply-btn:active:not(:disabled) {
  transform: scale(0.97);
  box-shadow: 0 2rpx 10rpx rgba(198, 23, 30, 0.25);
}

.apply-btn:disabled {
  background: #CCCCCC;
  opacity: 0.5;
  box-shadow: none;
}

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

.segmented-control {
  display: flex;
  background: #F5F5F5;
  border-radius: 16rpx;
  padding: 6rpx;
}

.segment-item {
  flex: 1;
  text-align: center;
  padding: 18rpx 0;
  font-size: 26rpx;
  color: #666666;
  border-radius: 12rpx;
  transition: all 0.25s ease;
  font-weight: 400;
}

.segment-item.active {
  color: #FFFFFF;
  background: #C6171E;
  font-weight: 500;
  box-shadow: 0 4rpx 12rpx rgba(198, 23, 30, 0.3);
}

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

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

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

.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: 22rpx;
  font-weight: 500;
  padding: 6rpx 24rpx;
  border-radius: 100rpx;
}


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

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

.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: #1A1A1A;
  flex: 1;
}

.record-footer {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #F0F0F0;
}

.record-actions {
  display: flex;
  gap: 16rpx;
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #F0F0F0;
}

.approve-btn {
  flex: 1;
  padding: 18rpx;
  background: #52C41A;
  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(82, 196, 26, 0.25);
}

.approve-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(82, 196, 26, 0.3);
}

.reject-btn {
  flex: 1;
  padding: 18rpx;
  background: #C6171E;
  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(198, 23, 30, 0.25);
}

.reject-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(198, 23, 30, 0.35);
}

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


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