<template>
  <Dialog v-model="dialogVisible" title="供应商评价汇总表" width="100%" fullscreen class="mobile-summary-dialog">
    <div v-loading="loading" class="mobile-summary-wrapper">
      <!-- 筛选条件 -->
      <div class="mobile-summary-section">
        <div class="mobile-summary-filter">
          <el-select v-model="queryParams.sortBy" @change="loadSummaryData" placeholder="排序方式" size="small" style="flex:1">
            <el-option label="综合评分" value="avgTotalScore" />
            <el-option label="评价次数" value="totalEvaluations" />
            <el-option label="质量评分" value="avgQualityScore" />
            <el-option label="服务评分" value="avgServiceScore" />
            <el-option label="价格评分" value="avgPriceScore" />
            <el-option label="交付评分" value="avgDeliveryScore" />
          </el-select>
          <el-button type="primary" size="small" :icon="Refresh" circle @click="refreshData" :loading="loading" />
          <el-button type="warning" size="small" @click="analyzeWithAI" :loading="aiAnalysisLoading">AI分析</el-button>
        </div>
      </div>

      <!-- 汇总统计卡片 -->
      <div class="mobile-summary-stats">
        <div class="mobile-summary-stats__item">
          <div class="mobile-summary-stats__val">{{ summaryStats.totalSuppliers }}</div>
          <div class="mobile-summary-stats__label">供应商总数</div>
        </div>
        <div class="mobile-summary-stats__item">
          <div class="mobile-summary-stats__val" style="color:#409eff">{{ summaryStats.totalEvaluations }}</div>
          <div class="mobile-summary-stats__label">评价总次数</div>
        </div>
        <div class="mobile-summary-stats__item">
          <div class="mobile-summary-stats__val" style="color:#67c23a">{{ summaryStats.avgScore }}</div>
          <div class="mobile-summary-stats__label">整体平均分</div>
        </div>
        <div class="mobile-summary-stats__item">
          <div class="mobile-summary-stats__val" style="color:#e6a23c">{{ summaryStats.excellentRate }}%</div>
          <div class="mobile-summary-stats__label">优秀占比</div>
        </div>
      </div>

      <!-- 供应商卡片列表 -->
      <div class="mobile-summary-list">
        <div v-if="summaryList.length === 0 && !loading" style="padding:40px 0">
          <el-empty description="暂无汇总数据" />
        </div>
        <div v-for="(item, index) in summaryList" :key="item.supplierId" class="mobile-summary-card">
          <div class="mobile-summary-card__header">
            <div class="mobile-summary-card__rank">
              <el-tag v-if="index < 3" :type="getRankingTagType(index)" size="small">{{ index + 1 }}</el-tag>
              <span v-else class="mobile-summary-card__rank-num">{{ index + 1 }}</span>
            </div>
            <div class="mobile-summary-card__name">
              {{ item.supplierName }}
              <el-tag v-if="item.avgTotalScore >= 9" type="success" size="small" style="margin-left:6px">优秀</el-tag>
            </div>
            <div class="mobile-summary-card__total" :class="getScoreClass(item.avgTotalScore)">
              {{ item.avgTotalScore }}
            </div>
          </div>
          <div class="mobile-summary-card__body">
            <div class="mobile-summary-card__row">
              <span class="mobile-summary-card__label">评价次数</span>
              <el-tag type="info" size="small">{{ item.totalEvaluations }}次</el-tag>
            </div>
            <div class="mobile-summary-card__scores">
              <div class="mobile-summary-card__score-item">
                <el-progress :percentage="(item.avgQualityScore / 10) * 100" :color="getProgressColor(item.avgQualityScore)" :show-text="false" :stroke-width="6" />
                <span class="mobile-summary-card__score-text">质量 {{ item.avgQualityScore }}</span>
              </div>
              <div class="mobile-summary-card__score-item">
                <el-progress :percentage="(item.avgServiceScore / 10) * 100" :color="getProgressColor(item.avgServiceScore)" :show-text="false" :stroke-width="6" />
                <span class="mobile-summary-card__score-text">服务 {{ item.avgServiceScore }}</span>
              </div>
              <div class="mobile-summary-card__score-item">
                <el-progress :percentage="(item.avgPriceScore / 10) * 100" :color="getProgressColor(item.avgPriceScore)" :show-text="false" :stroke-width="6" />
                <span class="mobile-summary-card__score-text">价格 {{ item.avgPriceScore }}</span>
              </div>
              <div class="mobile-summary-card__score-item">
                <el-progress :percentage="(item.avgDeliveryScore / 10) * 100" :color="getProgressColor(item.avgDeliveryScore)" :show-text="false" :stroke-width="6" />
                <span class="mobile-summary-card__score-text">交付 {{ item.avgDeliveryScore }}</span>
              </div>
            </div>
            <div class="mobile-summary-card__row">
              <span class="mobile-summary-card__label">最近评价</span>
              <span class="mobile-summary-card__value">{{ formatDate(item.lastEvaluationTime) }}</span>
            </div>
            <div class="mobile-summary-card__row">
              <span class="mobile-summary-card__label">趋势</span>
              <span :class="getTrendClass(item.trend)">{{ getTrendText(item.trend) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false" style="width:100%">关闭</el-button>
    </template>
  </Dialog>

  <!-- 供应商详情弹窗 -->
  <SupplierDetailDialog ref="supplierDetailRef" />

  <!-- 评价历史弹窗 -->
  <EvaluationHistoryDialog ref="evaluationHistoryRef" />

  <!-- AI分析结果弹窗 -->
  <Dialog v-model="showAnalysisDialog" title="AI分析报告" width="100%" fullscreen class="mobile-analysis-dialog">
    <div class="mobile-analysis-content">
      <div v-html="formatAnalysisText(aiAnalysisResult)"></div>
    </div>
    <template #footer>
      <div class="mobile-form-footer">
        <el-button @click="showAnalysisDialog = false" style="flex:1">关闭</el-button>
        <el-button type="primary" @click="copyAnalysisResult" style="flex:1">复制结果</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { Refresh } from '@element-plus/icons-vue'
import { SupplierEvaluationApi } from '@/api/erp/purchase/supplierEvaluation'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import SupplierDetailDialog from './SupplierDetailDialog.vue'
import EvaluationHistoryDialog from './EvaluationHistoryDialog.vue'

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

interface SupplierSummary {
  supplierId: number
  supplierName: string
  totalEvaluations: number
  avgTotalScore: number
  avgQualityScore: number
  avgServiceScore: number
  avgPriceScore: number
  avgDeliveryScore: number
  lastEvaluationTime: string
  trend: 'up' | 'down' | 'stable'
}

const dialogVisible = ref(false)
const fullscreen = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const aiAnalysisLoading = ref(false)
const aiAnalysisResult = ref('')
const showAnalysisDialog = ref(false)
const summaryList = ref<SupplierSummary[]>([])

const queryParams = reactive({
  dateRange: [],
  minEvaluations: 1,
  sortBy: 'avgTotalScore'
})

const summaryStats = ref({
  totalSuppliers: 0,
  totalEvaluations: 0,
  avgScore: '0.0',
  excellentRate: 0
})

// 打开弹窗
const open = async () => {
  dialogVisible.value = true
  await loadSummaryData()
}

// 加载汇总数据
const loadSummaryData = async () => {
  loading.value = true
  try {
    // 调用后端API获取供应商汇总数据
    const data = await SupplierEvaluationApi.getSupplierSummaryList({
      minEvaluations: queryParams.minEvaluations,
      sortBy: queryParams.sortBy
    })

    summaryList.value = data || []

    // 计算统计数据
    const totalSuppliers = summaryList.value.length
    const totalEvaluations = summaryList.value.reduce((sum, item) => sum + item.totalEvaluations, 0)
    const avgScore = totalSuppliers > 0
      ? (summaryList.value.reduce((sum, item) => sum + item.avgTotalScore, 0) / totalSuppliers).toFixed(1)
      : '0.0'
    const excellentRate = totalSuppliers > 0
      ? Math.round((summaryList.value.filter(item => item.avgTotalScore >= 9).length / totalSuppliers) * 100)
      : 0

    summaryStats.value = {
      totalSuppliers,
      totalEvaluations,
      avgScore,
      excellentRate
    }

    // 排序数据
    sortSummaryData()
  } catch (error) {
    console.error('加载汇总数据失败:', error)
    message.error('加载供应商汇总数据失败')
  } finally {
    loading.value = false
  }
}


// 排序数据
const sortSummaryData = () => {
  summaryList.value.sort((a, b) => {
    const field = queryParams.sortBy as keyof SupplierSummary
    return (b[field] as number) - (a[field] as number)
  })
}

// 处理表格排序
const handleSortChange = ({ prop, order }) => {
  if (order === 'ascending') {
    summaryList.value.sort((a, b) => (a[prop] as number) - (b[prop] as number))
  } else {
    summaryList.value.sort((a, b) => (b[prop] as number) - (a[prop] as number))
  }
}

// 刷新数据
const refreshData = async () => {
  await loadSummaryData()
}

// 监听查询参数变化，自动刷新数据
watch(() => [queryParams.minEvaluations, queryParams.sortBy], () => {
  if (dialogVisible.value) {
    loadSummaryData()
  }
}, { deep: true })

// 导出汇总表
const exportSummary = async () => {
  exportLoading.value = true
  try {
    // 这里应该调用实际的导出API
    const data = summaryList.value
    // download.excel(data, '供应商评价汇总表.xlsx')
    console.log('导出数据:', data)
  } finally {
    exportLoading.value = false
  }
}

// 获取排名标签类型
const getRankingTagType = (index: number) => {
  if (index === 0) return 'warning'
  if (index === 1) return 'info'
  if (index === 2) return 'success'
  return ''
}

// 获取评分等级
const getScoreLevel = (score: number) => {
  if (score >= 9) return '优秀'
  if (score >= 8) return '良好'
  if (score >= 7) return '一般'
  if (score >= 6) return '及格'
  return '不及格'
}

// 获取评分样式类
const getScoreClass = (score: number) => {
  if (score >= 9) return 'score-excellent'
  if (score >= 8) return 'score-good'
  if (score >= 7) return 'score-average'
  if (score >= 6) return 'score-pass'
  return 'score-fail'
}

// 获取进度条颜色
const getProgressColor = (score: number) => {
  if (score >= 9) return '#67c23a'
  if (score >= 8) return '#409eff'
  if (score >= 7) return '#e6a23c'
  if (score >= 6) return '#909399'
  return '#f56c6c'
}

// 获取趋势图标
const getTrendIcon = (trend: string) => {
  switch (trend) {
    case 'up': return 'ep:trend-charts'
    case 'down': return 'ep:bottom'
    case 'stable': return 'ep:minus'
    default: return 'ep:minus'
  }
}

// 获取趋势样式类
const getTrendClass = (trend: string) => {
  switch (trend) {
    case 'up': return 'trend-up'
    case 'down': return 'trend-down'
    case 'stable': return 'trend-stable'
    default: return 'trend-stable'
  }
}

// 获取趋势文本
const getTrendText = (trend: string) => {
  switch (trend) {
    case 'up': return '上升'
    case 'down': return '下降'
    case 'stable': return '稳定'
    default: return '稳定'
  }
}

// 查看供应商详情
const supplierDetailRef = ref()
const viewSupplierDetail = (row: SupplierSummary) => {
  supplierDetailRef.value.open(row)
}

// 查看评价历史
const evaluationHistoryRef = ref()
const viewEvaluationHistory = (row: SupplierSummary) => {
  evaluationHistoryRef.value.open(row.supplierId, row.supplierName)
}

// AI分析功能
const analyzeWithAI = async () => {
  aiAnalysisLoading.value = true
  try {
    // 准备分析数据
    const analysisData = {
      summaryStats: summaryStats.value,
      supplierData: summaryList.value,
      queryParams: queryParams
    }

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

    showAnalysisDialog.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 generateTextStatistics = (data) => {
  const { summaryStats, supplierData } = data

  let analysis = `## 供应商评价汇总分析报告\n\n`

  // 基础统计
  analysis += `### 📊 基础统计\n`
  analysis += `- **评价供应商总数**: ${summaryStats.totalSuppliers}家\n`
  analysis += `- **评价总次数**: ${summaryStats.totalEvaluations}次\n`
  analysis += `- **整体平均分**: ${summaryStats.avgScore}分\n`
  analysis += `- **优秀供应商占比**: ${summaryStats.excellentRate}%\n\n`

  // 供应商表现分析
  if (supplierData.length > 0) {
    analysis += `### 🏆 供应商表现分析\n`

    // 排名前三的供应商
    const topThree = supplierData.slice(0, 3)
    analysis += `**排名前三的供应商**:\n`
    topThree.forEach((supplier, index) => {
      const medal = ['🥇', '🥈', '🥉'][index]
      analysis += `${medal} ${supplier.supplierName} - 综合评分: ${supplier.avgTotalScore}分 (${supplier.totalEvaluations}次评价)\n`
    })
    analysis += `\n`

    // 优秀供应商
    const excellentSuppliers = supplierData.filter(s => s.avgTotalScore >= 9)
    if (excellentSuppliers.length > 0) {
      analysis += `**优秀供应商** (评分≥9分): ${excellentSuppliers.length}家\n`
      excellentSuppliers.forEach(supplier => {
        analysis += `- ${supplier.supplierName}: ${supplier.avgTotalScore}分\n`
      })
      analysis += `\n`
    }

    // 需要关注的供应商
    const concernSuppliers = supplierData.filter(s => s.avgTotalScore < 7)
    if (concernSuppliers.length > 0) {
      analysis += `**需要关注的供应商** (评分<7分): ${concernSuppliers.length}家\n`
      concernSuppliers.forEach(supplier => {
        analysis += `- ${supplier.supplierName}: ${supplier.avgTotalScore}分\n`
      })
      analysis += `\n`
    }
  }

  // 评分维度分析
  if (supplierData.length > 0) {
    analysis += `### 📈 评分维度分析\n`

    const avgQuality = (supplierData.reduce((sum, s) => sum + s.avgQualityScore, 0) / supplierData.length).toFixed(1)
    const avgService = (supplierData.reduce((sum, s) => sum + s.avgServiceScore, 0) / supplierData.length).toFixed(1)
    const avgPrice = (supplierData.reduce((sum, s) => sum + s.avgPriceScore, 0) / supplierData.length).toFixed(1)
    const avgDelivery = (supplierData.reduce((sum, s) => sum + s.avgDeliveryScore, 0) / supplierData.length).toFixed(1)

    analysis += `- **质量评分平均**: ${avgQuality}分\n`
    analysis += `- **服务评分平均**: ${avgService}分\n`
    analysis += `- **价格评分平均**: ${avgPrice}分\n`
    analysis += `- **交付评分平均**: ${avgDelivery}分\n\n`

    // 找出表现最好和最差的维度
    const dimensions = [
      { name: '质量', score: parseFloat(avgQuality) },
      { name: '服务', score: parseFloat(avgService) },
      { name: '价格', score: parseFloat(avgPrice) },
      { name: '交付', score: parseFloat(avgDelivery) }
    ]

    dimensions.sort((a, b) => b.score - a.score)
    analysis += `**表现最好的维度**: ${dimensions[0].name} (${dimensions[0].score}分)\n`
    analysis += `**需要改进的维度**: ${dimensions[3].name} (${dimensions[3].score}分)\n\n`
  }

  // 趋势分析
  const upTrend = supplierData.filter(s => s.trend === 'up').length
  const downTrend = supplierData.filter(s => s.trend === 'down').length
  const stableTrend = supplierData.filter(s => s.trend === 'stable').length

  if (upTrend + downTrend + stableTrend > 0) {
    analysis += `### 📊 趋势分析\n`
    analysis += `- **上升趋势**: ${upTrend}家供应商\n`
    analysis += `- **下降趋势**: ${downTrend}家供应商\n`
    analysis += `- **稳定趋势**: ${stableTrend}家供应商\n\n`
  }

  // 建议
  analysis += `### 💡 建议\n`
  if (summaryStats.excellentRate < 30) {
    analysis += `- 优秀供应商占比较低(${summaryStats.excellentRate}%)，建议加强供应商培训和管理\n`
  }
  if (concernSuppliers && concernSuppliers.length > 0) {
    analysis += `- 有${concernSuppliers.length}家供应商评分偏低，建议进行重点改进\n`
  }
  if (downTrend > upTrend) {
    analysis += `- 下降趋势供应商较多，建议分析原因并采取改进措施\n`
  }
  analysis += `- 建议定期进行供应商评价，持续优化供应商管理体系\n`

  return analysis
}

// 暴露方法
defineExpose({ open })
</script>

<style lang="scss" scoped>
.mobile-summary-wrapper {
  padding: 0 4px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.mobile-summary-section {
  margin-bottom: 12px;
}
.mobile-summary-filter {
  display: flex;
  gap: 8px;
  align-items: center;
}
.mobile-summary-stats {
  display: flex;
  justify-content: space-around;
  background: #fff;
  border-radius: 10px;
  padding: 14px 8px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__item { text-align: center; }
  &__val { font-size: 18px; font-weight: 700; color: #303133; }
  &__label { font-size: 11px; color: #909399; margin-top: 2px; }
}
.mobile-summary-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-summary-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
  }
  &__rank-num {
    font-weight: 600;
    color: #909399;
    font-size: 14px;
    min-width: 20px;
    text-align: center;
  }
  &__name {
    flex: 1;
    font-weight: 600;
    font-size: 15px;
    color: #303133;
    display: flex;
    align-items: center;
  }
  &__total {
    font-size: 20px;
    font-weight: 700;
    flex-shrink: 0;
  }
  &__body {
    font-size: 13px;
  }
  &__row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
  }
  &__label {
    color: #909399;
    flex-shrink: 0;
  }
  &__value {
    color: #606266;
  }
  &__scores {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    padding: 8px 0;
    margin: 4px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
  }
  &__score-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  &__score-text {
    font-size: 12px;
    color: #606266;
  }
}
.score-excellent { color: #67c23a; }
.score-good { color: #409eff; }
.score-average { color: #e6a23c; }
.score-pass { color: #909399; }
.score-fail { color: #f56c6c; }
.trend-up { color: #67c23a; }
.trend-down { color: #f56c6c; }
.trend-stable { color: #909399; }
.mobile-form-footer {
  display: flex;
  gap: 12px;
}
.mobile-analysis-content {
  padding: 12px;
  background-color: #fafafa;
  border-radius: 6px;
  line-height: 1.6;
  font-size: 13px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
:deep(.mobile-summary-dialog .el-dialog__body) {
  padding: 12px;
  background: #f5f5f5;
}
:deep(.mobile-analysis-dialog .el-dialog__body) {
  padding: 12px;
  background: #f5f5f5;
}
:deep(.el-progress-bar__outer) {
  background-color: #f5f7fa;
}
</style>
