<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getFundSummary, getCommissionRecords, getCommissionStats } from '@/api/commission'
import type { FundSummary, CommissionRecord, CommissionStats } from '@/api/commission'
import AgentFundSummaryCard from '@/components/AgentFundSummaryCard.vue'
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 commissionRecords = ref<CommissionRecord[]>([])
const commissionStats = ref<CommissionStats | null>(null)
const loadingRecords = ref(false)
const page = ref(1)
const pageSize = 20
const total = ref(0)
const searchKeyword = ref('')
const sourceFilter = ref<string | undefined>(undefined)
const showSourcePicker = ref(false)
const showSearchTypePicker = ref(false)

const sourceOptions = [
  { label: '全部来源', value: undefined },
  { label: '成本价差', value: 'cost_diff' },
  { label: '一次性佣金', value: 'one_time' },
]

const searchType = ref<'iccid' | 'virtual_no' | 'order_no'>('iccid')

const searchTypeOptions = [
  { label: 'ICCID', value: 'iccid' },
  { label: '虚拟号', value: 'virtual_no' },
  { label: '订单号', value: 'order_no' }
]

const selectedSourceName = computed(() => {
  if (sourceFilter.value === undefined) return '来源'
  const option = sourceOptions.find(o => o.value === sourceFilter.value)
  return option?.label || '来源'
})

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 getSourceText(source: string) {
  const map: Record<string, string> = {
    cost_diff: '成本价差',
    one_time: '一次性佣金',
    tier_bonus: '梯度奖励',
  }
  return map[source] || source
}

function getStatusText(status: number) {
  return status === 1 ? '已入账' : '已失效'
}

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()
  loadCommissionStats()
  loadCommissionRecords()
})

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

async function loadCommissionStats() {
  if (!shopId.value) return
  try {
    commissionStats.value = await getCommissionStats(shopId.value)
  } catch (error) {
    console.error('加载佣金统计失败:', error)
  }
}

async function loadCommissionRecords(isRefresh = false) {
  if (!shopId.value) return
  if (isRefresh) {
    page.value = 1
    commissionRecords.value = []
  }
  loadingRecords.value = true
  try {
    const params: any = { page: page.value, page_size: pageSize }
    if (sourceFilter.value) {
      params.commission_source = sourceFilter.value
    }
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.trim()
      if (searchType.value === 'iccid') params.iccid = keyword
      else if (searchType.value === 'virtual_no') params.virtual_no = keyword
      else params.order_no = keyword
    }
    const response = await getCommissionRecords(shopId.value, params)
    if (page.value === 1) {
      commissionRecords.value = response.items || []
    } else {
      commissionRecords.value.push(...(response.items || []))
    }
    total.value = response.total || 0
  } catch (error) {
    console.error('加载佣金明细失败:', error)
  } finally {
    loadingRecords.value = false
  }
}

function handleSearch() {
  loadCommissionRecords(true)
}

function onSourceConfirm(option: { label: string, value: any }) {
  sourceFilter.value = option.value
  loadCommissionRecords(true)
}

function onSearchTypeConfirm(option: { label: string, value: any }) {
  searchType.value = option.value
}

function loadMore() {
  if (commissionRecords.value.length < total.value) {
    page.value++
    loadCommissionRecords()
  }
}

</script>

