<template>
  <view class="page-container">
    <NavBar title="首页" :showBack="false">
      <template #right>
        <view class="nav-btn" @click="handleLogout">
          <AppIcon name="log-out" :size="28" color="#666666" />
        </view>
      </template>
    </NavBar>

    <!-- 加载骨架 -->
    <view class="content" v-if="loading && !hasData">
      <view class="skeleton-greeting"></view>
      <view class="skeleton-hero">
        <view class="skeleton-line hero-num"></view>
        <view class="skeleton-line hero-sub"></view>
      </view>
      <view class="skeleton-line station-sk"></view>
      <view class="skeleton-grid">
        <view class="skeleton-cell"></view>
        <view class="skeleton-cell"></view>
        <view class="skeleton-cell sm"></view>
        <view class="skeleton-cell sm"></view>
      </view>
      <view class="skeleton-line section-title"></view>
      <view class="skeleton-actions">
        <view class="skeleton-action"></view>
        <view class="skeleton-action"></view>
        <view class="skeleton-action"></view>
      </view>
    </view>

    <!-- 错误态 -->
    <view class="content" v-else-if="error && !hasData">
      <view class="error-state">
        <AppIcon name="inbox" :size="48" color="#BFBFBF" />
        <text class="error-text">数据加载失败</text>
        <text class="error-hint">下拉页面或点击下方按钮重试</text>
        <view class="retry-btn" @click="refreshData">
          <text class="retry-btn-text">重新加载</text>
        </view>
      </view>
    </view>

    <!-- 正常内容 -->
    <view class="content" v-else>
      <!-- 问候语 -->
      <text class="greeting">{{ timeGreeting }}</text>

      <!-- Hero -->
      <view class="hero-section">
        <text class="hero-value">¥{{ formatAmount(todayRevenue) }}</text>
        <text class="hero-label">今日收入</text>
      </view>

      <!-- 站点栏 -->
      <picker
        v-if="stationList.length > 0"
        mode="selector"
        :range="stationList"
        range-key="stationName"
        :value="selectedStationIndex"
        @change="onStationChange"
      >
        <view class="station-card">
          <view class="station-card-row">
            <AppIcon name="building" :size="18" color="#C6171E" />
            <text class="station-card-name">{{ currentStation?.stationName || '选择站点' }}</text>
            <AppIcon name="chevron-down" :size="14" color="#999999" />
          </view>
          <text class="station-card-date">{{ todayDate }}</text>
        </view>
      </picker>

      <!-- 主指标：订单 + 洗车人数 -->
      <view class="metrics-primary">
        <view class="metric-card-lg">
          <text class="metric-lg-value">{{ todayOrders }}</text>
          <text class="metric-lg-label">今日订单</text>
        </view>
        <view class="metric-card-lg">
          <text class="metric-lg-value">{{ todayWashUsers }}</text>
          <text class="metric-lg-label">洗车人数</text>
        </view>
      </view>

      <!-- 主指标：消费总额 + 今日退款 -->
      <view class="metrics-primary">
        <view class="metric-card-lg">
          <text class="metric-lg-value">¥{{ formatAmount(todayConsumption) }}</text>
          <text class="metric-lg-label">消费总额</text>
        </view>
        <view class="metric-card-lg">
          <text class="metric-lg-value">¥{{ formatAmount(todayRefund) }}</text>
          <text class="metric-lg-label">今日退款</text>
        </view>
      </view>

      <!-- 次指标：均价 + 时长 -->
      <view class="metrics-secondary">
        <view class="metric-card-sm">
          <text class="metric-sm-value">¥{{ formatAmount(avgOrderPrice) }}</text>
          <text class="metric-sm-label">平均消费</text>
        </view>
        <view class="metric-card-sm">
          <text class="metric-sm-value">{{ avgDuration }} 分钟</text>
          <text class="metric-sm-label">平均时长</text>
        </view>
      </view>

      <!-- 快捷入口标题 -->
      <view class="section-header">
        <view class="section-dot"></view>
        <text class="section-title">快捷功能</text>
      </view>

      <!-- 快捷入口 -->
      <view class="actions-row">
        <view class="action-item" @click="navigateTo('/pages/order/list')">
          <view class="action-icon-wrap">
            <AppIcon name="clipboard" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">订单管理</text>
        </view>
        <view class="action-item" @click="navigateTo('/pages/device/list')">
          <view class="action-icon-wrap">
            <AppIcon name="monitor" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">设备监控</text>
        </view>
        <view class="action-item" @click="navigateTo('/pages/finance/index')">
          <view class="action-icon-wrap">
            <AppIcon name="dollar" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">财务管理</text>
        </view>
        <view class="action-item" @click="navigateTo('/pages/user/list')">
          <view class="action-icon-wrap">
            <AppIcon name="users" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">用户管理</text>
        </view>
        <view class="action-item" @click="navigateTo('/pages/statistics/index')">
          <view class="action-icon-wrap">
            <AppIcon name="bar-chart" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">数据统计</text>
        </view>
        <view class="action-item" @click="navigateTo('/pages/setting/device-config')">
          <view class="action-icon-wrap">
            <AppIcon name="settings" :size="26" color="#C6171E" />
          </view>
          <text class="action-label">设备配置</text>
        </view>
      </view>

      <!-- 底栏信息 -->
      <view class="info-bar">
        <view class="info-item">
          <AppIcon name="users" :size="16" color="#999999" />
          <text class="info-text">今日注册会员 <text class="info-num">{{ todayMembers }}</text> 人</text>
        </view>
        <view class="info-item">
          <AppIcon name="smartphone" :size="16" color="#999999" />
          <text class="info-text">在线设备 <text class="info-num">{{ onlineDevices }}</text>/<text class="info-num">{{ totalDevices }}</text></text>
        </view>
      </view>
    </view>

    <CustomTabBar :selected="0" />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import CustomTabBar from '../../components/CustomTabBar.vue'
