<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElCard, ElRow, ElCol, ElStatistic, ElDatePicker, ElDivider } from 'element-plus'
import axios from 'axios'
import * as echarts from 'echarts'
import { Calendar, TrendCharts, DataAnalysis, Shop } from '@element-plus/icons-vue'

// API基础路径
const baseURL = 'http://localhost:8080'

// 定义接口类型
interface DailyRevenue {
  date: string
  revenue: number
  orderCount: number
}

interface StoreStatistics {
  branchId: number
  branchName: string
  dailyRevenues: DailyRevenue[]
  totalRevenue: number
  averageRating: number
  totalComments: number
}

interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

// 获取本地存储的accountId
const getAccountId = (): number | null => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      return userInfo.accountId || null
    } catch (e) {
      return null
    }
  }
  return null
}

// 响应式数据
const loading = ref(false)
const branchId = ref<number>(2) // TODO: 这里需要根据实际情况获取分店ID
const statistics = ref<StoreStatistics | null>(null)
const dateRange = ref<Date[]>([])
const revenueChart = ref<HTMLElement>()

// 默认显示最近7天
const defaultDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 6)
  return [start, end]
}

// 计算属性
const totalOrderCount = computed(() => {
  if (!statistics.value) return 0
  return statistics.value.dailyRevenues.reduce((sum, item) => sum + item.orderCount, 0)
})

const averageOrderValue = computed(() => {
  if (!statistics.value || totalOrderCount.value === 0) return 0
  return (statistics.value.totalRevenue / totalOrderCount.value).toFixed(2)
})

