<template>
  <div class="mobile-statistics">
    <!-- 顶部统计卡片 -->
    <div class="mobile-summary">
      <div class="mobile-summary__item">
        <div class="mobile-summary__val" v-loading="loading">¥{{ formatPrice(summary?.todayPrice) }}</div>
        <div class="mobile-summary__label">今日采购</div>
      </div>
      <div class="mobile-summary__item">
        <div class="mobile-summary__val" v-loading="loading">¥{{ formatPrice(summary?.yesterdayPrice) }}</div>
        <div class="mobile-summary__label">昨日采购</div>
      </div>
      <div class="mobile-summary__item">
        <div class="mobile-summary__val" v-loading="loading">¥{{ formatPrice(summary?.monthPrice) }}</div>
        <div class="mobile-summary__label">本月采购</div>
      </div>
      <div class="mobile-summary__item">
        <div class="mobile-summary__val" v-loading="loading">¥{{ formatPrice(summary?.yearPrice) }}</div>
        <div class="mobile-summary__label">今年采购</div>
      </div>
    </div>

    <!-- 趋势图区域 -->
    <div class="mobile-section">
      <div class="mobile-section__header">
        <span class="mobile-section__title">采购趋势</span>
        <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
          <el-radio-button label="week">按周</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <Echart :height="280" :options="trendChartOptions" :loading="trendLoading" />
      <div class="mobile-section__actions">
        <el-button size="small" type="primary" plain @click="showTrendInfo">数据分析</el-button>
        <el-button size="small" type="warning" plain @click="analyzeWithAI" :loading="aiAnalysisLoading">AI分析</el-button>
      </div>
    </div>

    <!-- 产品采购排行 -->
    <div class="mobile-section">
      <div class="mobile-section__header">
        <span class="mobile-section__title">产品采购排行</span>
      </div>
      <div class="mobile-section__date">
        <el-date-picker v-model="productRankDateRange" type="daterange" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" size="small" style="width:100%" @change="handleProductRankDateChange" />
      </div>
      <div class="mobile-rank-list" v-loading="productRankLoading">
        <div v-for="(item, index) in productRankList" :key="index" class="mobile-rank-item">
          <div class="mobile-rank-item__index">
            <el-tag v-if="index < 3" :type="index === 0 ? 'danger' : index === 1 ? 'warning' : 'success'" size="small">{{ index + 1 }}</el-tag>
            <span v-else class="mobile-rank-item__num">{{ index + 1 }}</span>
          </div>
          <div class="mobile-rank-item__name">{{ item.productName }}</div>
          <div class="mobile-rank-item__data">
            <div class="mobile-rank-item__price">¥{{ formatPrice(item.price) }}</div>
            <div class="mobile-rank-item__count">{{ formatCount(item.count) }}</div>
          </div>
        </div>
        <el-empty v-if="productRankList.length === 0 && !productRankLoading" description="暂无数据" :image-size="60" />
      </div>
    </div>

    <!-- 供应商采购排行 -->
    <div class="mobile-section">
      <div class="mobile-section__header">
        <span class="mobile-section__title">供应商采购排行</span>
      </div>
      <div class="mobile-section__date">
        <el-date-picker v-model="supplierRankDateRange" type="daterange" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" size="small" style="width:100%" @change="handleSupplierRankDateChange" />
      </div>
      <div class="mobile-rank-list" v-loading="supplierRankLoading">
        <div v-for="(item, index) in supplierRankList" :key="index" class="mobile-rank-item">
          <div class="mobile-rank-item__index">
            <el-tag v-if="index < 3" :type="index === 0 ? 'danger' : index === 1 ? 'warning' : 'success'" size="small">{{ index + 1 }}</el-tag>
            <span v-else class="mobile-rank-item__num">{{ index + 1 }}</span>
          </div>
          <div class="mobile-rank-item__name">{{ item.supplierName }}</div>
          <div class="mobile-rank-item__data">
            <div class="mobile-rank-item__price">¥{{ formatPrice(item.price) }}</div>
            <div class="mobile-rank-item__count">{{ formatCount(item.count) }}</div>
          </div>
        </div>
        <el-empty v-if="supplierRankList.length === 0 && !supplierRankLoading" description="暂无数据" :image-size="60" />
      </div>
    </div>

    <!-- 统计说明弹窗 -->
    <el-dialog v-model="trendInfoVisible" title="数据分析" width="95%" fullscreen>
      <div class="trend-info-content">
        <h4>当前统计周期</h4>
        <div class="analysis-card">
          <p><strong>统计方式：</strong>{{ trendType === 'week' ? '按周统计' : '按月统计' }}</p>
          <p><strong>统计范围：</strong>最近 {{ trendList.length }} 个{{ trendType === 'week' ? '周' : '月' }}</p>
          <p v-if="trendList.length > 0"><strong>时间跨度：</strong>{{ trendList[0]?.time }} 至 {{ trendList[trendList.length - 1]?.time }}</p>
        </div>
        <h4>金额统计</h4>
        <div class="analysis-card">
          <div class="stat-grid">
            <div class="stat-item"><span class="stat-label">总采购金额</span><span class="stat-value">¥{{ formatPrice(trendAnalysis.totalPrice) }}</span></div>
            <div class="stat-item"><span class="stat-label">平均金额</span><span class="stat-value">¥{{ formatPrice(trendAnalysis.avgPrice) }}</span></div>
            <div class="stat-item"><span class="stat-label">最高</span><span class="stat-value text-danger">¥{{ formatPrice(trendAnalysis.maxPrice) }}</span></div>
            <div class="stat-item"><span class="stat-label">最低</span><span class="stat-value text-success">¥{{ formatPrice(trendAnalysis.minPrice) }}</span></div>
          </div>
        </div>
        <h4>数量统计</h4>
        <div class="analysis-card">
          <div class="stat-grid">
            <div class="stat-item"><span class="stat-label">总采购数量</span><span class="stat-value">{{ formatCount(trendAnalysis.totalCount) }}</span></div>
            <div class="stat-item"><span class="stat-label">平均数量</span><span class="stat-value">{{ formatCount(trendAnalysis.avgCount) }}</span></div>
            <div class="stat-item"><span class="stat-label">最高</span><span class="stat-value text-danger">{{ formatCount(trendAnalysis.maxCount) }}</span></div>
            <div class="stat-item"><span class="stat-label">最低</span><span class="stat-value text-success">{{ formatCount(trendAnalysis.minCount) }}</span></div>
          </div>
        </div>
        <h4>数据特征</h4>
        <div class="analysis-card">
          <div class="feature-list">
            <div class="feature-item" v-if="trendAnalysis.priceTrend !== 0">
              金额趋势：
              <el-tag :type="trendAnalysis.priceTrend > 0 ? 'danger' : 'success'" size="small">{{ trendAnalysis.priceTrend > 0 ? '↑ 上升' : '↓ 下降' }}</el-tag>
              {{ Math.abs(trendAnalysis.priceTrendPercent).toFixed(1) }}%
            </div>
            <div class="feature-item" v-else>金额趋势：<el-tag type="info" size="small">→ 平稳</el-tag></div>
            <div class="feature-item" v-if="trendAnalysis.countTrend !== 0">
              数量趋势：
              <el-tag :type="trendAnalysis.countTrend > 0 ? 'danger' : 'success'" size="small">{{ trendAnalysis.countTrend > 0 ? '↑ 上升' : '↓ 下降' }}</el-tag>
              {{ Math.abs(trendAnalysis.countTrendPercent).toFixed(1) }}%
            </div>
            <div class="feature-item" v-else>数量趋势：<el-tag type="info" size="small">→ 平稳</el-tag></div>
            <div class="feature-item">高峰期：{{ trendAnalysis.peakTime || '暂无数据' }}</div>
            <div class="feature-item">低谷期：{{ trendAnalysis.valleyTime || '暂无数据' }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="trendInfoVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- AI分析结果弹窗 -->
    <el-dialog v-model="showAIAnalysisDialog" title="AI采购数据分析报告" width="95%" fullscreen>
      <div class="ai-analysis-content">
        <div v-html="formatAnalysisText(aiAnalysisResult)"></div>
      </div>
      <template #footer>
        <el-button @click="showAIAnalysisDialog = false">关闭</el-button>
        <el-button type="primary" @click="copyAnalysisResult">复制结果</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { EChartsOption } from 'echarts'
import {
  ErpPurchaseSummaryRespVO,
  ErpPurchaseTrendRespVO,
  ErpPurchaseProductRankRespVO,
  ErpPurchaseSupplierRankRespVO,
  PurchaseStatisticsApi
} from '@/api/erp/statistics/purchase'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'ErpPurchaseStatistics' })