import { logout } from '../../api/auth.js'
import { getDashboardData, getDeviceStatus } from '../../api/stat.js'
import { getStationList } from '../../api/station.js'
import { loadDicts } from '../../utils/dict.js'
import { storage, showToast, formatAmount } from '../../utils/index.js'

const userInfo = ref(storage.get('userInfo'))
const loading = ref(false)
const error = ref(false)
const hasData = ref(false)

const stationList = ref([])
const currentStation = ref(null)
const selectedStationIndex = ref(0)

const todayRevenue = ref(0)
const todayOrders = ref(0)
const todayWashUsers = ref(0)
const todayConsumption = ref(0)
const todayRefund = ref(0)
const avgOrderPrice = ref(0)
const avgDuration = ref(0)
const todayMembers = ref(0)
const totalDevices = ref(0)
const onlineDevices = ref(0)

const todayDate = computed(() => {
  const d = new Date()
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
})

const timeGreeting = computed(() => {
  const h = new Date().getHours()
  if (h < 6) return '夜深了'
  if (h < 9) return '早上好'
  if (h < 12) return '上午好'
  if (h < 14) return '中午好'
  if (h < 18) return '下午好'
  return '晚上好'
})

onMounted(async () => {
  await Promise.all([loadStationList(), loadDictionaries()])
})

const loadStationList = async () => {
  try {
    const res = await getStationList({ pageNum: 1, pageSize: 1024 })
    if (res && res.code === 200 && res.data && res.data.list) {
      stationList.value = res.data.list
      if (stationList.value.length > 0) {
        currentStation.value = stationList.value[0]
        selectedStationIndex.value = 0
        storage.set('currentStationId', currentStation.value.stationId)
        await loadData(currentStation.value.stationId)
      }
    } else {
      error.value = true
    }
  } catch (e) {
    console.error('加载站点列表失败:', e)
    error.value = true
  }
}

const loadDictionaries = async () => {
  await loadDicts()
}

