<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getFundSummary } from '@/api/commission'
import type { FundSummary } from '@/api/commission'
import { createWithdrawal, getWithdrawalRecords } from '@/api/withdrawal'
import type { WithdrawalRecord } from '@/api/withdrawal'
import SimplePicker from '@/components/SimplePicker.vue'

type LoginUserInfo = {
  shop_id?: number
  username?: string
}

const commissionSummary = ref<FundSummary | null>(null)
const shopId = ref<number>(0)
const withdrawAmount = ref('')
const accountName = ref('')
const accountNumber = ref('')
const withdrawRecords = ref<WithdrawalRecord[]>([])
const activeTab = ref<'apply' | 'records'>('apply')
const loading = ref(false)
const submitting = ref(false)
const loadingRecords = ref(false)
const page = ref(1)
const pageSize = 20
const total = ref(0)
const statusFilter = ref<number | undefined>(undefined)
const showStatusPicker = ref(false)
const MIN_WITHDRAW_AMOUNT = 100

const statusOptions = [
  { label: '全部状态', value: undefined },
  { label: '审核中', value: 1 },
  { label: '已通过', value: 2 },
  { label: '已拒绝', value: 3 },
  { label: '已到账', value: 4 },
]

const selectedStatusName = computed(() => {
  if (statusFilter.value === undefined) return '状态'
  const option = statusOptions.find(o => o.value === statusFilter.value)
  return option?.label || '状态'
})

const tabs: Array<{ key: 'apply' | 'records', label: string }> = [
  { key: 'apply', label: '申请提现' },
  { key: 'records', label: '提现记录' },
]

const availableAmount = computed(() => {
  if (!commissionSummary.value) return 0
  return commissionSummary.value.available_commission / 100
})

const canWithdrawByMinAmount = computed(() => availableAmount.value >= MIN_WITHDRAW_AMOUNT)

function formatAmount(amount: number) {
  const yuan = (amount / 100).toFixed(2)
  const parts = yuan.split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return `¥${parts.join('.')}`
}

function getStatusText(status: number, statusName?: string) {
  return statusName || (status === 1 ? '审核中' : status === 2 ? '已通过' : status === 3 ? '已拒绝' : status === 4 ? '已到账' : '未知')
}

function getStatusColor(status: number) {
  const map: Record<number, { bg: string, text: string }> = {
    1: { bg: '#fff3e0', text: '#e65100' },
    2: { bg: '#e8f5e9', text: '#2e7d32' },
    3: { bg: '#ffebee', text: '#c62828' },
    4: { bg: '#e3f2fd', text: '#1565c0' },
  }
  return map[status] || { bg: '#f5f5f5', text: '#999' }
}

