<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="100%" fullscreen class="mobile-history-dialog">
    <div v-loading="loading" class="mobile-history-wrapper">
      <!-- 筛选条件 -->
      <div class="mobile-history-filter">
        <el-select v-model="queryParams.scoreRange" placeholder="评分范围" clearable @change="loadHistoryData" size="small" style="flex:1">
          <el-option label="优秀 (9-10)" value="excellent" />
          <el-option label="良好 (8-8.9)" value="good" />
          <el-option label="一般 (7-7.9)" value="average" />
          <el-option label="及格 (6-6.9)" value="pass" />
          <el-option label="不及格 (<6)" value="fail" />
        </el-select>
        <el-button size="small" @click="loadHistoryData" :loading="loading">刷新</el-button>
      </div>

      <!-- 统计信息 -->
      <div class="mobile-history-stats">
        <div class="mobile-history-stats__item">
          <div class="mobile-history-stats__val">{{ historyStats.totalCount }}</div>
          <div class="mobile-history-stats__label">总评价次数</div>
        </div>
        <div class="mobile-history-stats__item">
          <div class="mobile-history-stats__val" style="color:#409eff">{{ historyStats.avgScore }}</div>
          <div class="mobile-history-stats__label">平均评分</div>
        </div>
        <div class="mobile-history-stats__item">
          <div class="mobile-history-stats__val" style="color:#67c23a">{{ historyStats.bestScore }}</div>
          <div class="mobile-history-stats__label">最高评分</div>
        </div>
        <div class="mobile-history-stats__item">
          <div class="mobile-history-stats__val" style="color:#e6a23c">{{ historyStats.recentTrend }}</div>
          <div class="mobile-history-stats__label">近期趋势</div>
        </div>
      </div>

      <!-- 评价历史卡片列表 -->
      <div class="mobile-history-list">
        <div v-if="historyList.length === 0 && !loading" style="padding:40px 0">
          <el-empty description="暂无评价历史" />
        </div>
        <div v-for="item in historyList" :key="item.id" class="mobile-history-card" @click="viewEvaluationDetail(item)">
          <div class="mobile-history-card__header">
            <span class="mobile-history-card__order">{{ item.orderNo }}</span>
            <el-tag :type="getScoreTagType(item.totalScore)" size="small">
              {{ item.totalScore }}分 · {{ getScoreLevel(item.totalScore) }}
            </el-tag>
          </div>
          <div class="mobile-history-card__scores">
            <div class="mobile-history-card__score-item">
              <el-progress :percentage="(item.qualityScore / 10) * 100" :color="getProgressColor(item.qualityScore)" :show-text="false" :stroke-width="6" />
              <span>质量 {{ item.qualityScore }}</span>
            </div>
            <div class="mobile-history-card__score-item">
              <el-progress :percentage="(item.serviceScore / 10) * 100" :color="getProgressColor(item.serviceScore)" :show-text="false" :stroke-width="6" />
              <span>服务 {{ item.serviceScore }}</span>
            </div>
            <div class="mobile-history-card__score-item">
              <el-progress :percentage="(item.priceScore / 10) * 100" :color="getProgressColor(item.priceScore)" :show-text="false" :stroke-width="6" />
              <span>价格 {{ item.priceScore }}</span>
            </div>
            <div class="mobile-history-card__score-item">
              <el-progress :percentage="(item.deliveryScore / 10) * 100" :color="getProgressColor(item.deliveryScore)" :show-text="false" :stroke-width="6" />
              <span>交付 {{ item.deliveryScore }}</span>
            </div>
          </div>
          <div class="mobile-history-card__footer">
            <span class="mobile-history-card__meta">{{ formatDate(item.createTime) }} · {{ item.creatorName }}</span>
            <span class="mobile-history-card__remark">{{ item.remark || '无备注' }}</span>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mobile-pagination" v-if="total > 0">
        <el-pagination v-model:current-page="queryParams.pageNo" v-model:page-size="queryParams.pageSize" :total="total" :page-sizes="[10, 20]" layout="total, prev, pager, next" :pager-count="5" @size-change="loadHistoryData" @current-change="loadHistoryData" />
      </div>
    </div>

    <template #footer>
      <div class="mobile-form-footer">
        <el-button @click="dialogVisible = false" style="flex:1">关闭</el-button>
        <el-button type="primary" @click="generateReport" style="flex:1">生成报告</el-button>
      </div>
    </template>
  </Dialog>

  <!-- 评价详情弹窗 -->
  <SupplierEvaluationDetail ref="evaluationDetailRef" />
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { SupplierEvaluationApi } from '@/api/erp/purchase/supplierEvaluation'
import SupplierEvaluationDetail from './SupplierEvaluationDetail.vue'

