<template>
  <div class="sale-statistics-container">
    <!-- 时间选择器 -->
    <el-card shadow="never" class="mb-4">
      <el-form :inline="true" class="query-form">
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">
            <Icon icon="ep:search" class="mr-1" />
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-popover
            placement="bottom-start"
            :width="420"
            trigger="click"
            :visible="showConclusion"
          >
            <template #reference>
              <el-button type="success" @click="showConclusion = !showConclusion">
                <Icon icon="ep:data-analysis" class="mr-2" />
                查看分析结论
              </el-button>
            </template>

            <div class="conclusion-panel">
              <div class="conclusion-header">
                <Icon icon="ep:data-analysis" :size="20" class="mr-2" />
                <span class="conclusion-title">销售分析结论</span>
                <el-button type="primary" link class="close-btn" @click="showConclusion = false">
                  <Icon icon="ep:close" />
                </el-button>
              </div>
              <el-divider style="margin: 12px 0" />
              <div class="conclusion-content">
                <div class="conclusion-item" v-for="(item, index) in conclusionList" :key="index">
                  <Icon :icon="item.icon" :class="item.iconClass" class="conclusion-icon" />
                  <span class="conclusion-text">{{ item.text }}</span>
                </div>
              </div>
              <el-divider style="margin: 12px 0" />
              <div class="conclusion-summary">
                <div class="summary-label">综合评估：</div>
                <el-tag :type="overallRating.type" size="large">{{ overallRating.text }}</el-tag>
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-tooltip content="使用AI深度分析销售数据，提供智能洞察和建议" placement="top">
            <el-button type="warning"  @click="analyzeWithAI" :loading="aiAnalysisLoading">
              <Icon icon="ep:cpu" class="mr-1" />
              AI分析
            </el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon sale-icon">
              <Icon icon="ep:money" :size="24" />
            </div>
            <div class="stat-content">
              <div class="stat-label">销售金额</div>
              <div class="stat-value">¥{{ formatNumber(analysis?.totalSalePrice) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon order-icon">
              <Icon icon="ep:document" :size="24" />
            </div>
            <div class="stat-content">
              <div class="stat-label">订单数量</div>
              <div class="stat-value">{{ analysis?.totalOrderCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon customer-icon">
              <Icon icon="ep:user" :size="24" />
            </div>
            <div class="stat-content">
              <div class="stat-label">客户数量</div>
              <div class="stat-value">{{ analysis?.customerCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" :class="growthClass">
              <Icon :icon="growthIcon" :size="24" />
            </div>
            <div class="stat-content">
              <div class="stat-label">环比增长</div>
              <div class="stat-value" :class="growthClass">
                {{ analysis?.growthRate >= 0 ? '+' : '' }}{{ analysis?.growthRate || 0 }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 更多统计数据 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card-mini">
          <div class="mini-stat">
            <span class="mini-label">销售数量</span>
            <span class="mini-value">{{ formatNumber(analysis?.totalSaleCount) }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card-mini">
          <div class="mini-stat">
            <span class="mini-label">日均销售额</span>
            <span class="mini-value">¥{{ formatNumber(analysis?.avgDailySalePrice) }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card-mini">
          <div class="mini-stat">
            <span class="mini-label">退货金额</span>
            <span class="mini-value text-danger">¥{{ formatNumber(analysis?.totalReturnPrice) }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="never" class="stat-card-mini">
          <div class="mini-stat">
            <span class="mini-label">净销售额</span>
            <span class="mini-value text-success">
              ¥{{ formatNumber((analysis?.totalSalePrice || 0) - (analysis?.totalReturnPrice || 0)) }}
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售趋势图 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">销售趋势</span>
              <div class="header-actions">
                <el-radio-group v-model="trendType" size="small" @change="updateTrendChart">
                  <el-radio-button label="price">金额</el-radio-button>
                  <el-radio-button label="count">数量</el-radio-button>
                  <el-radio-button label="order">订单</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <Echart :height="350" :options="trendChartOptions" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 按月/按年对比图 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">销售对比分析</span>
              <div class="compare-controls">
                <el-radio-group v-model="compareType" size="small" @change="handleCompareTypeChange">
                  <el-radio-button label="month">按月对比</el-radio-button>
                  <el-radio-button label="year">按年对比</el-radio-button>
                </el-radio-group>
                <el-date-picker
                  v-if="compareType === 'month'"
                  v-model="compareMonthRange"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  size="small"
                  style="margin-left: 12px; width: 260px"
                  @change="loadCompareData"
                />
                <el-date-picker
                  v-else
                  v-model="compareYearRange"
                  type="yearrange"
                  range-separator="至"
                  start-placeholder="开始年份"
                  end-placeholder="结束年份"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  size="small"
                  style="margin-left: 12px; width: 220px"
                  @change="loadCompareData"
                />
                <el-radio-group v-model="compareMetric" size="small" style="margin-left: 12px" @change="updateCompareChart">
                  <el-radio-button label="salePrice">销售额</el-radio-button>
                  <el-radio-button label="orderCount">订单数</el-radio-button>
                  <el-radio-button label="customerCount">客户数</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <Echart :height="350" :options="compareChartOptions" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 排名列表 -->
    <el-row :gutter="16" class="mb-4">
      <!-- 客户排名 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">客户销售排名 TOP10</span>
            </div>
          </template>
          <el-table :data="customerRanking" stripe style="width: 100%" max-height="400">
            <el-table-column type="index" label="排名" width="60" align="center">
              <template #default="{ $index }">
                <el-tag v-if="$index < 3" :type="['danger', 'warning', 'success'][$index]" size="small">
                  {{ $index + 1 }}
                </el-tag>
                <span v-else>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="customerName" label="客户名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="totalPrice" label="销售金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatNumber(row.totalPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="orderCount" label="订单数" width="80" align="center" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 产品排名 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">产品销售排名 TOP10</span>
            </div>
          </template>
          <el-table :data="productRanking" stripe style="width: 100%" max-height="400">
            <el-table-column type="index" label="排名" width="60" align="center">
              <template #default="{ $index }">
                <el-tag v-if="$index < 3" :type="['danger', 'warning', 'success'][$index]" size="small">
                  {{ $index + 1 }}
                </el-tag>
                <span v-else>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="totalPrice" label="销售金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatNumber(row.totalPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalCount" label="销售数量" width="100" align="center">
              <template #default="{ row }">
                {{ formatNumber(row.totalCount) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售人员排名 -->
    <el-row :gutter="16">
      <el-col :xs="24" :md="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">销售人员业绩排名 TOP10</span>
            </div>
          </template>
          <el-table :data="userRanking" stripe style="width: 100%" max-height="400">
            <el-table-column type="index" label="排名" width="60" align="center">
              <template #default="{ $index }">
                <el-tag v-if="$index < 3" :type="['danger', 'warning', 'success'][$index]" size="small">
                  {{ $index + 1 }}
                </el-tag>
                <span v-else>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="销售人员" min-width="100" show-overflow-tooltip />
            <el-table-column prop="totalPrice" label="销售金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatNumber(row.totalPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="orderCount" label="订单数" width="80" align="center" />
            <el-table-column prop="customerCount" label="客户数" width="80" align="center" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- AI分析结果弹窗 -->
    <el-dialog v-model="showAIAnalysisDialog" title="AI销售数据分析报告" width="800px">
      <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 lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { EChartsOption } from 'echarts'
import { formatDate } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import {
  SaleStatisticsApi,
  ErpSaleAnalysisRespVO,
  ErpSaleTrendRespVO,
  ErpSaleCustomerSummaryRespVO,
  ErpSaleProductSummaryRespVO,
  ErpSaleUserSummaryRespVO,
  ErpSaleCompareRespVO
} from '@/api/erp/statistics/sale'

defineOptions({ name: 'ErpSaleStatistics' })

// 日期范围
const dateRange = ref<[string, string]>([
  formatDate(new Date(new Date().setDate(new Date().getDate() - 30)), 'YYYY-MM-DD') + ' 00:00:00',
  formatDate(new Date(), 'YYYY-MM-DD') + ' 23:59:59'
])

// 快捷日期选项
const dateShortcuts = [
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '本月',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), end.getMonth(), 1)
      return [start, end]
    }
  },
  {
    text: '上月',
    value: () => {
      const end = new Date(new Date().getFullYear(), new Date().getMonth(), 0)
      const start = new Date(end.getFullYear(), end.getMonth(), 1)
      return [start, end]
    }
  },
  {
    text: '本季度',
    value: () => {
      const now = new Date()
      const quarter = Math.floor(now.getMonth() / 3)
      const start = new Date(now.getFullYear(), quarter * 3, 1)
      return [start, now]
    }
  },
  {
    text: '本年',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), 0, 1)
      return [start, end]
    }
  }
]

// 数据
const analysis = ref<ErpSaleAnalysisRespVO>()
const trendData = ref<ErpSaleTrendRespVO[]>([])
const customerRanking = ref<ErpSaleCustomerSummaryRespVO[]>([])
const productRanking = ref<ErpSaleProductSummaryRespVO[]>([])
const userRanking = ref<ErpSaleUserSummaryRespVO[]>([])
const trendType = ref<'price' | 'count' | 'order'>('price')
const showConclusion = ref(false)

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

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

// 对比数据
const compareType = ref<'month' | 'year'>('month')
const compareMetric = ref<'salePrice' | 'orderCount' | 'customerCount'>('salePrice')
const compareData = ref<ErpSaleCompareRespVO[]>([])
const compareMonthRange = ref<[string, string]>([
  formatDate(new Date(new Date().getFullYear(), 0, 1), 'YYYY-MM-DD') + ' 00:00:00',
  formatDate(new Date(), 'YYYY-MM-DD') + ' 23:59:59'
])
const compareYearRange = ref<[string, string]>([
  formatDate(new Date(new Date().getFullYear() - 4, 0, 1), 'YYYY-MM-DD') + ' 00:00:00',
  formatDate(new Date(), 'YYYY-MM-DD') + ' 23:59:59'
])

// 对比图配置
const compareChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' }
  },
  legend: {
    data: ['销售额', '退货额', '净销售额'],
    top: 0
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value: number) => {
        if (value >= 10000) return (value / 10000).toFixed(1) + '万'
        return value.toString()
      }
    }
  },
  series: [
    {
      name: '销售额',
      type: 'bar',
      barWidth: '20%',
      itemStyle: { color: '#409EFF' },
      data: []
    },
    {
      name: '退货额',
      type: 'bar',
      barWidth: '20%',
      itemStyle: { color: '#F56C6C' },
      data: []
    },
    {
      name: '净销售额',
      type: 'bar',
      barWidth: '20%',
      itemStyle: { color: '#67C23A' },
      data: []
    }
  ]
})

// 趋势图配置
const trendChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'cross' }
  },
  legend: {
    data: ['销售金额', '退货金额'],
    top: 0
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value: number) => {
        if (value >= 10000) return (value / 10000).toFixed(1) + '万'
        return value.toString()
      }
    }
  },
  series: [
    {
      name: '销售金额',
      type: 'line',
      smooth: true,
      areaStyle: { opacity: 0.3 },
      itemStyle: { color: '#409EFF' },
      data: []
    },
    {
      name: '退货金额',
      type: 'line',
      smooth: true,
      areaStyle: { opacity: 0.3 },
      itemStyle: { color: '#F56C6C' },
      data: []
    }
  ]
})

