<template>
  <div class="mobile-dashboard">
    <!-- 筛选条件 -->
    <div class="mobile-dashboard-filter">
      <el-select v-model="queryParams.supplierId" clearable filterable placeholder="选择供应商" @change="getSupplierStats" size="small" style="flex:1">
        <el-option
          v-for="item in supplierList"
          :key="item.id"
          :label="item.name"
          :value="item.id" />
      </el-select>
      <el-button size="small" @click="getAllSuppliersStats">刷新</el-button>
    </div>

    <!-- 统计卡片 -->
    <div v-if="selectedSupplierStats" class="mobile-dashboard-stats">
      <div class="mobile-dashboard-stats__item">
        <div class="mobile-dashboard-stats__val">{{ selectedSupplierStats.totalEvaluations }}</div>
        <div class="mobile-dashboard-stats__label">总评价次数</div>
      </div>
      <div class="mobile-dashboard-stats__item">
        <div class="mobile-dashboard-stats__val" style="color:#409eff">{{ selectedSupplierStats.avgTotalScore }}</div>
        <div class="mobile-dashboard-stats__label">平均综合评分</div>
      </div>
      <div class="mobile-dashboard-stats__item">
        <div class="mobile-dashboard-stats__val" style="color:#67c23a">{{ selectedSupplierStats.avgQualityScore }}</div>
        <div class="mobile-dashboard-stats__label">平均质量评分</div>
      </div>
      <div class="mobile-dashboard-stats__item">
        <div class="mobile-dashboard-stats__val" style="color:#e6a23c">{{ selectedSupplierStats.avgServiceScore }}</div>
        <div class="mobile-dashboard-stats__label">平均服务评分</div>
      </div>
    </div>

    <!-- 供应商排行榜 -->
    <div class="mobile-dashboard-section">
      <div class="mobile-dashboard-section__title">综合评分排行榜 (TOP 10)</div>
      <div class="mobile-ranking-list">
        <div v-for="(item, index) in topSuppliers" :key="item.supplierId" class="mobile-ranking-item">
          <div class="mobile-ranking-item__rank">
            <el-tag v-if="index < 3" :type="getRankingTagType(index)" size="small">{{ index + 1 }}</el-tag>
            <span v-else class="mobile-ranking-item__rank-num">{{ index + 1 }}</span>
          </div>
          <div class="mobile-ranking-item__info">
            <div class="mobile-ranking-item__name">{{ item.supplierName }}</div>
            <div class="mobile-ranking-item__meta">{{ item.totalEvaluations }}次评价</div>
          </div>
          <div class="mobile-ranking-item__score">
            <div class="mobile-ranking-item__score-val">{{ item.avgTotalScore }}</div>
            <el-tag :type="getScoreTagType(item.avgTotalScore)" size="small">
              {{ getScoreLevel(item.avgTotalScore) }}
            </el-tag>
          </div>
        </div>
        <div v-if="topSuppliers.length === 0" style="padding:30px 0; text-align:center">
          <el-empty description="暂无排行数据" :image-size="60" />
        </div>
      </div>
    </div>

    <!-- 评分分布统计 -->
    <div class="mobile-dashboard-section">
      <div class="mobile-dashboard-section__title">评分分布统计</div>
      <div class="mobile-distribution">
        <div class="mobile-distribution__item">
          <div class="mobile-distribution__header">
            <span class="mobile-distribution__label">优秀 (9-10)</span>
            <span class="mobile-distribution__count">{{ excellentCount }} 个</span>
          </div>
          <el-progress :percentage="scoreDistribution.excellent" color="#67c23a" :stroke-width="10" />
        </div>
        <div class="mobile-distribution__item">
          <div class="mobile-distribution__header">
            <span class="mobile-distribution__label">良好 (8-8.9)</span>
            <span class="mobile-distribution__count">{{ goodCount }} 个</span>
          </div>
          <el-progress :percentage="scoreDistribution.good" color="#409eff" :stroke-width="10" />
        </div>
        <div class="mobile-distribution__item">
          <div class="mobile-distribution__header">
            <span class="mobile-distribution__label">一般 (7-7.9)</span>
            <span class="mobile-distribution__count">{{ averageCount }} 个</span>
          </div>
          <el-progress :percentage="scoreDistribution.average" color="#e6a23c" :stroke-width="10" />
        </div>
        <div class="mobile-distribution__item">
          <div class="mobile-distribution__header">
            <span class="mobile-distribution__label">及格 (6-6.9)</span>
            <span class="mobile-distribution__count">{{ passCount }} 个</span>
          </div>
          <el-progress :percentage="scoreDistribution.pass" color="#909399" :stroke-width="10" />
        </div>
        <div class="mobile-distribution__item">
          <div class="mobile-distribution__header">
            <span class="mobile-distribution__label">不及格 (&lt;6)</span>
            <span class="mobile-distribution__count">{{ failCount }} 个</span>
          </div>
          <el-progress :percentage="scoreDistribution.fail" color="#f56c6c" :stroke-width="10" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { SupplierEvaluationApi } from '@/api/erp/purchase/supplierEvaluation'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'

