<template>
  <div class="reliability-assessment-container">
    <!-- 顶部操作区 -->
    <div class="top-section">
      <div class="project-selection">
        <a-select 
          v-model="selectedProject" 
          placeholder="选择项目"
          style="width: 200px"
          @change="handleProjectChange"
        >
          <a-option 
            v-for="project in projectOptions" 
            :key="project.value" 
            :value="project.value"
          >
            {{ project.label }}
          </a-option>
        </a-select>
      </div>
      
      <div class="action-buttons">
        <a-button 
          type="primary"
          @click="generateReport"
          :loading="generating"
        >
          <template #icon><icon-file-add /></template>
          生成评估报告
        </a-button>
      </div>
    </div>

    <!-- 机组可靠性评分图表 -->
    <div class="chart-section">
      <a-card title="机组可靠性评分" :bordered="false">
        <div ref="chartContainer" class="chart-container"></div>
      </a-card>
    </div>

    <!-- 评估结果表格 -->
    <div class="result-section">
      <a-card title="评估结果" :bordered="false">
        <a-table 
          :data="assessmentData"
          :columns="columns"
          :pagination="false"
          size="medium"
        >
          <template #reliability-score="{ record }">
            <span class="score-text" :class="getScoreClass(record.reliabilityScore)">
              {{ record.reliabilityScore }} 分
            </span>
          </template>
          
          <template #severity="{ record }">
            <a-tag :color="getSeverityColor(record.severity)">
              {{ record.severity }}
            </a-tag>
          </template>
          
          <template #maintenance-suggestion="{ record }">
            <div class="suggestion-text">
              {{ record.maintenanceSuggestion }}
            </div>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <a-space>
        <a-button 
          type="primary"
          @click="exportReport"
          :loading="exporting"
        >
          <template #icon><icon-download /></template>
          导出评估报告
        </a-button>
        
        <a-button @click="printReport">
          <template #icon><icon-printer /></template>
          打印
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { Message } from '@arco-design/web-vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'

defineOptions({ name: 'ReliabilityAssessment' })

// 响应式数据
const selectedProject = ref('A风场2023年检查')
const generating = ref(false)
const exporting = ref(false)
const chartContainer = ref<HTMLElement>()
let chartInstance: ECharts | null = null

// 项目选项
const projectOptions = ref([
  { label: 'A风场2023年检查', value: 'A风场2023年检查' },
  { label: 'B风场维修项目', value: 'B风场维修项目' },
  { label: 'C风场年度检查', value: 'C风场年度检查' },
  { label: 'D风场初步检查', value: 'D风场初步检查' }
])

// 评估数据
const assessmentData = ref([
  {
    unitCode: 'A-001',
    reliabilityScore: 85,
    defectCount: 2,
    severity: '中',
    maintenanceSuggestion: '建议在下次停机时对维修前端频障'
  },
  {
    unitCode: 'A-002',
    reliabilityScore: 90,
    defectCount: 1,
    severity: '低',
    maintenanceSuggestion: '持续观察后续开裂情况'
  },
  {
    unitCode: 'A-003',
    reliabilityScore: 95,
    defectCount: 0,
    severity: '无',
    maintenanceSuggestion: '机组状况良好，无需特别处理'
  }
])

// 表格列配置
const columns = [
  {
    title: '机组编号',
    dataIndex: 'unitCode',
    width: 120
  },
  {
    title: '可靠性评分',
    dataIndex: 'reliabilityScore',
    slotName: 'reliability-score',
    width: 150
  },
  {
    title: '缺陷数量',
    dataIndex: 'defectCount',
    width: 120
  },
  {
    title: '严重程度',
    dataIndex: 'severity',
    slotName: 'severity',
    width: 120
  },
  {
    title: '维护建议',
    dataIndex: 'maintenanceSuggestion',
    slotName: 'maintenance-suggestion'
  }
]

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  chartInstance = echarts.init(chartContainer.value)
  
  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value} 分'
      }
    },
    yAxis: {
      type: 'category',
      data: ['A-001', 'A-002', 'A-003'],
      axisLabel: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '可靠性评分',
        type: 'bar',
        data: [
          { value: 85, itemStyle: { color: '#3b82f6' } },
          { value: 90, itemStyle: { color: '#10b981' } },
          { value: 95, itemStyle: { color: '#10b981' } }
        ],
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 分',
          fontSize: 12
        },
        barWidth: 30
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        const data = params[0]
        return `${data.name}: ${data.value} 分`
      }
    }
  }
  
  chartInstance.setOption(option)
}

// 项目变更处理
const handleProjectChange = (value: string) => {
  Message.info(`切换到项目: ${value}`)
  // 这里可以根据项目重新加载数据
  loadAssessmentData(value)
}

// 加载评估数据
const loadAssessmentData = (projectId: string) => {
  // 模拟加载数据
  console.log(`Loading assessment data for project: ${projectId}`)
}

// 生成报告
const generateReport = async () => {
  generating.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))
    Message.success('评估报告生成成功')
  } catch (error) {
    Message.error('生成报告失败')
  } finally {
    generating.value = false
  }
}

// 导出报告
const exportReport = async () => {
  exporting.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1500))
    Message.success('报告导出成功')
  } catch (error) {
    Message.error('导出报告失败')
  } finally {
    exporting.value = false
  }
}

// 打印报告
const printReport = () => {
  window.print()
}

// 获取分数样式类
const getScoreClass = (score: number) => {
  if (score >= 90) return 'score-high'
  if (score >= 80) return 'score-medium'
  return 'score-low'
}

// 获取严重程度颜色
const getSeverityColor = (severity: string) => {
  switch (severity) {
    case '高': return 'red'
    case '中': return 'orange'
    case '低': return 'green'
    case '无': return 'gray'
    default: return 'gray'
  }
}

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件销毁时清理图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style scoped lang="scss">
.reliability-assessment-container {
  padding: 20px;
  
  .top-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .project-selection {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .action-buttons {
      display: flex;
      gap: 12px;
    }
  }
  
  .chart-section {
    margin-bottom: 20px;
    
    .chart-container {
      height: 300px;
      width: 100%;
    }
  }
  
  .result-section {
    margin-bottom: 20px;
    
    .score-text {
      font-weight: 600;
      
      &.score-high {
        color: #10b981;
      }
      
      &.score-medium {
        color: #3b82f6;
      }
      
      &.score-low {
        color: #f59e0b;
      }
    }
    
    .suggestion-text {
      color: #6b7280;
      line-height: 1.5;
    }
  }
  
  .bottom-actions {
    display: flex;
    justify-content: flex-start;
    padding: 20px 0;
  }
}

:deep(.arco-card-header) {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

:deep(.arco-table-th) {
  background-color: #f9fafb;
  color: #374151;
  font-weight: 600;
}

:deep(.arco-table-td) {
  padding: 12px 16px;
}
</style>