// 计算属性
const growthClass = computed(() => {
  if (!analysis.value) return 'neutral-icon'
  return analysis.value.growthRate >= 0 ? 'growth-icon' : 'decline-icon'
})

const growthIcon = computed(() => {
  if (!analysis.value) return 'ep:minus'
  return analysis.value.growthRate >= 0 ? 'ep:top' : 'ep:bottom'
})

// 分析结论列表
const conclusionList = computed(() => {
  if (!analysis.value) return []
  const list: { icon: string; iconClass: string; text: string }[] = []
  const a = analysis.value
  const netSales = (a.totalSalePrice || 0) - (a.totalReturnPrice || 0)
  const returnRate = a.totalSalePrice > 0 ? ((a.totalReturnPrice || 0) / a.totalSalePrice * 100) : 0
  const avgOrderValue = a.totalOrderCount > 0 ? (a.totalSalePrice / a.totalOrderCount) : 0

  // 销售额分析
  list.push({
    icon: 'ep:money',
    iconClass: 'text-primary',
    text: `统计期间总销售额 ¥${formatNumber(a.totalSalePrice)}，净销售额 ¥${formatNumber(netSales)}`
  })

  // 增长率分析
  if (a.growthRate > 10) {
    list.push({ icon: 'ep:top', iconClass: 'text-success', text: `环比增长 ${a.growthRate}%，销售业绩增长强劲！` })
  } else if (a.growthRate > 0) {
    list.push({ icon: 'ep:top', iconClass: 'text-success', text: `环比增长 ${a.growthRate}%，销售业绩稳步提升` })
  } else if (a.growthRate < -10) {
    list.push({ icon: 'ep:bottom', iconClass: 'text-danger', text: `环比下降 ${Math.abs(a.growthRate)}%，需重点关注销售策略` })
  } else if (a.growthRate < 0) {
    list.push({ icon: 'ep:bottom', iconClass: 'text-warning', text: `环比下降 ${Math.abs(a.growthRate)}%，销售略有下滑` })
  } else {
    list.push({ icon: 'ep:minus', iconClass: 'text-info', text: '环比持平，销售业绩保持稳定' })
  }

  // 订单分析
  list.push({
    icon: 'ep:document',
    iconClass: 'text-primary',
    text: `共完成 ${a.totalOrderCount} 笔订单，平均订单金额 ¥${formatNumber(avgOrderValue)}`
  })

  // 客户分析
  list.push({
    icon: 'ep:user',
    iconClass: 'text-warning',
    text: `服务客户 ${a.customerCount} 位，客均消费 ¥${formatNumber(a.customerCount > 0 ? a.totalSalePrice / a.customerCount : 0)}`
  })

  // 退货率分析
  if (returnRate > 10) {
    list.push({ icon: 'ep:warning', iconClass: 'text-danger', text: `退货率 ${returnRate.toFixed(2)}%，退货比例偏高，建议排查原因` })
  } else if (returnRate > 5) {
    list.push({ icon: 'ep:info-filled', iconClass: 'text-warning', text: `退货率 ${returnRate.toFixed(2)}%，处于正常偏高水平` })
  } else if (returnRate > 0) {
    list.push({ icon: 'ep:success-filled', iconClass: 'text-success', text: `退货率 ${returnRate.toFixed(2)}%，退货率控制良好` })
  }

  // 日均销售
  list.push({
    icon: 'ep:calendar',
    iconClass: 'text-primary',
    text: `日均销售额 ¥${formatNumber(a.avgDailySalePrice)}，销售数量 ${formatNumber(a.totalSaleCount)} 件`
  })

  // 销售人员分析
  if (userRanking.value && userRanking.value.length > 0) {
    const topUser = userRanking.value[0]
    const userCount = userRanking.value.length
    const totalUserSales = userRanking.value.reduce((sum, u) => sum + (u.totalPrice || 0), 0)
    const avgUserSales = userCount > 0 ? totalUserSales / userCount : 0
    const topUserPercent = totalUserSales > 0 ? ((topUser.totalPrice / totalUserSales) * 100).toFixed(1) : 0

    list.push({
      icon: 'ep:avatar',
      iconClass: 'text-primary',
      text: `共有 ${userCount} 位销售人员参与销售，人均销售额 ¥${formatNumber(avgUserSales)}`
    })

    list.push({
      icon: 'ep:trophy',
      iconClass: 'text-warning',
      text: `销售冠军：${topUser.userName}，销售额 ¥${formatNumber(topUser.totalPrice)}，占比 ${topUserPercent}%`
    })
  }

  return list
})