<template>
  <view class="bg-page min-h-screen">
    <!-- 顶部搜索区域 -->
    <view class="bg-white px-4 pt-4 pb-3">
      <!-- 搜索框 -->
      <view class="relative flex items-center">
        <input
          v-model="searchKeyword"
          class="flex-1 h-10 bg-[#f1f5f9] rounded-full pl-4 pr-12 text-sm text-[#1e293b] placeholder-[#94a3b8]"
          :placeholder="searchType === 'iccid' ? '搜索ICCID' : searchType === 'virtual_no' ? '搜索虚拟号' : '搜索订单号'"
          @confirm="handleSearch"
        />
        <view class="absolute right-1 flex items-center">
          <view v-if="searchKeyword" class="w-8 h-8 flex items-center justify-center text-[#94a3b8]"
            @click="searchKeyword = ''">
            <i class="i-mdi-close-circle text-lg" />
          </view>
          <view class="w-8 h-8 flex items-center justify-center text-brand" @click="handleSearch">
            <i class="i-mdi-magnify text-xl" />
          </view>
        </view>
      </view>

      <!-- 筛选器 -->
      <view class="flex items-center gap-2 mt-3">
        <view class="flex items-center gap-1 px-3 py-1.5 bg-[#f8fafc] rounded-full" @click="showSearchTypePicker = true">
          <text class="text-12px text-[#64748b]">{{ searchType === 'iccid' ? 'ICCID' : searchType === 'virtual_no' ? '虚拟号' : '订单号' }}</text>
          <i class="i-mdi-chevron-down text-12px text-[#94a3b8]" />
        </view>
        <view class="flex items-center gap-1 px-3 py-1.5 bg-[#f8fafc] rounded-full" @click="showSourcePicker = true">
          <text class="text-12px" :class="sourceFilter !== undefined ? 'text-brand font-medium' : 'text-[#64748b]'">{{ selectedSourceName }}</text>
          <i class="i-mdi-chevron-down text-12px text-[#94a3b8]" />
        </view>
        <view v-if="sourceFilter !== undefined" class="flex items-center gap-1 px-2 py-1.5 rounded-full bg-[#ff4d4f]/10 text-[#ff4d4f]"
          @click="sourceFilter = undefined; loadCommissionRecords(true)">
          <i class="i-mdi-close text-12px" />
          <text class="text-12px font-medium">清除</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="px-4 pb-4">
      <!-- 概览卡片 -->
      <AgentFundSummaryCard class="mt-4" :summary="commissionSummary" />

      <!-- 佣金统计 -->
      <view class="bg-white rounded-16px p-4 mt-3 shadow-[0_2px_8px_rgba(0,0,0,0.04)]">
        <text class="text-14px font-600 text-[#212121]">佣金统计</text>
        <view class="mt-3 space-y-3">
          <view class="flex items-center justify-between">
            <view class="flex items-center gap-2">
              <view class="w-2 h-2 rounded-full bg-[#2196f3]" />
              <text class="text-13px text-[#666]">成本价差</text>
            </view>
            <view class="flex items-center gap-2">
              <span class="text-11px text-[#999]">{{ commissionStats ? (commissionStats.cost_diff_percent / 10).toFixed(1) + '%' : '--' }}</span>
              <text class="text-14px font-600 text-[#212121]">{{ commissionStats ? formatAmount(commissionStats.cost_diff_amount) : '--' }}</text>
            </view>
          </view>
          <view class="flex items-center justify-between">
            <view class="flex items-center gap-2">
              <view class="w-2 h-2 rounded-full bg-[#ff9800]" />
              <text class="text-13px text-[#666]">一次性佣金</text>
            </view>
            <view class="flex items-center gap-2">
              <span class="text-11px text-[#999]">{{ commissionStats ? (commissionStats.one_time_percent / 10).toFixed(1) + '%' : '--' }}</span>
              <text class="text-14px font-600 text-[#212121]">{{ commissionStats ? formatAmount(commissionStats.one_time_amount) : '--' }}</text>
            </view>
          </view>
          <view class="flex items-center justify-between pt-3 border-t border-[#f0f0f0]">
            <text class="text-13px font-600 text-[#212121]">总计</text>
            <text class="text-16px font-700 text-brand">{{ commissionStats ? formatAmount(commissionStats.total_amount) : '--' }}</text>
          </view>
        </view>
      </view>

      <!-- 佣金明细 -->
      <view class="mt-4">
        <view class="flex items-center justify-between mb-3">
          <text class="text-14px font-600 text-[#212121]">佣金明细</text>
          <text class="text-12px text-[#999]">共 {{ total }} 条</text>
        </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="commissionRecords.length > 0" class="space-y-2">
          <view
            v-for="record in commissionRecords"
            :key="record.id"
            class="bg-white rounded-12px p-4"
          >
            <view class="flex items-center justify-between mb-2">
              <view class="flex items-center gap-2">
                <text class="text-14px font-500 text-[#212121]">{{ getSourceText(record.commission_source) }}</text>
                <view :class="record.status === 1 ? 'bg-[#e8f5e9] text-[#2e7d32]' : 'bg-[#f5f5f5] text-[#999]'"
                  class="px-2 py-0.5 rounded text-11px">
                  {{ getStatusText(record.status) }}
                </view>
              </view>
              <text class="text-16px font-600 text-[#52c41a]">+{{ formatAmount(record.amount) }}</text>
            </view>
            <view class="flex items-center justify-between text-12px text-[#999]">
              <text>{{ formatTime(record.created_at) }}</text>
            </view>
          </view>

          <view v-if="commissionRecords.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]">{{ searchKeyword ? '未找到相关结果' : '暂无佣金记录' }}</text>
        </view>
      </view>
    </view>

    <SimplePicker
      v-model:show="showSourcePicker"
      :options="sourceOptions"
      title="选择佣金来源"
      @confirm="onSourceConfirm"
    />

    <SimplePicker
      v-model:show="showSearchTypePicker"
      :options="searchTypeOptions"
      title="选择搜索类型"
      @confirm="onSearchTypeConfirm"
    />
  </view>
</template>

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