<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'

// 佣金概览
const commissionSummary = ref<FundSummary | null>(null)

// 店铺ID (从登录信息获取)
const shopId = ref<number>(0)

// 从本地存储获取用户信息
function getUserInfo() {
  const userInfo = uni.getStorageSync('user_info')
  return userInfo || null
}

// 提现金额（元）
const withdrawAmount = ref('')

// 账户信息
const accountName = ref('')
const accountNumber = ref('')

// 提现记录
const withdrawRecords = ref<WithdrawalRecord[]>([])

// 当前Tab
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 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 || '全部状态'
})

// Tab选项
const tabs = [
  { key: 'apply', label: '申请提现' },
  { key: 'records', label: '提现记录' },
]

// 可提现金额（分转元）
const availableAmount = computed(() => {
  if (!commissionSummary.value) return 0
  return commissionSummary.value.available_commission / 100
})

// 格式化可提现金额显示（带千分号）
const formattedAvailableAmount = computed(() => {
  const amount = availableAmount.value.toFixed(2)
  const parts = amount.split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
})

// 实际到账金额 (无手续费,带千分号)
const actualAmount = computed(() => {
  const amount = parseFloat(withdrawAmount.value) || 0
  const fixed = amount.toFixed(2)
  const parts = fixed.split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
})

// 格式化输入金额显示 (带千分号)
const formattedWithdrawAmount = computed(() => {
  if (!withdrawAmount.value) return '0.00'
  const amount = parseFloat(withdrawAmount.value) || 0
  const fixed = amount.toFixed(2)
  const parts = fixed.split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
})

// 格式化金额（分转元,带千分号）
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) {
  if (statusName) return statusName
  const map: Record<number, string> = {
    1: '审核中',
    2: '已通过',
    3: '已拒绝',
    4: '已到账',
  }
  return map[status] || '未知'
}

// 获取提现状态颜色
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)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 页面加载
onMounted(() => {
  // 从登录信息获取 shop_id
  const userInfo = getUserInfo()
  if (userInfo?.shop_id) {
    shopId.value = userInfo.shop_id
  }

  loadCommissionSummary()
  loadWithdrawRecords()
})

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

// 加载提现记录
async function loadWithdrawRecords() {
  if (!shopId.value) return

  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 > availableAmount.value) {
    uni.$u.toast('提现金额超过可用余额')
    return
  }

  const name = accountName.value.trim()
  if (!name) {
    uni.$u.toast('请输入收款人姓名')
    return
  }
  if (!/^[\u4e00-\u9fa5]{2,20}$|^[a-zA-Z]{2,20}$/.test(name)) {
    uni.$u.toast('姓名格式错误')
    return
  }

  const account = accountNumber.value.trim()
  if (!account) {
    uni.$u.toast('请输入支付宝账号')
    return
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!phoneRegex.test(account) && !emailRegex.test(account)) {
    uni.$u.toast('支付宝账号格式错误')
    return
  }

  submitting.value = true

  try {
    const result = 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
  }
}

// 切换Tab
function handleTabChange(tab: 'apply' | 'records') {
  activeTab.value = tab
  if (tab === 'records') {
    page.value = 1
    loadWithdrawRecords()
  }
}

// 状态筛选变化
function onStatusConfirm(option: { label: string, value: any }) {
  statusFilter.value = option.value
  page.value = 1
  withdrawRecords.value = []
  loadWithdrawRecords()
}

// 加载更多
function loadMore() {
  if (withdrawRecords.value.length >= total.value) {
    return
  }
  page.value++
  loadWithdrawRecords()
}
</script>