// 综合评级
const overallRating = computed(() => {
  if (!analysis.value) return { type: 'info' as const, text: '暂无数据' }
  const a = analysis.value
  const returnRate = a.totalSalePrice > 0 ? ((a.totalReturnPrice || 0) / a.totalSalePrice * 100) : 0

  // 综合评分
  let score = 50
  if (a.growthRate > 10) score += 30
  else if (a.growthRate > 0) score += 15
  else if (a.growthRate < -10) score -= 20
  else if (a.growthRate < 0) score -= 10

  if (returnRate < 3) score += 15
  else if (returnRate < 5) score += 5
  else if (returnRate > 10) score -= 15
  else if (returnRate > 5) score -= 5

  if (a.totalOrderCount > 100) score += 10
  else if (a.totalOrderCount > 50) score += 5

  if (score >= 80) return { type: 'success' as const, text: '🌟 销售业绩优秀' }
  if (score >= 60) return { type: 'primary' as const, text: '👍 销售业绩良好' }
  if (score >= 40) return { type: 'warning' as const, text: '📊 销售业绩一般' }
  return { type: 'danger' as const, text: '⚠️ 销售业绩需改善' }
})

// 格式化数字
const formatNumber = (num: number | undefined | null): string => {
  if (num === undefined || num === null) return '0'
  return Number(num).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 处理日期变化
const handleDateChange = () => {
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    loadData()
  }
}

