<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { getUserInfo, logout as logoutApi } from '@/api/auth'
  import { clearToken } from '@/utils/auth'
  import type { UserInfo } from '@/api/auth'
  import { getFundSummary, getCommissionDailyStats } from '@/api/commission'
  import type { FundSummary, DailyCommissionStats } from '@/api/commission'
  import AgentFundSummaryCard from '@/components/AgentFundSummaryCard.vue'


  // 用户信息
  const userInfo = ref<UserInfo | null>(null)
  // 佣金概览
  const commissionSummary = ref<FundSummary | null>(null)
  // 每日佣金统计 (最近7天)
  const dailyStats = ref<DailyCommissionStats[]>([])
  // 加载状态
  const loading = ref(true)
  const loadingCommission = ref(false)

  // 店铺ID
  const shopId = ref<number>(0)

  // 是否为代理账号
  const isAgent = computed(() => userInfo.value?.user_type === 3)
  const todayStat = computed(() => dailyStats.value[0] || null)

  function getLoginUserInfo() {
    return uni.getStorageSync('user_info') as Partial<UserInfo> | undefined
  }

  // 格式化金额（分转元,带千分号）
  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('.')}`
  }

  // 格式化日期 (MM-DD)
  // 根据用户类型动态生成菜单
  function formatDate(dateStr : string) {
    const date = new Date(dateStr)
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${month}-${day}`
  }

  // 加载佣金数据
  async function loadCommissionData(username?: string) {
    if (!isAgent.value) return

    loadingCommission.value = true

    try {
      // 1. 加载佣金概览 (新接口 /shops/fund-summary)
      const summary = await getFundSummary(username ? { username } : undefined)
      commissionSummary.value = summary

      if (!shopId.value) {
        dailyStats.value = []
        return
      }

      const todayStats = await getCommissionDailyStats(shopId.value, {
        days: 1,
      })
      dailyStats.value = todayStats || []
      return

      // 2. 加载最近30天佣金统计
      const stats = await getCommissionDailyStats(shopId.value, { days: 30 })
      dailyStats.value = stats || []
    }
    catch (error) {
      console.error('加载佣金数据失败:', error)
    }
    finally {
      loadingCommission.value = false
    }
  }

  // 加载首页数据
  async function loadHomeData() {
    loading.value = true

    try {
      // 加载用户信息
      const user = await getUserInfo()
      userInfo.value = user

      // 设置店铺ID
      const loginUserInfo = getLoginUserInfo()
      shopId.value = user.shop_id || loginUserInfo?.shop_id || 0
      const fundSummaryUsername = loginUserInfo?.username || user.username

      // 如果是代理账号,加载佣金数据
      if (user.user_type === 3) {
        await loadCommissionData(fundSummaryUsername)
      }
    }
    catch (error : any) {
      console.error('加载首页数据失败:', error)
      // 如果是前端逻辑错误（非 API 错误），需要手动显示提示
      const errorWithStatus = error as { statusCode?: number } | undefined
      if (error instanceof Error && error.message && !errorWithStatus?.statusCode) {
        uni.$u.toast(error.message)
      }
      // API 请求错误已由拦截器统一处理
    }
    finally {
      loading.value = false
    }
  }

  // 跳转页面
  function navigateTo(path : string) {
    uni.navigateTo({ url: path })
  }

  // 退出登录
  function logout() {
    uni.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 调用登出接口
            await logoutApi()
          }
          catch (error) {
            console.error('登出接口调用失败:', error)
          }
          finally {
            // 清除本地登录状态
            clearToken()
            uni.removeStorageSync('refresh_token')
            uni.removeStorageSync('user_info')

            // 跳转到登录页
            uni.reLaunch({
              url: '/pages/common/login/index',
            })
          }
        }
      },
    })
  }

  onMounted(() => {
    loadHomeData()
  })
</script>