/** 供应商评分统计仪表板 */
defineOptions({ name: 'SupplierScoreDashboard' })

const loading = ref(false)
const supplierList = ref<SupplierVO[]>([])
const allSuppliersStats = ref([])
const selectedSupplierStats = ref(null)
const topSuppliers = ref([])

const queryParams = reactive({
  supplierId: undefined
})

// 评分分布统计
const scoreDistribution = ref({
  excellent: 0,
  good: 0,
  average: 0,
  pass: 0,
  fail: 0
})

const excellentCount = ref(0)
const goodCount = ref(0)
const averageCount = ref(0)
const passCount = ref(0)
const failCount = ref(0)

// 获取所有供应商统计
const getAllSuppliersStats = async () => {
  loading.value = true
  try {
    const suppliers = await SupplierApi.getSupplierSimpleList()
    const statsPromises = suppliers.map(async (supplier) => {
      try {
        const stats = await SupplierEvaluationApi.getSupplierAverageScore(supplier.id)
        return stats ? { ...stats, supplierName: supplier.name } : null
      } catch (error) {
        return null
      }
    })

    const results = await Promise.all(statsPromises)
    allSuppliersStats.value = results.filter(item => item && item.totalEvaluations > 0)

    // 计算排行榜
    topSuppliers.value = allSuppliersStats.value
      .sort((a, b) => b.avgTotalScore - a.avgTotalScore)
      .slice(0, 10)

    // 计算评分分布
    calculateScoreDistribution()
  } finally {
    loading.value = false
  }
}

// 获取单个供应商统计
const getSupplierStats = async () => {
  if (!queryParams.supplierId) {
    selectedSupplierStats.value = null
    return
  }

  try {
    const stats = await SupplierEvaluationApi.getSupplierAverageScore(queryParams.supplierId)
    const supplier = supplierList.value.find(s => s.id === queryParams.supplierId)
    selectedSupplierStats.value = stats ? { ...stats, supplierName: supplier?.name } : null
  } catch (error) {
    selectedSupplierStats.value = null
  }
}

// 计算评分分布
const calculateScoreDistribution = () => {
  const total = allSuppliersStats.value.length
  if (total === 0) return

  excellentCount.value = allSuppliersStats.value.filter(item => item.avgTotalScore >= 9.0).length
  goodCount.value = allSuppliersStats.value.filter(item => item.avgTotalScore >= 8.0 && item.avgTotalScore < 9.0).length
  averageCount.value = allSuppliersStats.value.filter(item => item.avgTotalScore >= 7.0 && item.avgTotalScore < 8.0).length
  passCount.value = allSuppliersStats.value.filter(item => item.avgTotalScore >= 6.0 && item.avgTotalScore < 7.0).length
  failCount.value = allSuppliersStats.value.filter(item => item.avgTotalScore < 6.0).length

  scoreDistribution.value = {
    excellent: Math.round((excellentCount.value / total) * 100),
    good: Math.round((goodCount.value / total) * 100),
    average: Math.round((averageCount.value / total) * 100),
    pass: Math.round((passCount.value / total) * 100),
    fail: Math.round((failCount.value / total) * 100)
  }
}

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

// 获取评分标签类型
const getScoreTagType = (score: number) => {
  if (score >= 9) return 'success'
  if (score >= 8) return ''
  if (score >= 7) return 'warning'
  if (score >= 6) return 'info'
  return 'danger'
}

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

/** 初始化 **/
onMounted(async () => {
  // 加载供应商列表
  supplierList.value = await SupplierApi.getSupplierSimpleList()
  // 获取统计数据
  await getAllSuppliersStats()
})
</script>

<style lang="scss" scoped>
.mobile-dashboard {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}
.mobile-dashboard-filter {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}
.mobile-dashboard-stats {
  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: 20px; font-weight: 700; color: #303133; }
  &__label { font-size: 11px; color: #909399; margin-top: 2px; }
}
.mobile-dashboard-section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}
.mobile-ranking-list {
  display: flex;
  flex-direction: column;
}
.mobile-ranking-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
  &:last-child { border-bottom: none; }
  &__rank {
    min-width: 28px;
    text-align: center;
  }
  &__rank-num {
    font-weight: 600;
    color: #909399;
    font-size: 14px;
  }
  &__info {
    flex: 1;
    min-width: 0;
  }
  &__name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &__meta {
    font-size: 11px;
    color: #909399;
    margin-top: 2px;
  }
  &__score {
    text-align: right;
    flex-shrink: 0;
  }
  &__score-val {
    font-size: 18px;
    font-weight: 700;
    color: #409eff;
    margin-bottom: 2px;
  }
}
.mobile-distribution {
  display: flex;
  flex-direction: column;
  gap: 14px;
  &__item { }
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
  }
  &__label {
    font-size: 13px;
    color: #606266;
  }
  &__count {
    font-size: 12px;
    color: #909399;
  }
}
:deep(.el-progress-bar__outer) {
  background-color: #f5f7fa;
}
</style>