// 更新趋势图
const updateTrendChart = () => {
  if (!trendData.value || trendData.value.length === 0) return

  const xAxisData = trendData.value.map((item) => item.date)
  let seriesData1: number[] = []
  let seriesData2: number[] = []
  let legendData: string[] = []

  switch (trendType.value) {
    case 'price':
      legendData = ['销售金额', '退货金额']
      seriesData1 = trendData.value.map((item) => item.salePrice || 0)
      seriesData2 = trendData.value.map((item) => item.returnPrice || 0)
      break
    case 'count':
      legendData = ['销售数量']
      seriesData1 = trendData.value.map((item) => item.saleCount || 0)
      seriesData2 = []
      break
    case 'order':
      legendData = ['订单数量']
      seriesData1 = trendData.value.map((item) => item.orderCount || 0)
      seriesData2 = []
      break
  }

  // 更新图表配置
  if (trendChartOptions.xAxis && !Array.isArray(trendChartOptions.xAxis)) {
    trendChartOptions.xAxis.data = xAxisData
  }
  if (trendChartOptions.legend && !Array.isArray(trendChartOptions.legend)) {
    trendChartOptions.legend.data = legendData
  }
  if (trendChartOptions.series && Array.isArray(trendChartOptions.series)) {
    trendChartOptions.series[0].name = legendData[0]
    trendChartOptions.series[0].data = seriesData1
    if (seriesData2.length > 0) {
      trendChartOptions.series[1] = {
        name: legendData[1] || '',
        type: 'line',
        smooth: true,
        areaStyle: { opacity: 0.3 },
        itemStyle: { color: '#F56C6C' },
        data: seriesData2
      }
    } else {
      trendChartOptions.series = [trendChartOptions.series[0]]
    }
  }
}