// 加载状态
const loading = ref(true)
const trendLoading = ref(true)
const productRankLoading = ref(true)
const supplierRankLoading = ref(true)

// 统计数据
const summary = ref<ErpPurchaseSummaryRespVO>()
const trendList = ref<ErpPurchaseTrendRespVO[]>([])
const productRankList = ref<ErpPurchaseProductRankRespVO[]>([])
const supplierRankList = ref<ErpPurchaseSupplierRankRespVO[]>([])

// 趋势类型
const trendType = ref<'week' | 'month'>('month')

// 统计说明弹窗
const trendInfoVisible = ref(false)

// AI分析相关
const aiAnalysisLoading = ref(false)
const aiAnalysisResult = ref('')
const showAIAnalysisDialog = ref(false)

const message = useMessage() // 消息弹窗

// 趋势数据分析（计算属性）
const trendAnalysis = computed(() => {
  const data = trendList.value
  if (!data || data.length === 0) {
    return {
      totalPrice: 0,
      avgPrice: 0,
      maxPrice: 0,
      minPrice: 0,
      totalCount: 0,
      avgCount: 0,
      maxCount: 0,
      minCount: 0,
      priceTrend: 0,
      priceTrendPercent: 0,
      countTrend: 0,
      countTrendPercent: 0,
      peakTime: '',
      valleyTime: ''
    }
  }
  
  // 金额统计
  const prices = data.map(item => item.price || 0)
  const totalPrice = prices.reduce((sum, p) => sum + p, 0)
  const avgPrice = totalPrice / prices.length
  const maxPrice = Math.max(...prices)
  const minPrice = Math.min(...prices)
  
  // 数量统计
  const counts = data.map(item => item.count || 0)
  const totalCount = counts.reduce((sum, c) => sum + c, 0)
  const avgCount = totalCount / counts.length
  const maxCount = Math.max(...counts)
  const minCount = Math.min(...counts)
  
  // 趋势分析（前半段 vs 后半段）
  const midIndex = Math.floor(data.length / 2)
  const firstHalfPrice = prices.slice(0, midIndex).reduce((sum, p) => sum + p, 0) / midIndex
  const secondHalfPrice = prices.slice(midIndex).reduce((sum, p) => sum + p, 0) / (data.length - midIndex)
  const priceTrend = secondHalfPrice - firstHalfPrice
  const priceTrendPercent = firstHalfPrice > 0 ? ((secondHalfPrice - firstHalfPrice) / firstHalfPrice) * 100 : 0
  
  const firstHalfCount = counts.slice(0, midIndex).reduce((sum, c) => sum + c, 0) / midIndex
  const secondHalfCount = counts.slice(midIndex).reduce((sum, c) => sum + c, 0) / (data.length - midIndex)
  const countTrend = secondHalfCount - firstHalfCount
  const countTrendPercent = firstHalfCount > 0 ? ((secondHalfCount - firstHalfCount) / firstHalfCount) * 100 : 0
  
  // 高峰期和低谷期
  const maxPriceIndex = prices.indexOf(maxPrice)
  const minPriceIndex = prices.indexOf(minPrice)
  const peakTime = data[maxPriceIndex]?.time || ''
  const valleyTime = data[minPriceIndex]?.time || ''
  
  return {
    totalPrice,
    avgPrice,
    maxPrice,
    minPrice,
    totalCount,
    avgCount,
    maxCount,
    minCount,
    priceTrend,
    priceTrendPercent,
    countTrend,
    countTrendPercent,
    peakTime,
    valleyTime
  }
})