const onStationChange = async (e) => {
  const index = e.detail.value
  selectedStationIndex.value = index
  currentStation.value = stationList.value[index]
  storage.set('currentStationId', currentStation.value.stationId)

  await loadData(currentStation.value.stationId)
  showToast(`已切换至${currentStation.value.stationName}`, 'success')
}

const loadData = async (stationId) => {
  if (!stationId) return
  error.value = false
  if (!hasData.value) loading.value = true

  try {
    const [dashboardRes, deviceRes] = await Promise.all([
      getDashboardData(stationId).catch(err => { console.error('获取仪表盘数据失败:', err); return null }),
      getDeviceStatus(stationId).catch(err => { console.error('获取设备状态失败:', err); return null })
    ])

    if (!dashboardRes && !deviceRes) { error.value = true; return }

    if (dashboardRes && dashboardRes.code === 200) {
      const data = dashboardRes.data
      todayRevenue.value = data.todayIncome || 0
      todayOrders.value = data.todayWashOrders || 0
      todayWashUsers.value = data.todayWashUsers || 0
      todayConsumption.value = data.todayConsumptionAmount || 0
      todayRefund.value = data.todayRefundAmount || 0
      avgOrderPrice.value = data.avgOrderPrice || 0
      avgDuration.value = Math.round((data.avgOrderDuration || 0) / 60 * 10) / 10
      todayMembers.value = data.todayRegisteredMembers || 0
    }

    if (deviceRes && deviceRes.code === 200) {
      const deviceData = deviceRes.data
      totalDevices.value = Object.values(deviceData).reduce((sum, count) => sum + count, 0)
      onlineDevices.value = totalDevices.value
    }
    hasData.value = true
  } catch (e) {
    console.error('加载首页数据失败:', e)
    if (!hasData.value) error.value = true
  } finally {
    loading.value = false
  }
}

const refreshData = async () => {
  if (currentStation.value) await loadData(currentStation.value.stationId)
}

const navigateTo = (url) => {

  let fullUrl = url
  if (!fullUrl.startsWith('/')) fullUrl = `/${fullUrl}`
  const tabBarPages = ['/pages/index/index', '/pages/order/list', '/pages/device/list', '/pages/finance/index']
  if (tabBarPages.includes(fullUrl)) {
    uni.switchTab({ url: fullUrl, fail: (err) => { console.error('switchTab失败:', err); showToast('页面跳转失败') } })
  } else {
    uni.navigateTo({ url: fullUrl, fail: (err) => { console.error('navigateTo失败:', err); showToast('页面跳转失败') } })
  }
}

const handleLogout = async () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try { await logout() } catch (e) { console.error('登出接口调用失败:', e) }
        storage.remove('token')
        storage.remove('userInfo')
        storage.remove('currentStationId')
        showToast('已退出登录', 'success')
        setTimeout(() => { uni.reLaunch({ url: '/pages/login/login' }) }, 500)
      }
    }
  })
}

onPullDownRefresh(async () => {
  await refreshData()
  uni.stopPullDownRefresh()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: #F5F7FA;
  padding-bottom: 120rpx;
}

.nav-btn {
  width: 56rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.25s;
}
.nav-btn:active { background: rgba(255, 255, 255, 0.2); }

/* ===== Content ===== */
.content { padding: 0 28rpx; }

/* ===== Greeting ===== */
.greeting {
  display: block;
  text-align: center;
  font-size: 30rpx;
  font-weight: 500;
  color: #666666;
  padding: 32rpx 0 32rpx;
}

/* ===== Hero ===== */
.hero-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 0 44rpx;
}
.hero-value {
  font-size: 64rpx;
  font-weight: 700;
  color: #1A1A1A;
  line-height: 1;
  letter-spacing: -1px;
}
.hero-label {
  font-size: 24rpx;
  color: #999999;
  margin-top: 18rpx;
  letter-spacing: 1px;
}