// 加载数据
const loadData = async () => {
  if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) return

  const beginTime = dateRange.value[0]
  const endTime = dateRange.value[1]

  try {
    // 并行请求所有数据
    const [analysisData, trendList, customerList, productList, userList] = await Promise.all([
      SaleStatisticsApi.getSaleAnalysis(beginTime, endTime),
      SaleStatisticsApi.getSaleTrend(beginTime, endTime),
      SaleStatisticsApi.getCustomerSaleRanking(beginTime, endTime, 10),
      SaleStatisticsApi.getProductSaleRanking(beginTime, endTime, 10),
      SaleStatisticsApi.getUserSaleRanking(beginTime, endTime, 10)
    ])

    analysis.value = analysisData
    trendData.value = trendList
    customerRanking.value = customerList
    productRanking.value = productList
    userRanking.value = userList

    // 更新趋势图
    updateTrendChart()

    // 加载对比数据
    loadCompareData()
  } catch (error) {
    console.error('加载销售统计数据失败:', error)
  }
}

// 处理对比类型变化
const handleCompareTypeChange = () => {
  loadCompareData()
}

// 加载对比数据
const loadCompareData = async () => {
  try {
    let beginTime: string
    let endTime: string

    if (compareType.value === 'month') {
      if (!compareMonthRange.value || !compareMonthRange.value[0] || !compareMonthRange.value[1]) return
      beginTime = compareMonthRange.value[0]
      endTime = compareMonthRange.value[1]
      compareData.value = await SaleStatisticsApi.getSaleCompareByMonth(beginTime, endTime)
    } else {
      if (!compareYearRange.value || !compareYearRange.value[0] || !compareYearRange.value[1]) return
      beginTime = compareYearRange.value[0]
      endTime = compareYearRange.value[1]
      compareData.value = await SaleStatisticsApi.getSaleCompareByYear(beginTime, endTime)
    }

    updateCompareChart()
  } catch (error) {
    console.error('加载对比数据失败:', error)
  }
}