// 日期范围
const getDefaultDateRange = () => {
  const now = new Date()
  const endTime = formatDate(now, 'YYYY-MM-DD') + ' 23:59:59'
  const startTime = formatDate(new Date(now.getFullYear(), 0, 1), 'YYYY-MM-DD') + ' 00:00:00'
  return [startTime, endTime]
}

const productRankDateRange = ref<string[]>(getDefaultDateRange())
const supplierRankDateRange = ref<string[]>(getDefaultDateRange())

// 趋势图配置
const trendChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: (params: any) => {
      if (!Array.isArray(params)) return ''
      let result = `<div style="font-weight:bold;margin-bottom:8px">${params[0].axisValue}</div>`
      params.forEach((item: any) => {
        const value = item.seriesName === '采购金额' 
          ? `￥${(item.value || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}` 
          : (item.value || 0).toFixed(2)
        result += `<div style="display:flex;justify-content:space-between;min-width:160px">
          <span>${item.marker}${item.seriesName}</span>
          <span style="font-weight:bold;margin-left:20px">${value}</span>
        </div>`
      })
      return result
    }
  },
  legend: {
    data: ['采购金额', '采购数量'],
    top: 10
  },
  grid: {
    left: 80,
    right: 40,
    bottom: 80,
    top: 60
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45,
      interval: 0,
      fontSize: 11
    },
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    name: '采购金额/数量',
    axisLabel: {
      formatter: (value: number) => {
        if (value >= 10000) {
          return (value / 10000).toFixed(1) + '万'
        }
        return value.toString()
      }
    },
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: [
    {
      name: '采购金额',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      barMaxWidth: 40
    },
    {
      name: '采购数量',
      type: 'line',
      data: [],
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      itemStyle: {
        color: '#67C23A'
      },
      lineStyle: {
        width: 2
      }
    }
  ]
}) as EChartsOption