<template>
  <view class="bg-[#fafafa] min-h-screen pb-safe">
    <!-- 加载中 -->
    <view v-if="loading" class="pt-20 center">
      <text class="text-14px text-[#999]">加载中...</text>
    </view>

    <!-- 实际内容 -->
    <view v-else>
      <!-- 顶部用户信息卡片 -->
      <view class="px-4 pt-4">
        <view class="bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)] px-4 py-4">
          <view class="flex items-center">
            <!-- 左侧头像 -->
            <view class="w-56px h-56px rounded-full bg-[#f5f5f5] center mr-4"
              @click="navigateTo('/pages/agent-system/user-info/index')">
              <text class="text-14px text-[#666] font-700">
                {{ userInfo?.user_type === 3 ? '代理' : '企业' }}
              </text>
            </view>

            <!-- 右侧用户信息 -->
            <view class="flex-1">
              <text class="text-18px font-700 text-[#212121] block mb-1">
                {{ userInfo?.username || '欢迎回来' }}
              </text>
              <text class="text-13px text-[#999]">
                {{ userInfo?.phone || '-' }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 代理端: 佣金展示 -->
      <view v-if="isAgent" class="px-4 pt-4">
        <AgentFundSummaryCard
          class="mb-3"
          :summary="commissionSummary"
          @click="navigateTo('/pages/agent-system/commission-center/index')"
        />

        <!-- 最近一天佣金 -->
        <view>
          <view class="flex items-center justify-between mb-3">
            <text class="text-16px font-700 text-[#212121]">最近一天佣金</text>
            <text class="text-13px text-[#999]" @click="navigateTo('/pages/agent-system/commission-center/index')">明细</text>
          </view>
          <view class="bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)] p-4">
            <view class="grid grid-cols-3 gap-3">
              <view class="text-center">
                <text class="text-12px text-[#999] block mb-1">日期</text>
                <text class="text-14px font-600 text-[#212121]">
                  {{ todayStat ? formatDate(todayStat.date) : '--' }}
                </text>
              </view>
              <view class="text-center">
                <text class="text-12px text-[#999] block mb-1">佣金金额</text>
                <text class="text-14px font-600 text-[#212121]">
                  {{ formatAmount(todayStat?.total_amount || 0) }}
                </text>
              </view>
              <view class="text-center">
                <text class="text-12px text-[#999] block mb-1">订单笔数</text>
                <text class="text-14px font-600 text-[#212121]">
                  {{ todayStat?.total_count || 0 }}
                </text>
              </view>
            </view>
            <view v-if="!todayStat" class="mt-3 pt-3 border-t border-[#f5f5f5] text-center">
              <text class="text-12px text-[#999]">最近一天暂无佣金数据</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 快捷功能区 -->
      <view class="px-4 pt-4">
        <text class="text-16px font-700 text-[#212121] block mb-3">快捷功能</text>

        <view class="grid grid-cols-3 gap-3 mb-3">
          <!-- 资产列表 -->
          <view class="bg-white rounded-16px p-3 flex flex-col items-center shadow-[0_2px_12px_rgba(0,0,0,0.06)] aspect-square" @click="navigateTo('/pages/agent-system/assets/index')">
            <image src="@/static/icons/资产列表.png" class="w-12 h-12 rounded-12px mb-2" mode="aspectFit" />
            <text class="text-13px font-500 text-[#212121]">资产列表</text>
          </view>

          <!-- 企业端: 授权卡列表 -->
          <view v-if="userInfo?.user_type === 4" class="bg-white rounded-16px p-3 flex flex-col items-center shadow-[0_2px_12px_rgba(0,0,0,0.06)] aspect-square" @click="navigateTo('/pages/agent-system/enterprise-cards/index')">
            <image src="@/static/icons/授权卡列表.png" class="w-12 h-12 rounded-12px mb-2" mode="aspectFit" />
            <text class="text-13px font-500 text-[#212121]">授权卡</text>
          </view>

          <!-- 企业端: 授权设备列表 -->
          <view v-if="userInfo?.user_type === 4" class="bg-white rounded-16px p-3 flex flex-col items-center shadow-[0_2px_12px_rgba(0,0,0,0.06)] aspect-square" @click="navigateTo('/pages/agent-system/enterprise-devices/index')">
            <image src="@/static/icons/授权设备列表.png" class="w-12 h-12 rounded-12px mb-2" mode="aspectFit" />
            <text class="text-13px font-500 text-[#212121]">授权设备</text>
          </view>

          <!-- 代理端: 佣金中心 -->
          <view v-if="userInfo?.user_type === 3" class="bg-white rounded-16px p-3 flex flex-col items-center shadow-[0_2px_12px_rgba(0,0,0,0.06)] aspect-square" @click="navigateTo('/pages/agent-system/commission-center/index')">
            <image src="@/static/icons/佣金中心.png" class="w-12 h-12 rounded-12px mb-2" mode="aspectFit" />
            <text class="text-13px font-500 text-[#212121]">佣金中心</text>
          </view>

          <!-- 代理端: 提现管理 -->
          <view v-if="userInfo?.user_type === 3" class="bg-white rounded-16px p-3 flex flex-col items-center shadow-[0_2px_12px_rgba(0,0,0,0.06)] aspect-square" @click="navigateTo('/pages/agent-system/withdraw/index')">
            <image src="@/static/icons/提现管理.png" class="w-12 h-12 rounded-12px mb-2" mode="aspectFit" />
            <text class="text-13px font-500 text-[#212121]">提现管理</text>
          </view>
        </view>
      </view>

      <!-- 设置区 -->
      <view class="px-4 pt-4 pb-6">
        <text class="text-16px font-700 text-[#212121] block mb-3">设置</text>

        <view class="bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)] overflow-hidden">
          <!-- 修改密码 -->
          <view class="flex items-center px-4 py-4 active:bg-[#f8fafc] transition-all duration-200" @click="navigateTo('/pages/agent-system/change-password/index')">
            <view class="w-40px h-40px rounded-12px bg-[#f0f5ff] flex items-center justify-center mr-3">
              <i class="i-mdi-lock-reset text-20px text-brand" />
            </view>
            <view class="flex-1">
              <text class="text-15px text-[#212121] font-500 block">修改密码</text>
              <text class="text-12px text-[#999] block mt-0.5">更新登录密码</text>
            </view>
            <i class="i-mdi-chevron-right text-20px text-[#cbd5e1]" />
          </view>

          <!-- 退出登录 -->
          <view class="flex items-center px-4 py-4 border-t border-[#f5f5f5] active:bg-[#f8fafc] transition-all duration-200" @click="logout">
            <view class="w-40px h-40px rounded-12px bg-[#fff2f0] flex items-center justify-center mr-3">
              <i class="i-mdi-logout text-20px text-[#ff4d4f]" />
            </view>
            <view class="flex-1">
              <text class="text-15px text-[#212121] font-500 block">退出登录</text>
              <text class="text-12px text-[#999] block mt-0.5">退出当前账号</text>
            </view>
            <i class="i-mdi-chevron-right text-20px text-[#cbd5e1]" />
          </view>
        </view>
      </view>
    </view>
  </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>