// 获取店铺统计数据
const fetchStoreStatistics = async () => {
  loading.value = true
  try {
    const accountId = getAccountId()
    if (!accountId) {
      ElMessage.error('请先登录')
      return
    }

    const response = await axios.get<ApiResponse<StoreStatistics>>(
      `${baseURL}/branch/statistics/store/${branchId.value}`,
      {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
        }
      }
    )

    if (response.data.code === 200) {
      statistics.value = response.data.data
      // 更新图表
      updateChart()
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateChart = () => {
  if (!statistics.value || !revenueChart.value) return

  const myChart = echarts.init(revenueChart.value)
  
  const dates = statistics.value.dailyRevenues.map(item => {
    const date = new Date(item.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  const revenues = statistics.value.dailyRevenues.map(item => item.revenue)
  const orderCounts = statistics.value.dailyRevenues.map(item => item.orderCount)

  const option = {
    title: {
      text: '营业数据趋势',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: '600',
        color: '#2563eb'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#2563eb'
        }
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e5e7eb',
      borderWidth: 1,
      borderRadius: 12,
      textStyle: {
        color: '#374151'
      }
    },
    legend: {
      data: ['营业额', '订单数'],
      top: 35,
      itemGap: 20,
      textStyle: {
        color: '#6b7280',
        fontSize: 14
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 80,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#9ca3af'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '营业额(元)',
        position: 'left',
        axisLabel: {
          formatter: '¥{value}',
          color: '#9ca3af'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#f3f4f6',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
        axisLabel: {
          color: '#9ca3af'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '营业额',
        type: 'line',
        smooth: true,
        data: revenues,
        itemStyle: {
          color: '#2563eb'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(37, 99, 235, 0.3)' },
            { offset: 1, color: 'rgba(37, 99, 235, 0)' }
          ])
        }
      },
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: orderCounts,
        itemStyle: {
          color: '#1d4ed8'
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  }

  myChart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 日期范围变化处理
const handleDateChange = (value: Date[]) => {
  if (value && value.length === 2) {
    // TODO: 根据日期范围重新请求数据
    fetchStoreStatistics()
  }
}

// 页面加载时初始化
onMounted(() => {
  dateRange.value = defaultDateRange()
  fetchStoreStatistics()
})
</script>

<template>
  <div class="dashboard-container" v-loading="loading">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">商户主页</h1>
        <p class="page-subtitle">实时监控您的业务数据和运营状况</p>
      </div>
      <div class="header-extra">
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stat-cards">
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="never" class="stat-card revenue-card">
          <el-statistic :value="statistics?.totalRevenue || 0" :precision="2">
            <template #title>
              <div class="stat-title">
                <div class="stat-icon revenue-icon">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <span>总营业额</span>
              </div>
            </template>
            <template #prefix>¥</template>
          </el-statistic>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="never" class="stat-card orders-card">
          <el-statistic :value="totalOrderCount">
            <template #title>
              <div class="stat-title">
                <div class="stat-icon orders-icon">
                  <el-icon><Calendar /></el-icon>
                </div>
                <span>总订单数</span>
              </div>
            </template>
            <template #suffix>单</template>
          </el-statistic>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="never" class="stat-card rating-card">
          <el-statistic :value="statistics?.averageRating || 0" :precision="1">
            <template #title>
              <div class="stat-title">
                <div class="stat-icon rating-icon">
                  <el-icon><DataAnalysis /></el-icon>
                </div>
                <span>平均评分</span>
              </div>
            </template>
            <template #suffix>分</template>
          </el-statistic>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="never" class="stat-card value-card">
          <el-statistic :value="Number(averageOrderValue)">
            <template #title>
              <div class="stat-title">
                <div class="stat-icon value-icon">
                  <el-icon><Shop /></el-icon>
                </div>
                <span>客单价</span>
              </div>
            </template>
            <template #prefix>¥</template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 店铺信息 -->
    <el-card class="store-info modern-card" shadow="never" v-if="statistics">
      <template #header>
        <div class="card-header">
          <div class="header-icon">
            <el-icon><Shop /></el-icon>
          </div>
          <span>店铺信息</span>
        </div>
      </template>
      <div class="info-content">
        <div class="info-item">
          <span class="label">店铺名称</span>
          <span class="value">{{ statistics.branchName }}</span>
        </div>
        <div class="info-item">
          <span class="label">评论总数</span>
          <span class="value">{{ statistics.totalComments }} 条</span>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <el-card class="chart-container modern-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <span>数据趋势</span>
        </div>
      </template>
      <div ref="revenueChart" class="revenue-chart"></div>
    </el-card>
  </div>
</template>

<style scoped>
/* 全局容器样式 - 改为白色背景 */
.dashboard-container {
  padding: 32px;
  background: #ffffff;
  min-height: 100vh;
  position: relative;
}

.dashboard-container::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 50%, rgba(37, 99, 235, 0.03) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(37, 99, 235, 0.02) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(37, 99, 235, 0.015) 0%, transparent 50%);
  pointer-events: none;
  z-index: -1;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  position: relative;
  z-index: 1;
  padding: 24px;
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  border-radius: 20px;
  color: white;
  box-shadow: 0 8px 32px rgba(37, 99, 235, 0.15);
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  color: white;
  letter-spacing: -0.5px;
}

.page-subtitle {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  font-weight: 400;
}

.header-extra {
  margin-left: 24px;
}

/* 现代化日期选择器 */
.modern-date-picker :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.modern-date-picker :deep(.el-input__wrapper):hover {
  background: rgba(255, 255, 255, 1);
  border-color: rgba(255, 255, 255, 0.4);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

/* 统计卡片网格 */
.stat-cards {
  margin-bottom: 32px;
}

/* 统计卡片样式 */
.stat-card {
  height: 100%;
  border: 1px solid #e5e7eb;
  border-radius: 16px;
  background: white;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #2563eb, #1d4ed8);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(37, 99, 235, 0.15);
  border-color: #2563eb;
}

.stat-card:hover::before {
  height: 6px;
}

/* 不同卡片的蓝色渐变 */
.revenue-card::before {
  background: linear-gradient(90deg, #2563eb, #3b82f6);
}

.orders-card::before {
  background: linear-gradient(90deg, #1d4ed8, #2563eb);
}

.rating-card::before {
  background: linear-gradient(90deg, #1e40af, #1d4ed8);
}

.value-card::before {
  background: linear-gradient(90deg, #1e3a8a, #1e40af);
}

/* 统计标题样式 */
.stat-title {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  transition: all 0.3s ease;
}

.revenue-icon {
  background: linear-gradient(135deg, #2563eb, #3b82f6);
}

.orders-icon {
  background: linear-gradient(135deg, #1d4ed8, #2563eb);
}

.rating-icon {
  background: linear-gradient(135deg, #1e40af, #1d4ed8);
}

.value-icon {
  background: linear-gradient(135deg, #1e3a8a, #1e40af);
}

/* 现代化卡片样式 */
.modern-card {
  border: 1px solid #e5e7eb;
  border-radius: 16px;
  background: white;
  transition: all 0.3s ease;
  margin-bottom: 24px;
}

.modern-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(37, 99, 235, 0.1);
  border-color: #2563eb;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.header-icon {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

/* 店铺信息内容 */
.info-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.info-item:hover {
  background: #ffffff;
  border-color: #2563eb;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(37, 99, 235, 0.1);
}

.info-item .label {
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

.info-item .value {
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

/* 图表容器 */
.chart-container {
  margin-top: 24px;
}

.revenue-chart {
  width: 100%;
  height: 450px;
  border-radius: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 20px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 20px;
    padding: 20px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .header-extra {
    margin-left: 0;
  }
  
  .header-extra :deep(.el-date-editor) {
    width: 100%;
  }
  
  .info-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .revenue-chart {
    height: 320px;
  }
  
  .stat-card:hover {
    transform: translateY(-2px);
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-statistic__content) {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  background: #f8fafc;
}

/* 加载状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>