// 格式化金额
const formatPrice = (price: number) => {
  return (price || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 格式化数量
const formatCount = (count: number) => {
  return (count || 0).toFixed(2)
}

// 获取统计概况
const getSummary = async () => {
  loading.value = true
  try {
    summary.value = await PurchaseStatisticsApi.getPurchaseSummary()
  } finally {
    loading.value = false
  }
}

// 获取趋势数据
const getTrendData = async () => {
  trendLoading.value = true
  try {
    if (trendType.value === 'week') {
      trendList.value = await PurchaseStatisticsApi.getPurchaseTrendByWeek(12)
    } else {
      trendList.value = await PurchaseStatisticsApi.getPurchaseTrendByMonth(12)
    }
    updateTrendChart()
  } finally {
    trendLoading.value = false
  }
}

// 更新趋势图
const updateTrendChart = () => {
  const xAxisData = trendList.value.map(item => item.time)
  const priceData = trendList.value.map(item => item.price)
  const countData = trendList.value.map(item => item.count)
  
  if (trendChartOptions.xAxis && !Array.isArray(trendChartOptions.xAxis)) {
    (trendChartOptions.xAxis as any).data = xAxisData
  }
  if (trendChartOptions.series && Array.isArray(trendChartOptions.series)) {
    (trendChartOptions.series[0] as any).data = priceData;
    (trendChartOptions.series[1] as any).data = countData
  }
}

// 获取产品排行
const getProductRank = async () => {
  if (!productRankDateRange.value || productRankDateRange.value.length !== 2) return
  productRankLoading.value = true
  try {
    productRankList.value = await PurchaseStatisticsApi.getPurchaseProductRank(
      productRankDateRange.value[0],
      productRankDateRange.value[1],
      10
    )
  } finally {
    productRankLoading.value = false
  }
}

// 获取供应商排行
const getSupplierRank = async () => {
  if (!supplierRankDateRange.value || supplierRankDateRange.value.length !== 2) return
  supplierRankLoading.value = true
  try {
    supplierRankList.value = await PurchaseStatisticsApi.getPurchaseSupplierRank(
      supplierRankDateRange.value[0],
      supplierRankDateRange.value[1],
      10
    )
  } finally {
    supplierRankLoading.value = false
  }
}

// 趋势类型切换
const handleTrendTypeChange = () => {
  getTrendData()
}

// 产品排行日期变化
const handleProductRankDateChange = () => {
  getProductRank()
}

// 供应商排行日期变化
const handleSupplierRankDateChange = () => {
  getSupplierRank()
}

// 显示统计说明
const showTrendInfo = () => {
  trendInfoVisible.value = true
}

// AI分析功能
const analyzeWithAI = async () => {
  aiAnalysisLoading.value = true
  try {
    // 准备分析数据
    const analysisData = {
      summary: summary.value,
      trendData: trendList.value,
      trendAnalysis: trendAnalysis.value,
      productRankList: productRankList.value,
      supplierRankList: supplierRankList.value,
      trendType: trendType.value
    }

    // 尝试调用AI分析API
    try {
      // 调用实际的AI分析API (DeepSeek)
      const aiResult = await PurchaseStatisticsApi.analyzeWithAI(analysisData)
      aiAnalysisResult.value = aiResult.data || aiResult
    } catch (aiError) {
      console.warn('AI分析失败，使用文字统计:', aiError)
      // 生成文字统计分析作为fallback
      aiAnalysisResult.value = generatePurchaseStatisticsAnalysis(analysisData)
    }

    showAIAnalysisDialog.value = true
  } catch (error) {
    console.error('分析失败:', error)
    message.error('分析失败，请稍后重试')
  } finally {
    aiAnalysisLoading.value = false
  }
}

// 格式化分析文本为HTML
const formatAnalysisText = (text) => {
  return text
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/^### (.*$)/gm, '<h3 style="color: #409eff; margin: 16px 0 8px 0;">$1</h3>')
    .replace(/^## (.*$)/gm, '<h2 style="color: #303133; margin: 20px 0 12px 0;">$1</h2>')
    .replace(/^- (.*$)/gm, '<div style="margin: 4px 0; padding-left: 16px;">• $1</div>')
}

// 复制分析结果
const copyAnalysisResult = async () => {
  try {
    await navigator.clipboard.writeText(aiAnalysisResult.value)
    message.success('分析结果已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败，请手动复制')
  }
}

// 生成采购统计分析
const generatePurchaseStatisticsAnalysis = (data) => {
  const { summary, trendData, trendAnalysis, productRankList, supplierRankList, trendType } = data

  let analysis = `## 采购数据智能分析报告\n\n`

  // 基础统计概览
  analysis += `### 📊 采购概览\n`
  if (summary) {
    analysis += `- **今日采购金额**: ￥${formatPrice(summary.todayPrice || 0)}\n`
    analysis += `- **昨日采购金额**: ￥${formatPrice(summary.yesterdayPrice || 0)}\n`
    analysis += `- **本月采购金额**: ￥${formatPrice(summary.monthPrice || 0)}\n`
    analysis += `- **今年采购金额**: ￥${formatPrice(summary.yearPrice || 0)}\n\n`

    // 日环比分析
    const dayChange = ((summary.todayPrice || 0) - (summary.yesterdayPrice || 0)) / (summary.yesterdayPrice || 1) * 100
    if (dayChange > 0) {
      analysis += `📈 **日环比**: 今日较昨日增长 ${dayChange.toFixed(1)}%\n`
    } else if (dayChange < 0) {
      analysis += `📉 **日环比**: 今日较昨日下降 ${Math.abs(dayChange).toFixed(1)}%\n`
    } else {
      analysis += `➡️ **日环比**: 今日与昨日持平\n`
    }
    analysis += `\n`
  }

  // 趋势分析
  if (trendData && trendData.length > 0) {
    analysis += `### 📈 趋势分析 (${trendType === 'week' ? '按周' : '按月'})\n`
    analysis += `- **统计周期**: 最近 ${trendData.length} 个${trendType === 'week' ? '周' : '月'}\n`
    analysis += `- **总采购金额**: ￥${formatPrice(trendAnalysis.totalPrice)}\n`
    analysis += `- **平均每${trendType === 'week' ? '周' : '月'}金额**: ￥${formatPrice(trendAnalysis.avgPrice)}\n`
    analysis += `- **最高金额**: ￥${formatPrice(trendAnalysis.maxPrice)} (${trendAnalysis.peakTime})\n`
    analysis += `- **最低金额**: ￥${formatPrice(trendAnalysis.minPrice)} (${trendAnalysis.valleyTime})\n\n`

    // 趋势变化
    if (trendAnalysis.priceTrend !== 0) {
      const trendDirection = trendAnalysis.priceTrend > 0 ? '上升' : '下降'
      analysis += `📊 **价格趋势**: ${trendDirection} ${Math.abs(trendAnalysis.priceTrendPercent).toFixed(1)}%\n`
    } else {
      analysis += `📊 **价格趋势**: 保持稳定\n`
    }

    if (trendAnalysis.countTrend !== 0) {
      const trendDirection = trendAnalysis.countTrend > 0 ? '上升' : '下降'
      analysis += `📦 **数量趋势**: ${trendDirection} ${Math.abs(trendAnalysis.countTrendPercent).toFixed(1)}%\n`
    } else {
      analysis += `📦 **数量趋势**: 保持稳定\n`
    }
    analysis += `\n`
  }

  // 产品排行分析
  if (productRankList && productRankList.length > 0) {
    analysis += `### 🏆 产品采购排行分析\n`
    analysis += `**前三名产品**:\n`
    productRankList.slice(0, 3).forEach((product, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysis += `${medal} ${product.productName} - 采购金额: ￥${formatPrice(product.price)} (数量: ${formatCount(product.count)})\n`
    })

    const totalProductAmount = productRankList.reduce((sum, p) => sum + (p.price || 0), 0)
    const topThreeAmount = productRankList.slice(0, 3).reduce((sum, p) => sum + (p.price || 0), 0)
    const topThreePercent = totalProductAmount > 0 ? (topThreeAmount / totalProductAmount * 100).toFixed(1) : '0'
    analysis += `\n📊 **集中度分析**: 前三名产品占总采购金额的 ${topThreePercent}%\n\n`
  }

  // 供应商排行分析
  if (supplierRankList && supplierRankList.length > 0) {
    analysis += `### 🏢 供应商采购排行分析\n`
    analysis += `**前三名供应商**:\n`
    supplierRankList.slice(0, 3).forEach((supplier, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysis += `${medal} ${supplier.supplierName} - 采购金额: ￥${formatPrice(supplier.price)} (数量: ${formatCount(supplier.count)})\n`
    })

    const totalSupplierAmount = supplierRankList.reduce((sum, s) => sum + (s.price || 0), 0)
    const topThreeSupplierAmount = supplierRankList.slice(0, 3).reduce((sum, s) => sum + (s.price || 0), 0)
    const topThreeSupplierPercent = totalSupplierAmount > 0 ? (topThreeSupplierAmount / totalSupplierAmount * 100).toFixed(1) : '0'
    analysis += `\n📊 **供应商集中度**: 前三名供应商占总采购金额的 ${topThreeSupplierPercent}%\n\n`
  }

  // 智能建议
  analysis += `### 💡 智能建议\n`
  
  // 基于趋势的建议
  if (trendAnalysis.priceTrend > 0 && trendAnalysis.priceTrendPercent > 20) {
    analysis += `- ⚠️ 采购金额呈快速上升趋势，建议关注成本控制，评估是否需要优化采购策略\n`
  } else if (trendAnalysis.priceTrend < 0 && Math.abs(trendAnalysis.priceTrendPercent) > 20) {
    analysis += `- 📉 采购金额呈下降趋势，可能反映业务收缩或采购效率提升，建议进一步分析原因\n`
  }

  // 基于集中度的建议
  if (productRankList && productRankList.length > 0) {
    const totalProductAmount = productRankList.reduce((sum, p) => sum + (p.price || 0), 0)
    const topThreeAmount = productRankList.slice(0, 3).reduce((sum, p) => sum + (p.price || 0), 0)
    const topThreePercent = totalProductAmount > 0 ? (topThreeAmount / totalProductAmount * 100) : 0
    
    if (topThreePercent > 70) {
      analysis += `- 🎯 产品采购集中度较高(${topThreePercent.toFixed(1)}%)，建议关注供应风险管理\n`
    } else if (topThreePercent < 30) {
      analysis += `- 🌐 产品采购较为分散，有利于风险分散，但可考虑是否有规模采购优化空间\n`
    }
  }

  if (supplierRankList && supplierRankList.length > 0) {
    const totalSupplierAmount = supplierRankList.reduce((sum, s) => sum + (s.price || 0), 0)
    const topThreeSupplierAmount = supplierRankList.slice(0, 3).reduce((sum, s) => sum + (s.price || 0), 0)
    const topThreeSupplierPercent = totalSupplierAmount > 0 ? (topThreeSupplierAmount / totalSupplierAmount * 100) : 0
    
    if (topThreeSupplierPercent > 80) {
      analysis += `- ⚠️ 供应商集中度过高(${topThreeSupplierPercent.toFixed(1)}%)，存在供应链风险，建议拓展供应商渠道\n`
    } else if (topThreeSupplierPercent < 40) {
      analysis += `- 🤝 供应商分布较为均衡，有利于议价能力和风险控制\n`
    }
  }

  analysis += `- 📊 建议定期进行采购数据分析，持续优化采购策略和供应商管理\n`
  analysis += `- 🔍 关注采购成本变化趋势，及时调整采购计划和预算安排\n`

  return analysis
}

// 初始化
onMounted(async () => {
  await Promise.all([
    getSummary(),
    getTrendData(),
    getProductRank(),
    getSupplierRank()
  ])
})
</script>

<style lang="scss" scoped>
.mobile-statistics {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}
.mobile-summary {
  display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px;
  &__item { background: #fff; border-radius: 10px; padding: 12px; text-align: center; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
  &__val { font-size: 16px; font-weight: 700; color: #409eff; }
  &__label { font-size: 11px; color: #909399; margin-top: 4px; }
}
.mobile-section {
  background: #fff; border-radius: 10px; padding: 14px; margin-bottom: 12px; box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
  &__title { font-weight: 600; font-size: 15px; color: #303133; }
  &__actions { display: flex; gap: 8px; margin-top: 10px; }
  &__date { margin-bottom: 10px; }
}
.mobile-rank-list { min-height: 60px; }
.mobile-rank-item {
  display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f5f5f5;
  &:last-child { border-bottom: none; }
  &__index { width: 32px; flex-shrink: 0; text-align: center; }
  &__num { font-size: 13px; color: #909399; }
  &__name { flex: 1; font-size: 13px; color: #303133; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin: 0 8px; }
  &__data { text-align: right; flex-shrink: 0; }
  &__price { font-size: 13px; font-weight: 600; color: #303133; }
  &__count { font-size: 11px; color: #909399; }
}
.text-danger { color: #f56c6c; }
.text-success { color: #67c23a; }
.trend-info-content {
  h4 { margin: 14px 0 8px; color: #303133; font-size: 14px; &:first-child { margin-top: 0; } }
  .analysis-card { background: #f5f7fa; border-radius: 8px; padding: 12px; margin-bottom: 8px;
    p { margin: 0 0 6px; color: #606266; font-size: 13px; &:last-child { margin-bottom: 0; } }
  }
  .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
  .stat-item { display: flex; flex-direction: column; padding: 6px 0;
    .stat-label { font-size: 11px; color: #909399; margin-bottom: 2px; }
    .stat-value { font-size: 16px; font-weight: 600; color: #303133; }
  }
  .feature-list { .feature-item { padding: 6px 0; border-bottom: 1px solid #ebeef5; color: #606266; font-size: 13px; &:last-child { border-bottom: none; } } }
}
.ai-analysis-content {
  max-height: 70vh; overflow-y: auto; padding: 12px; background: #fafafa; border-radius: 4px; line-height: 1.6; font-size: 13px;
  :deep(h2) { color: #303133; margin: 16px 0 8px; font-size: 16px; font-weight: 600; }
  :deep(h3) { color: #409eff; margin: 12px 0 6px; font-size: 14px; font-weight: 500; }
  :deep(strong) { color: #303133; font-weight: 600; }
}
</style>