function formatTime(time: string) {
  if (!time) return '-'
  const date = new Date(time)
  return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function getLoginUserInfo() {
  return uni.getStorageSync('user_info') as LoginUserInfo | undefined
}

onMounted(() => {
  const userInfo = getLoginUserInfo()
  if (userInfo?.shop_id) {
    shopId.value = userInfo.shop_id
  }
  loadCommissionSummary()
  loadWithdrawRecords()
})

async function loadCommissionSummary() {
  loading.value = true
  try {
    const userInfo = getLoginUserInfo()
    commissionSummary.value = await getFundSummary(userInfo?.username ? { username: userInfo.username } : undefined)
    withdrawAmount.value = availableAmount.value.toFixed(2)
  } catch (error) {
    console.error('加载佣金概览失败:', error)
  } finally {
    loading.value = false
  }
}

async function loadWithdrawRecords(isRefresh = false) {
  if (!shopId.value) return
  if (isRefresh) {
    page.value = 1
    withdrawRecords.value = []
  }
  loadingRecords.value = true
  try {
    const params: any = { page: page.value, page_size: pageSize }
    if (statusFilter.value !== undefined) {
      params.status = statusFilter.value
    }
    const response = await getWithdrawalRecords(shopId.value, params)
    if (page.value === 1) {
      withdrawRecords.value = response.items || []
    } else {
      withdrawRecords.value.push(...(response.items || []))
    }
    total.value = response.total || 0
  } catch (error) {
    console.error('加载提现记录失败:', error)
  } finally {
    loadingRecords.value = false
  }
}

function setQuickAmount(amount: number) {
  withdrawAmount.value = amount.toString()
}

function setAllAmount() {
  withdrawAmount.value = availableAmount.value.toFixed(2)
}

async function handleSubmit() {
  const amount = parseFloat(withdrawAmount.value)
  if (!amount || amount <= 0) {
    uni.$u.toast('请输入提现金额')
    return
  }
  if (amount < MIN_WITHDRAW_AMOUNT) {
    uni.$u.toast(`满${MIN_WITHDRAW_AMOUNT}元才可提现`)
    return
  }
  if (amount > availableAmount.value) {
    uni.$u.toast('提现金额超过可用余额')
    return
  }
  const name = accountName.value.trim()
  if (!name) {
    uni.$u.toast('请输入收款人姓名')
    return
  }
  const account = accountNumber.value.trim()
  if (!account) {
    uni.$u.toast('请输入支付宝账号')
    return
  }
  submitting.value = true
  try {
    await createWithdrawal(shopId.value, {
      account_name: name,
      account_number: account,
      amount: Math.round(amount * 100),
      withdrawal_method: 'alipay',
    })
    uni.$u.toast('提现申请已提交')
    withdrawAmount.value = ''
    accountName.value = ''
    accountNumber.value = ''
    await loadCommissionSummary()
    page.value = 1
    await loadWithdrawRecords()
    activeTab.value = 'records'
  } catch (error) {
    console.error('提现申请失败:', error)
  } finally {
    submitting.value = false
  }
}

function handleTabChange(tab: 'apply' | 'records') {
  activeTab.value = tab
  if (tab === 'records') {
    loadWithdrawRecords(true)
  }
}

function onStatusConfirm(option: { label: string, value: any }) {
  statusFilter.value = option.value
  loadWithdrawRecords(true)
}

function loadMore() {
  if (withdrawRecords.value.length < total.value) {
    page.value++
    loadWithdrawRecords()
  }
}

</script>

<template>
  <view class="bg-page min-h-screen">
    <!-- 顶部搜索区域 -->
    <view class="bg-white px-4 pt-4 pb-3">
      <view class="flex rounded-full bg-[#f1f5f9] p-1">
        <view
          v-for="tab in tabs"
          :key="tab.key"
          class="flex-1 text-center py-2 rounded-full text-14px font-medium transition-all"
          :class="activeTab === tab.key ? 'bg-white text-[#212121] shadow-sm' : 'text-[#999]'"
          @click="handleTabChange(tab.key)"
        >
          {{ tab.label }}
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="px-4 pb-4">
      <!-- 申请提现 -->
      <view v-if="activeTab === 'apply'">
        <!-- 可提现金额卡片 -->
        <view class="bg-white rounded-16px p-5 mt-4 shadow-[0_2px_12px_rgba(0,0,0,0.08)]">
          <view class="flex items-center justify-between">
            <view>
              <text class="text-12px text-[#999]">可提现金额</text>
              <text class="text-32px font-700 text-[#212121] block mt-1">
                ¥{{ availableAmount.toFixed(2) }}
              </text>
            </view>
            <image src="@/static/icons/提现管理.png" class="w-12 h-12 rounded-12px" mode="aspectFit" />
          </view>
        </view>

        <!-- 提现金额输入 -->
        <view class="bg-white rounded-16px p-4 mt-3">
          <text class="text-12px text-[#999]">提现金额</text>
          <view class="flex items-center mt-2">
            <text class="text-24px text-[#212121] mr-2">¥</text>
            <input
              v-model="withdrawAmount"
              type="digit"
              class="flex-1 text-24px text-[#212121]"
              placeholder="0.00"
            />
          </view>
          <view class="flex gap-2 mt-3">
            <view
              v-for="amount in [100, 500, 1000]"
              :key="amount"
              class="px-4 py-2 rounded-full text-13px"
              :class="withdrawAmount == amount.toString() ? 'bg-brand text-white' : 'bg-[#f1f5f9] text-[#666]'"
              @click="setQuickAmount(amount)"
            >
              ¥{{ amount }}
            </view>
            <view
              class="px-4 py-2 rounded-full text-13px"
              :class="withdrawAmount == availableAmount.toFixed(2) ? 'bg-brand text-white' : 'bg-[#f1f5f9] text-[#666]'"
              @click="setAllAmount"
            >
              全部
            </view>
          </view>
        </view>

        <!-- 收款信息 -->
        <view class="bg-white rounded-16px p-4 mt-3">
          <text class="text-12px text-[#999]">收款人姓名</text>
          <input
            v-model="accountName"
            class="w-full text-16px text-[#212121] mt-2"
            placeholder="请输入姓名"
          />
        </view>

        <view class="bg-white rounded-16px p-4 mt-3">
          <text class="text-12px text-[#999]">支付宝账号</text>
          <input
            v-model="accountNumber"
            class="w-full text-16px text-[#212121] mt-2"
            placeholder="请输入账号"
          />
        </view>

        <view class="mt-6 mb-3 flex items-center gap-1.5 px-3 py-2 rounded-12px bg-[var(--color-warning-bg)]">
          <i class="i-mdi-information-outline text-14px text-warning" />
          <text class="text-12px" :class="canWithdrawByMinAmount ? 'text-warning' : 'text-error'">
            满100元才可提现
          </text>
        </view>

        <!-- 提交按钮 -->
        <view
          class="bg-brand rounded-full py-4 text-center text-16px font-600 text-white"
          :class="{ 'opacity-50': submitting || !canWithdrawByMinAmount }"
          @click="handleSubmit"
        >
          {{ submitting ? '提交中...' : '确认提现' }}
        </view>
      </view>

      <!-- 提现记录 -->
      <view v-else>
        <view class="flex items-center gap-2 mt-4 mb-3">
          <view class="flex items-center gap-1 px-3 py-1.5 bg-[#f8fafc] rounded-full" @click="showStatusPicker = true">
            <text class="text-12px text-[#64748b]">{{ selectedStatusName }}</text>
            <i class="i-mdi-chevron-down text-12px text-[#94a3b8]" />
          </view>
          <view
            v-if="statusFilter !== undefined"
            class="flex items-center gap-1 px-2 py-1.5 rounded-full bg-[#ff4d4f]/10 text-[#ff4d4f]"
            @click="statusFilter = undefined; loadWithdrawRecords(true)"
          >
            <i class="i-mdi-close text-12px" />
            <text class="text-12px font-medium">清除</text>
          </view>
        </view>

        <view v-if="loadingRecords && page === 1" class="pt-20 flex justify-center">
          <text class="text-14px text-[#64748b]">加载中...</text>
        </view>

        <view v-else-if="withdrawRecords.length > 0" class="space-y-3">
          <view
            v-for="record in withdrawRecords"
            :key="record.id"
            class="bg-white rounded-12px p-4"
          >
            <view class="flex items-center justify-between mb-2">
              <text class="text-12px text-[#999]">{{ formatTime(record.created_at) }}</text>
              <view
                :style="{ backgroundColor: getStatusColor(record.status).bg, color: getStatusColor(record.status).text }"
                class="px-2 py-0.5 rounded text-11px font-500"
              >
                {{ getStatusText(record.status, record.status_name) }}
              </view>
            </view>
            <view class="flex items-center justify-between">
              <text class="text-14px text-[#666]">{{ record.account_name }}</text>
              <text class="text-18px font-600 text-[#ff4d4f]">-{{ formatAmount(record.amount) }}</text>
            </view>
            <view v-if="record.status === 3 && record.reject_reason" class="mt-2 pt-2 border-t border-[#f0f0f0]">
              <text class="text-12px text-[#ff4d4f]">拒绝原因: {{ record.reject_reason }}</text>
            </view>
          </view>

          <view v-if="withdrawRecords.length < total" class="py-4 text-center">
            <text v-if="loadingRecords" class="text-12px text-[#64748b]">加载中...</text>
            <text v-else class="text-12px text-brand" @click="loadMore">加载更多</text>
          </view>
          <view v-else class="py-4 text-center">
            <text class="text-12px text-[#cbd5e1]">没有更多了</text>
          </view>
        </view>

        <view v-else class="pt-16 flex flex-col items-center">
          <i class="i-mdi-file-document-outline text-5xl text-[#e0e0e0] mb-3" />
          <text class="text-14px text-[#999]">暂无提现记录</text>
        </view>
      </view>
    </view>

    <SimplePicker
      v-model:show="showStatusPicker"
      :options="statusOptions"
      title="选择提现状态"
      @confirm="onStatusConfirm"
    />
  </view>
</template>

<style scoped>
.space-y-3 > view:not(:last-child) {
  margin-bottom: 12px;
}
</style>