/* ===== Station Card ===== */
.station-card {
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 24rpx;
}
.station-card:active { background: #F5F7FA; }
.station-card-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}
.station-card-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
}
.station-card-date {
  font-size: 22rpx;
  color: #999999;
}

/* ===== Primary Metrics ===== */
.metrics-primary {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}
.metric-card-lg {
  flex: 1;
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  transition: box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1), transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
.metric-card-lg:active {
  transform: translateY(-2rpx);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.06);
}
.metric-lg-value {
  font-size: 38rpx;
  font-weight: 700;
  color: #1A1A1A;
  line-height: 1.2;
}
.metric-lg-label {
  font-size: 24rpx;
  color: #999999;
}

/* ===== Secondary Metrics ===== */
.metrics-secondary {
  display: flex;
  gap: 16rpx;
  margin-bottom: 40rpx;
}
.metric-card-sm {
  flex: 1;
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 28rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
  transition: box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1), transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
.metric-card-sm:active {
  transform: translateY(-2rpx);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.06);
}
.metric-sm-value {
  font-size: 38rpx;
  font-weight: 700;
  color: #1A1A1A;
  line-height: 1.2;
}
.metric-sm-label {
  font-size: 24rpx;
  color: #999999;
}

/* ===== Section Header ===== */
.section-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 0 0 20rpx;
}
.section-dot {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  background: #C6171E;
  flex-shrink: 0;
}
.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* ===== Quick Actions ===== */
.actions-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 28rpx;
}
.action-item {
  flex: 0 0 calc(33.333% - 11rpx);
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx 12rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 18rpx;
  box-sizing: border-box;
}
.action-icon-wrap {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  background: #FFF0F0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.action-item:active .action-icon-wrap {
  transform: scale(0.94);
}
.action-label {
  font-size: 26rpx;
  font-weight: 500;
  color: #1A1A1A;
}

/* ===== Info Bar ===== */
.info-bar {
  display: flex;
  justify-content: center;
  gap: 40rpx;
  padding: 16rpx 0 40rpx;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.info-text {
  font-size: 24rpx;
  color: #999999;
}
.info-num {
  font-weight: 600;
  color: #666666;
}

/* ===== Skeleton ===== */
.skeleton-greeting {
  width: 180rpx;
  height: 30rpx;
  background: #E8E8E8;
  border-radius: 8rpx;
  margin: 32rpx auto;
}
.skeleton-hero {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 0 44rpx;
}
.skeleton-line {
  background: #E8E8E8;
  border-radius: 8rpx;
}
.skeleton-line.hero-num {
  width: 360rpx;
  height: 64rpx;
  margin-bottom: 16rpx;
}
.skeleton-line.hero-sub {
  width: 160rpx;
  height: 26rpx;
}
.skeleton-line.station-sk {
  width: 100%;
  height: 90rpx;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
}
.skeleton-line.section-title {
  width: 160rpx;
  height: 28rpx;
  margin: 0 auto 20rpx;
}
.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  margin-bottom: 16rpx;
}
.skeleton-cell {
  height: 120rpx;
  background: #E8E8E8;
  border-radius: 24rpx;
}
.skeleton-cell.sm {
  height: 100rpx;
  border-radius: 20rpx;
}
.skeleton-actions {
  display: flex;
  gap: 16rpx;
  margin-bottom: 28rpx;
}
.skeleton-action {
  flex: 1;
  height: 170rpx;
  background: #E8E8E8;
  border-radius: 24rpx;
}

/* ===== Error ===== */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0 0;
}
.error-text { font-size: 28rpx; color: #999999; margin-top: 24rpx; }
.error-hint { font-size: 24rpx; color: #B0B0B0; margin-top: 8rpx; }
.retry-btn {
  margin-top: 40rpx;
  background: #C6171E;
  padding: 16rpx 48rpx;
  border-radius: 44rpx;
}
.retry-btn:active { background: #A81212; transform: scale(0.97); }
.retry-btn-text { font-size: 28rpx; color: #FFFFFF; font-weight: 500; }
</style>