// 更新对比图表
const updateCompareChart = () => {
  if (!compareData.value || compareData.value.length === 0) return

  const xAxisData = compareData.value.map((item) => item.timeLabel)

  // 根据选择的指标更新图表
  if (compareChartOptions.xAxis && !Array.isArray(compareChartOptions.xAxis)) {
    compareChartOptions.xAxis.data = xAxisData
  }

  if (compareMetric.value === 'salePrice') {
    // 销售额模式：显示销售额、退货额、净销售额
    if (compareChartOptions.legend && !Array.isArray(compareChartOptions.legend)) {
      compareChartOptions.legend.data = ['销售额', '退货额', '净销售额']
    }
    if (compareChartOptions.series && Array.isArray(compareChartOptions.series)) {
      compareChartOptions.series = [
        {
          name: '销售额',
          type: 'bar',
          barWidth: '20%',
          itemStyle: { color: '#409EFF' },
          data: compareData.value.map((item) => item.salePrice || 0)
        },
        {
          name: '退货额',
          type: 'bar',
          barWidth: '20%',
          itemStyle: { color: '#F56C6C' },
          data: compareData.value.map((item) => item.returnPrice || 0)
        },
        {
          name: '净销售额',
          type: 'bar',
          barWidth: '20%',
          itemStyle: { color: '#67C23A' },
          data: compareData.value.map((item) => item.netSalePrice || 0)
        }
      ]
    }
  } else if (compareMetric.value === 'orderCount') {
    // 订单数模式
    if (compareChartOptions.legend && !Array.isArray(compareChartOptions.legend)) {
      compareChartOptions.legend.data = ['订单数量']
    }
    if (compareChartOptions.series && Array.isArray(compareChartOptions.series)) {
      compareChartOptions.series = [
        {
          name: '订单数量',
          type: 'bar',
          barWidth: '40%',
          itemStyle: { color: '#409EFF' },
          data: compareData.value.map((item) => item.orderCount || 0)
        }
      ]
    }
  } else if (compareMetric.value === 'customerCount') {
    // 客户数模式
    if (compareChartOptions.legend && !Array.isArray(compareChartOptions.legend)) {
      compareChartOptions.legend.data = ['客户数量']
    }
    if (compareChartOptions.series && Array.isArray(compareChartOptions.series)) {
      compareChartOptions.series = [
        {
          name: '客户数量',
          type: 'bar',
          barWidth: '40%',
          itemStyle: { color: '#E6A23C' },
          data: compareData.value.map((item) => item.customerCount || 0)
        }
      ]
    }
  }
}