interface EvaluationHistory {
  id: number
  orderId: number
  orderNo: string
  totalScore: number
  qualityScore: number
  serviceScore: number
  priceScore: number
  deliveryScore: number
  remark: string
  createTime: string
  creatorName: string
}

const dialogVisible = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const dialogTitle = ref('')
const supplierId = ref(0)
const supplierName = ref('')
const historyList = ref<EvaluationHistory[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  dateRange: [],
  scoreRange: undefined
})

const historyStats = ref({
  totalCount: 0,
  avgScore: '0.0',
  bestScore: '0.0',
  recentTrend: '稳定'
})

// 打开历史弹窗
const open = async (id: number, name: string) => {
  dialogVisible.value = true
  supplierId.value = id
  supplierName.value = name
  dialogTitle.value = `${name} - 评价历史`
  
  // 重置查询参数
  queryParams.pageNo = 1
  queryParams.dateRange = []
  queryParams.scoreRange = undefined
  
  await loadHistoryData()
}

// 加载历史数据
const loadHistoryData = async () => {
  loading.value = true
  try {
    // 模拟API调用 - 实际应该调用后端API
    const mockData = await generateMockHistoryData()
    historyList.value = mockData.list
    total.value = mockData.total
    historyStats.value = mockData.stats
  } catch (error) {
    console.error('加载历史数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 生成模拟历史数据
const generateMockHistoryData = async () => {
  const count = Math.floor(Math.random() * 30) + 10
  const list: EvaluationHistory[] = []
  
  for (let i = 0; i < Math.min(count, queryParams.pageSize); i++) {
    const totalScore = Number((Math.random() * 4 + 6).toFixed(1))
    list.push({
      id: i + 1,
      orderId: 1000 + i,
      orderNo: `PO${String(1000 + i).padStart(6, '0')}`,
      totalScore,
      qualityScore: Number((Math.random() * 3 + 7).toFixed(1)),
      serviceScore: Number((Math.random() * 3 + 7).toFixed(1)),
      priceScore: Number((Math.random() * 3 + 7).toFixed(1)),
      deliveryScore: Number((Math.random() * 3 + 7).toFixed(1)),
      remark: Math.random() > 0.5 ? '服务态度很好，产品质量符合要求' : '',
      createTime: new Date(Date.now() - Math.random() * 180 * 24 * 60 * 60 * 1000).toISOString(),
      creatorName: ['张三', '李四', '王五', '赵六'][Math.floor(Math.random() * 4)]
    })
  }
  
  // 按时间排序
  list.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
  
  const totalCount = count
  const avgScore = (list.reduce((sum, item) => sum + item.totalScore, 0) / list.length).toFixed(1)
  const bestScore = Math.max(...list.map(item => item.totalScore)).toFixed(1)
  const recentTrend = ['上升', '下降', '稳定'][Math.floor(Math.random() * 3)]
  
  return {
    list,
    total: totalCount,
    stats: {
      totalCount,
      avgScore,
      bestScore,
      recentTrend
    }
  }
}

// 导出历史数据
const exportHistory = async () => {
  exportLoading.value = true
  try {
    // 这里应该调用实际的导出API
    console.log('导出历史数据:', historyList.value)
  } finally {
    exportLoading.value = false
  }
}

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  // 这里可以跳转到订单详情页面或打开订单详情弹窗
  console.log('查看订单详情:', orderId)
}

// 查看评价详情
const evaluationDetailRef = ref()
const viewEvaluationDetail = (row: EvaluationHistory) => {
  const evaluationData = {
    ...row,
    supplierName: supplierName.value
  }
  evaluationDetailRef.value.open(evaluationData)
}

// 对比评价
const compareEvaluation = (row: EvaluationHistory) => {
  // 这里可以实现评价对比功能
  console.log('对比评价:', row)
}

// 生成评价报告
const generateReport = () => {
  // 这里可以生成PDF报告或其他格式的报告
  console.log('生成评价报告')
}

// 获取评分标签类型
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 '不及格'
}

// 获取评分样式类
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'
}

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

<style lang="scss" scoped>
.mobile-history-wrapper {
  padding: 0 4px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.mobile-history-filter {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}
.mobile-history-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-history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-history-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  &__order {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
  }
  &__scores {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    padding: 8px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    color: #606266;
  }
  &__score-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  &__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
    font-size: 12px;
  }
  &__meta {
    color: #909399;
  }
  &__remark {
    color: #c0c4cc;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 50%;
    text-align: right;
  }
}
.mobile-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  :deep(.el-pagination) { flex-wrap: wrap; justify-content: center; }
}
.mobile-form-footer {
  display: flex;
  gap: 12px;
}
:deep(.mobile-history-dialog .el-dialog__body) {
  padding: 12px;
  background: #f5f5f5;
}
:deep(.el-progress-bar__outer) {
  background-color: #f5f7fa;
}
</style>