<template>
  <view class="bg-[var(--bg-page)] min-h-screen pb-safe">
    <view class="bg-brand rounded-12px px-4 py-3 mx-4">
      <text class="text-11px text-white/60">可提现金额</text>
      <text class="text-24px font-700 text-white block mt-1">¥{{ formattedAvailableAmount }}</text>
    </view>

    <view class="px-4 mt-4">
      <view class="flex rounded-full bg-[var(--bg-container)] p-1">
        <view
          v-for="tab in tabs"
          :key="tab.key"
          :class="[
            'flex-1 text-center py-2 rounded-full text-14px transition-all',
            activeTab === tab.key
              ? 'bg-brand text-white font-600'
              : 'text-[var(--text-secondary)]',
          ]"
          @click="handleTabChange(tab.key)"
        >
          {{ tab.label }}
        </view>
      </view>
    </view>

    <view v-if="activeTab === 'apply'" class="px-4 mt-4">
      <view class="bg-[var(--bg-container)] rounded-12px p-4">
        <text class="text-12px text-[var(--text-tertiary)]">提现金额</text>
        <view class="flex items-center mt-1">
          <text class="text-24px text-[var(--text-secondary)] mr-1">¥</text>
          <input
            v-model="withdrawAmount"
            type="digit"
            class="flex-1 text-24px text-[var(--text-primary)]"
            placeholder="0.00"
            placeholder-class="text-[var(--text-quaternary)]"
          >
        </view>
        <view class="flex items-center gap-2 mt-3">
          <view
            v-for="amount in [100, 500, 1000]"
            :key="amount"
            :class="[
              'px-4 py-1.5 text-13px rounded-full transition-all',
              withdrawAmount == amount.toString()
                ? 'bg-brand text-white font-600'
                : 'bg-[var(--bg-muted)] text-[var(--text-secondary)]',
            ]"
            @click="setQuickAmount(amount)"
          >
            {{ amount }}
          </view>
          <view
            :class="[
              'px-4 py-1.5 text-13px rounded-full transition-all font-500',
              withdrawAmount == availableAmount.toFixed(2)
                ? 'bg-brand text-white'
                : 'bg-[var(--bg-muted)] text-[var(--text-secondary)]',
            ]"
            @click="setAllAmount"
          >
            全部
          </view>
        </view>
      </view>

      <view class="bg-[var(--bg-container)] rounded-12px p-4 mt-3">
        <text class="text-12px text-[var(--text-tertiary)]">收款人姓名</text>
        <input
          v-model="accountName"
          class="w-full text-16px text-[var(--text-primary)] mt-1"
          placeholder="请输入姓名"
          placeholder-class="text-[var(--text-quaternary)]"
        >
      </view>

      <view class="bg-[var(--bg-container)] rounded-12px p-4 mt-3">
        <text class="text-12px text-[var(--text-tertiary)]">支付宝账号</text>
        <input
          v-model="accountNumber"
          class="w-full text-16px text-[var(--text-primary)] mt-1"
          placeholder="请输入账号"
          placeholder-class="text-[var(--text-quaternary)]"
        >
      </view>

      <view class="bg-[var(--bg-container)] rounded-12px p-4 mt-3">
        <view class="flex items-center justify-between">
          <text class="text-14px text-[var(--text-secondary)]">提现金额</text>
          <text class="text-20px font-600 text-brand">¥{{ formattedWithdrawAmount }}</text>
        </view>
      </view>

      <view
        :class="[
          'w-full py-4 rounded-12px text-center text-16px font-600 mt-4',
          submitting ? 'bg-[var(--bg-muted)] text-[var(--text-quaternary)]' : 'bg-brand text-white',
        ]"
        @click="handleSubmit"
      >
        {{ submitting ? '提交中...' : '确认提现' }}
      </view>
    </view>

    <view v-else class="px-4 mt-4">
      <view class="flex items-center gap-2 mb-3">
        <view class="flex-1 bg-[var(--bg-container)] rounded-12px px-4 py-3" @click="showStatusPicker = true">
          <text class="text-14px text-[var(--text-primary)]">{{ selectedStatusName }}</text>
        </view>
      </view>

      <view v-if="loadingRecords && page === 1" class="pt-10 center">
        <text class="text-14px text-[var(--text-secondary)]">加载中...</text>
      </view>

      <view v-else-if="withdrawRecords.length > 0" class="space-y-3">
        <view
          v-for="record in withdrawRecords"
          :key="record.id"
          class="bg-[var(--bg-container)] rounded-12px p-4"
        >
          <view class="flex items-center justify-between">
            <text class="text-13px text-[var(--text-tertiary)]">{{ formatTime(record.created_at) }}</text>
            <view
              :style="{
                backgroundColor: getStatusColor(record.status).bg,
                color: getStatusColor(record.status).text,
              }"
              class="px-3 py-1 rounded-full text-12px font-600"
            >
              {{ getStatusText(record.status, record.status_name) }}
            </view>
          </view>
          <view class="flex items-center justify-between mt-3">
            <text class="text-14px text-[var(--text-secondary)]">{{ record.account_name }}</text>
            <text class="text-20px font-700 text-brand">-{{ formatAmount(record.amount) }}</text>
          </view>
          <view v-if="record.status === 3 && record.reject_reason" class="mt-2 pt-2 border-t border-[var(--border-secondary)]">
            <text class="text-12px text-[var(--color-error)]">{{ record.reject_reason }}</text>
          </view>
        </view>

        <view v-if="withdrawRecords.length < total" class="py-4 center">
          <text v-if="loadingRecords" class="text-14px text-[var(--text-secondary)]">加载中...</text>
          <text v-else class="text-14px text-[var(--brand-primary)]" @click="loadMore">加载更多</text>
        </view>
      </view>

      <view v-else class="pt-16 center">
        <text class="text-14px text-[var(--text-secondary)]">暂无记录</text>
      </view>
    </view>

    <view class="h-16" />

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

<style scoped>
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.space-y-2 > view:not(:last-child) {
  margin-bottom: 8px;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