// AI分析功能
const analyzeWithAI = async () => {
  aiAnalysisLoading.value = true
  try {
    // 准备分析数据
    const analysisData = {
      analysis: analysis.value,
      trendData: trendData.value,
      customerRanking: customerRanking.value,
      productRanking: productRanking.value,
      userRanking: userRanking.value,
      compareData: compareData.value,
      dateRange: dateRange.value
    }

    // 尝试调用AI分析API
    try {
      // 调用实际的AI分析API (DeepSeek)
      const aiResult = await SaleStatisticsApi.analyzeWithAI(analysisData)
      aiAnalysisResult.value = aiResult.data || aiResult
    } catch (aiError) {
      console.warn('AI分析失败，使用文字统计:', aiError)
      // 生成文字统计分析作为fallback
      aiAnalysisResult.value = generateSaleStatisticsAnalysis(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 generateSaleStatisticsAnalysis = (data) => {
  const { analysis, trendData, customerRanking, productRanking, userRanking } = data

  let analysisText = `## 销售数据智能分析报告\n\n`

  // 基础统计概览
  analysisText += `### 📊 销售概览\n`
  if (analysis) {
    analysisText += `- **总销售金额**: ￥${formatNumber(analysis.totalSalePrice || 0)}\n`
    analysisText += `- **总订单数量**: ${analysis.totalOrderCount || 0}\n`
    analysisText += `- **客户数量**: ${analysis.customerCount || 0}\n`
    analysisText += `- **销售数量**: ${formatNumber(analysis.totalSaleCount || 0)}\n`
    analysisText += `- **退货金额**: ￥${formatNumber(analysis.totalReturnPrice || 0)}\n`
    analysisText += `- **净销售额**: ￥${formatNumber((analysis.totalSalePrice || 0) - (analysis.totalReturnPrice || 0))}\n\n`

    // 环比分析
    if (analysis.growthRate !== undefined) {
      if (analysis.growthRate > 0) {
        analysisText += `📈 **环比增长**: ${analysis.growthRate}%，销售业绩呈上升趋势\n`
      } else if (analysis.growthRate < 0) {
        analysisText += `📉 **环比变化**: ${analysis.growthRate}%，销售业绩有所下降\n`
      } else {
        analysisText += `➡️ **环比变化**: 与上期持平\n`
      }
    }
    analysisText += `\n`
  }

  // 趋势分析
  if (trendData && trendData.length > 0) {
    analysisText += `### 📈 销售趋势分析\n`
    analysisText += `- **统计周期**: 共 ${trendData.length} 个时间点\n`

    const totalSales = trendData.reduce((sum, item) => sum + (item.salePrice || 0), 0)
    const avgSales = totalSales / trendData.length
    const maxSales = Math.max(...trendData.map(item => item.salePrice || 0))
    const minSales = Math.min(...trendData.map(item => item.salePrice || 0))

    analysisText += `- **总销售额**: ￥${formatNumber(totalSales)}\n`
    analysisText += `- **平均销售额**: ￥${formatNumber(avgSales)}\n`
    analysisText += `- **最高销售额**: ￥${formatNumber(maxSales)}\n`
    analysisText += `- **最低销售额**: ￥${formatNumber(minSales)}\n\n`
  }

  // 客户排行分析
  if (customerRanking && customerRanking.length > 0) {
    analysisText += `### 🏆 客户销售排行分析\n`
    analysisText += `**前三名客户**:\n`
    customerRanking.slice(0, 3).forEach((customer, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysisText += `${medal} ${customer.customerName} - 销售金额: ￥${formatNumber(customer.totalPrice)} (订单数: ${customer.orderCount})\n`
    })

    const totalCustomerAmount = customerRanking.reduce((sum, c) => sum + (c.totalPrice || 0), 0)
    const topThreeAmount = customerRanking.slice(0, 3).reduce((sum, c) => sum + (c.totalPrice || 0), 0)
    const topThreePercent = totalCustomerAmount > 0 ? (topThreeAmount / totalCustomerAmount * 100).toFixed(1) : '0'
    analysisText += `\n📊 **客户集中度**: 前三名客户占总销售金额的 ${topThreePercent}%\n\n`
  }

  // 产品排行分析
  if (productRanking && productRanking.length > 0) {
    analysisText += `### 🛍️ 产品销售排行分析\n`
    analysisText += `**前三名产品**:\n`
    productRanking.slice(0, 3).forEach((product, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysisText += `${medal} ${product.productName} - 销售金额: ￥${formatNumber(product.totalPrice)} (销量: ${formatNumber(product.totalCount)})\n`
    })

    const totalProductAmount = productRanking.reduce((sum, p) => sum + (p.totalPrice || 0), 0)
    const topThreeProductAmount = productRanking.slice(0, 3).reduce((sum, p) => sum + (p.totalPrice || 0), 0)
    const topThreeProductPercent = totalProductAmount > 0 ? (topThreeProductAmount / totalProductAmount * 100).toFixed(1) : '0'
    analysisText += `\n📊 **产品集中度**: 前三名产品占总销售金额的 ${topThreeProductPercent}%\n\n`
  }

  // 销售人员分析
  if (userRanking && userRanking.length > 0) {
    analysisText += `### 👥 销售人员业绩分析\n`
    analysisText += `**前三名销售人员**:\n`
    userRanking.slice(0, 3).forEach((user, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysisText += `${medal} ${user.userName} - 销售金额: ￥${formatNumber(user.totalPrice)} (订单: ${user.orderCount}, 客户: ${user.customerCount})\n`
    })

    const totalUserAmount = userRanking.reduce((sum, u) => sum + (u.totalPrice || 0), 0)
    const topThreeUserAmount = userRanking.slice(0, 3).reduce((sum, u) => sum + (u.totalPrice || 0), 0)
    const topThreeUserPercent = totalUserAmount > 0 ? (topThreeUserAmount / totalUserAmount * 100).toFixed(1) : '0'
    analysisText += `\n📊 **业绩集中度**: 前三名销售人员占总销售金额的 ${topThreeUserPercent}%\n\n`
  }

  // 智能建议
  analysisText += `### 💡 智能建议\n`

  // 基于增长率的建议
  if (analysis && analysis.growthRate !== undefined) {
    if (analysis.growthRate > 20) {
      analysisText += `- 🚀 销售增长强劲，建议加大市场投入，扩大销售规模\n`
    } else if (analysis.growthRate > 0) {
      analysisText += `- 📈 销售稳步增长，建议保持现有策略，优化销售流程\n`
    } else if (analysis.growthRate < -10) {
      analysisText += `- ⚠️ 销售下降明显，建议重新评估市场策略和产品定位\n`
    } else if (analysis.growthRate < 0) {
      analysisText += `- 📉 销售略有下降，建议分析原因并调整销售策略\n`
    }
  }

  // 基于退货率的建议
  if (analysis && analysis.totalSalePrice > 0 && analysis.totalReturnPrice > 0) {
    const returnRate = (analysis.totalReturnPrice / analysis.totalSalePrice * 100).toFixed(1)
    if (parseFloat(returnRate) > 10) {
      analysisText += `- 🔄 退货率较高(${returnRate}%)，建议加强产品质量控制和售后服务\n`
    } else if (parseFloat(returnRate) > 5) {
      analysisText += `- 📦 退货率适中(${returnRate}%)，建议持续关注产品质量\n`
    } else {
      analysisText += `- ✅ 退货率较低(${returnRate}%)，产品质量控制良好\n`
    }
  }

  // 基于集中度的建议
  if (customerRanking && customerRanking.length > 0) {
    const totalCustomerAmount = customerRanking.reduce((sum, c) => sum + (c.totalPrice || 0), 0)
    const topThreeAmount = customerRanking.slice(0, 3).reduce((sum, c) => sum + (c.totalPrice || 0), 0)
    const topThreePercent = totalCustomerAmount > 0 ? (topThreeAmount / totalCustomerAmount * 100) : 0

    if (topThreePercent > 70) {
      analysisText += `- 🎯 客户集中度较高(${topThreePercent.toFixed(1)}%)，建议拓展客户群体，降低依赖风险\n`
    } else if (topThreePercent < 30) {
      analysisText += `- 🌐 客户分布较为均衡，有利于风险分散和业务稳定\n`
    }
  }

  analysisText += `- 📊 建议定期进行销售数据分析，持续优化销售策略和客户管理\n`
  analysisText += `- 🔍 关注销售趋势变化，及时调整产品策略和市场投入\n`

  return analysisText
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.sale-statistics-container {
  padding: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mr-1 {
  margin-right: 4px;
}

.query-form {
  display: flex;
  align-items: center;
}

.stat-card {
  .stat-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
  }

  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    color: #fff;
  }

  .sale-icon {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  }

  .order-icon {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  }

  .customer-icon {
    background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
  }

  .growth-icon {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  }

  .decline-icon {
    background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  }

  .neutral-icon {
    background: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
  }

  .stat-content {
    flex: 1;
  }

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 4px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;

    &.growth-icon {
      color: #67c23a;
    }

    &.decline-icon {
      color: #f56c6c;
    }
  }
}

.stat-card-mini {
  .mini-stat {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
  }

  .mini-label {
    font-size: 14px;
    color: #606266;
  }

  .mini-value {
    font-size: 18px;
    font-weight: 600;
    color: #303133;

    &.text-danger {
      color: #f56c6c;
    }

    &.text-success {
      color: #67c23a;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.compare-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.mr-2 {
  margin-right: 8px;
}

.conclusion-panel {
  .conclusion-header {
    display: flex;
    align-items: center;

    .conclusion-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      flex: 1;
    }

    .close-btn {
      padding: 0;
    }
  }

  .conclusion-content {
    .conclusion-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      line-height: 1.5;

      &:last-child {
        margin-bottom: 0;
      }

      .conclusion-icon {
        margin-right: 8px;
        margin-top: 2px;
        flex-shrink: 0;
      }

      .conclusion-text {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .conclusion-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .summary-label {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.text-primary {
  color: #409eff;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

.text-info {
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ai-analysis-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
  line-height: 1.6;
}

.ai-analysis-content h2 {
  color: #303133;
  margin: 20px 0 12px 0;
  font-size: 18px;
  font-weight: 600;
}

.ai-analysis-content h3 {
  color: #409eff;
  margin: 16px 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.ai-analysis-content strong {
  color: #303133;
  font-weight: 600;
}

.ai-analysis-content div {
  margin: 4px 0;
  color: #606266;
}
</style>
