<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <div class="filter-section">
      <el-card>
        <div class="filter-container">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
            <el-form-item label="考核月份" prop="assessmentMonth">
              <el-date-picker v-model="queryParams.assessmentMonth" type="month" placeholder="请选择考核月份" 
                value-format="YYYY-MM" style="width: 200px" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          
          <div class="export-button">
            <el-button type="warning" icon="Document" @click="handleExport">导出文档</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 非干部月度考核分数汇总 -->
    <div class="main-section">
      <h2 class="section-title">非干部月度考核分数汇总</h2>
      
      <!-- 第一行：两个区块 -->
      <div class="chart-row">
        <!-- 整体分支分布柱状图 -->
        <el-card class="chart-card">
          <div class="chart-header">整体分支分布柱状图</div>
          <div ref="overallBarChart" class="chart-container"></div>
        </el-card>
        
        <!-- 参与人数占比饼图 -->
        <el-card class="chart-card">
          <div class="chart-header">参与人数占比饼图</div>
          <div ref="participantPieChart" class="chart-container"></div>
        </el-card>
      </div>

      <!-- 第二行：两个区块 -->
      <div class="chart-row">
        <!-- 各部门分支分布对比图 -->
        <el-card class="chart-card">
          <div class="chart-header">各部门分支分布对比图</div>
          <div ref="departmentComparisonChart" class="chart-container"></div>
        </el-card>
        
        <!-- 汇总表 -->
        <el-card class="chart-card">
          <div class="chart-header">汇总表</div>
          <el-table :data="summaryTableData" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="range" label="区间" align="center" min-width="100" />
            <el-table-column prop="simulationScore" label="2026年1月模拟分数汇总" align="center" min-width="150" />
            <el-table-column prop="team1" label="一队" align="center" min-width="100" />
            <el-table-column prop="team2" label="二队" align="center" min-width="100" />
            <el-table-column prop="team3" label="三队" align="center" min-width="100" />
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 非干部月度考核分类结果汇总 -->
    <div class="main-section">
      <h2 class="section-title">非干部月度考核分类结果汇总</h2>
      
      <!-- 汇总统计表格 -->
      <el-card class="summary-table-card">
        <div class="chart-header">汇总统计</div>
        <el-table :data="classificationTableData" border style="width: 100%; margin-top: 10px;">
          <el-table-column prop="assessmentGroup" label="考核组人数" align="center" min-width="120" />
          <el-table-column prop="calculatedImprovement" label="测算待改进人数" align="center" min-width="140" />
          <el-table-column prop="totalImprovement" label="待改进总人数" align="center" min-width="120" />
          <el-table-column prop="exemption1" label="豁免" align="center" min-width="80" />
          <el-table-column prop="actualImprovement" label="实际待改进总人数" align="center" min-width="140" />
          <el-table-column prop="totalUnqualified" label="不称职总人数" align="center" min-width="120" />
          <el-table-column prop="exemption2" label="豁免" align="center" min-width="80" />
          <el-table-column prop="actualUnqualified" label="实际不称职人数" align="center" min-width="140" />
        </el-table>
      </el-card>

      <!-- 第四行：两个区块 -->
      <div class="chart-row">
        <!-- 大队分布统计图 -->
        <el-card class="chart-card">
          <div class="chart-header">大队分布统计图</div>
          <div class="pie-charts-container">
            <div ref="brigadePieChart1" class="pie-chart"></div>
            <div ref="brigadePieChart2" class="pie-chart"></div>
          </div>
        </el-card>
        
        <!-- 岗位分布统计图 -->
        <el-card class="chart-card">
          <div class="chart-header">岗位分布统计图</div>
          <div class="pie-charts-container">
            <div ref="positionPieChart1" class="pie-chart"></div>
            <div ref="positionPieChart2" class="pie-chart"></div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 第一个遍历：表格和两个饼状图 -->
    <div class="traversal-section">
      <div v-for="(item, index) in traversalData1" :key="index" class="traversal-container">
        <div class="traversal-header">{{ item.title }}</div>
        <div class="traversal-content">
          <!-- 左边表格 -->
          <div class="table-section">
            <el-table :data="item.tableData" border style="width: 100%;">
              <el-table-column prop="brigade" label="大队" align="center" min-width="100" />
              <el-table-column prop="assessmentGroup" label="考核组" align="center" min-width="100" />
              <el-table-column prop="groupCount" label="考核组人数" align="center" min-width="120" />
              <el-table-column prop="calculatedImprovement" label="测算待改进人数" align="center" min-width="140" />
              <el-table-column prop="improvementCount" label="待改进人数" align="center" min-width="120" />
              <el-table-column prop="exemption1" label="豁免" align="center" min-width="80" />
              <el-table-column prop="actualImprovement" label="实际待改进人数" align="center" min-width="140" />
              <el-table-column prop="unqualifiedCount" label="不称职人数" align="center" min-width="120" />
              <el-table-column prop="exemption2" label="豁免" align="center" min-width="80" />
              <el-table-column prop="actualUnqualified" label="实际不称职人数" align="center" min-width="140" />
            </el-table>
          </div>
          
          <!-- 右边两个饼状图 -->
          <div class="chart-section">
            <div class="pie-chart-container">
              <div class="pie-chart-title">考核结果分布</div>
              <div :ref="el => setTraversalChartRef(el, `pieChart1_${index}`)" class="pie-chart"></div>
            </div>
            <div class="pie-chart-container">
              <div class="pie-chart-title">改进情况分布</div>
              <div :ref="el => setTraversalChartRef(el, `pieChart2_${index}`)" class="pie-chart"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第二个遍历：表格、柱状图和饼状图 -->
    <div class="traversal-section">
      <div v-for="(item, index) in traversalData2" :key="index" class="traversal-container">
        <div class="traversal-header">{{ item.title }}</div>
        <div class="traversal-content">
          <!-- 左边表格 -->
          <div class="table-section">
            <el-table :data="item.tableData" border style="width: 100%;">
              <el-table-column prop="brigade" label="大队" align="center" min-width="100" />
              <el-table-column prop="assessmentGroup" label="考核组" align="center" min-width="100" />
              <el-table-column prop="groupCount" label="考核组人数" align="center" min-width="120" />
              <el-table-column prop="calculatedImprovement" label="测算待改进人数" align="center" min-width="140" />
              <el-table-column prop="improvementCount" label="待改进人数" align="center" min-width="120" />
              <el-table-column prop="exemption1" label="豁免" align="center" min-width="80" />
              <el-table-column prop="actualImprovement" label="实际待改进人数" align="center" min-width="140" />
              <el-table-column prop="unqualifiedCount" label="不称职人数" align="center" min-width="120" />
              <el-table-column prop="exemption2" label="豁免" align="center" min-width="80" />
              <el-table-column prop="actualUnqualified" label="实际不称职人数" align="center" min-width="140" />
            </el-table>
          </div>
          
          <!-- 右边柱状图和饼状图 -->
          <div class="chart-section">
            <div class="bar-chart-container">
              <div class="chart-title">考核分数分布</div>
              <div :ref="el => setTraversalChartRef(el, `barChart_${index}`)" class="bar-chart"></div>
            </div>
            <div class="pie-chart-container">
              <div class="pie-chart-title">岗位分布</div>
              <div :ref="el => setTraversalChartRef(el, `pieChart3_${index}`)" class="pie-chart"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// API导入
import { getNonCadreMonthlyScoreSum } from '@/api/performance/nonCadreMonthlyScoreSum.js'

// 响应式数据
const loading = ref(false)
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  assessmentMonth: ''
})

// 图表引用
const overallBarChart = ref(null)
const participantPieChart = ref(null)
const departmentComparisonChart = ref(null)
const brigadePieChart1 = ref(null)
const brigadePieChart2 = ref(null)
const positionPieChart1 = ref(null)
const positionPieChart2 = ref(null)

// 遍历图表引用
const traversalChartsRefs = ref({})

// 表格数据
const summaryTableData = ref([
  { range: '90-100分', simulationScore: '85', team1: '15', team2: '20', team3: '25' },
  { range: '80-89分', simulationScore: '120', team1: '30', team2: '35', team3: '40' },
  { range: '70-79分', simulationScore: '95', team1: '25', team2: '30', team3: '35' },
  { range: '60-69分', simulationScore: '60', team1: '15', team2: '20', team3: '25' },
  { range: '60分以下', simulationScore: '20', team1: '5', team2: '8', team3: '7' }
])

const classificationTableData = ref([
  { 
    assessmentGroup: '100', 
    calculatedImprovement: '15', 
    totalImprovement: '12', 
    exemption1: '2', 
    actualImprovement: '10', 
    totalUnqualified: '5', 
    exemption2: '1', 
    actualUnqualified: '4'
  }
])

// 遍历数据
const traversalData1 = ref([
  {
    title: '大队考核统计',
    tableData: [
      { brigade: '一大队', assessmentGroup: '一组', groupCount: 50, calculatedImprovement: 8, improvementCount: 6, exemption1: 1, actualImprovement: 5, unqualifiedCount: 2, exemption2: 0, actualUnqualified: 2 },
      { brigade: '一大队', assessmentGroup: '二组', groupCount: 45, calculatedImprovement: 7, improvementCount: 5, exemption1: 1, actualImprovement: 4, unqualifiedCount: 1, exemption2: 0, actualUnqualified: 1 },
      { brigade: '二大队', assessmentGroup: '一组', groupCount: 55, calculatedImprovement: 9, improvementCount: 7, exemption1: 1, actualImprovement: 6, unqualifiedCount: 3, exemption2: 1, actualUnqualified: 2 },
      { brigade: '二大队', assessmentGroup: '二组', groupCount: 48, calculatedImprovement: 6, improvementCount: 5, exemption1: 0, actualImprovement: 5, unqualifiedCount: 2, exemption2: 0, actualUnqualified: 2 }
    ]
  }
])

const traversalData2 = ref([
  {
    title: '岗位考核统计',
    tableData: [
      { brigade: '安检员', assessmentGroup: '一组', groupCount: 60, calculatedImprovement: 10, improvementCount: 8, exemption1: 1, actualImprovement: 7, unqualifiedCount: 3, exemption2: 0, actualUnqualified: 3 },
      { brigade: '安检员', assessmentGroup: '二组', groupCount: 55, calculatedImprovement: 8, improvementCount: 6, exemption1: 1, actualImprovement: 5, unqualifiedCount: 2, exemption2: 0, actualUnqualified: 2 },
      { brigade: '设备操作员', assessmentGroup: '一组', groupCount: 40, calculatedImprovement: 5, improvementCount: 4, exemption1: 0, actualImprovement: 4, unqualifiedCount: 1, exemption2: 0, actualUnqualified: 1 }
    ]
  }
])

// 图表实例
let overallBarChartInstance = null
let participantPieChartInstance = null
let departmentComparisonChartInstance = null
let brigadePieChart1Instance = null
let brigadePieChart2Instance = null
let positionPieChart1Instance = null
let positionPieChart2Instance = null

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 整体分支分布柱状图
    if (overallBarChart.value) {
      overallBarChartInstance = echarts.init(overallBarChart.value)
      overallBarChartInstance.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: ['90-100分', '80-89分', '70-79分', '60-69分', '60分以下'] },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: [85, 120, 95, 60, 20], itemStyle: { color: '#3b82f6' } }]
      })
    }

    // 参与人数占比饼图
    if (participantPieChart.value) {
      participantPieChartInstance = echarts.init(participantPieChart.value)
      participantPieChartInstance.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '70%',
          data: [
            { value: 380, name: '参与考核' },
            { value: 20, name: '未参与考核' }
          ]
        }]
      })
    }

    // 各部门分支分布对比图
    if (departmentComparisonChart.value) {
      departmentComparisonChartInstance = echarts.init(departmentComparisonChart.value)
      departmentComparisonChartInstance.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['一队', '二队', '三队'] },
        xAxis: { type: 'category', data: ['90-100分', '80-89分', '70-79分', '60-69分', '60分以下'] },
        yAxis: { type: 'value' },
        series: [
          { name: '一队', type: 'bar', data: [15, 30, 25, 15, 5] },
          { name: '二队', type: 'bar', data: [20, 35, 30, 20, 8] },
          { name: '三队', type: 'bar', data: [25, 40, 35, 25, 7] }
        ]
      })
    }

    // 大队分布饼图1
    if (brigadePieChart1.value) {
      brigadePieChart1Instance = echarts.init(brigadePieChart1.value)
      brigadePieChart1Instance.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '70%',
          data: [
            { value: 120, name: '一队' },
            { value: 150, name: '二队' },
            { value: 130, name: '三队' }
          ]
        }]
      })
    }

    // 大队分布饼图2
    if (brigadePieChart2.value) {
      brigadePieChart2Instance = echarts.init(brigadePieChart2.value)
      brigadePieChart2Instance.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '70%',
          data: [
            { value: 45, name: '优秀' },
            { value: 280, name: '合格' },
            { value: 75, name: '待改进' }
          ]
        }]
      })
    }

    // 岗位分布饼图1
    if (positionPieChart1.value) {
      positionPieChart1Instance = echarts.init(positionPieChart1.value)
      positionPieChart1Instance.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '70%',
          data: [
            { value: 150, name: '安检员' },
            { value: 120, name: '设备操作员' },
            { value: 80, name: '管理人员' },
            { value: 50, name: '其他' }
          ]
        }]
      })
    }

    // 岗位分布饼图2
    if (positionPieChart2.value) {
      positionPieChart2Instance = echarts.init(positionPieChart2.value)
      positionPieChart2Instance.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '70%',
          data: [
            { value: 35, name: '优秀' },
            { value: 320, name: '合格' },
            { value: 45, name: '待改进' }
          ]
        }]
      })
    }
  })
}

// 设置遍历图表引用
const setTraversalChartRef = (el, key) => {
  if (el) {
    traversalChartsRefs.value[key] = el
  }
}

// 初始化遍历图表
const initTraversalCharts = () => {
  nextTick(() => {
    // 第一个遍历的饼状图
    traversalData1.value.forEach((item, index) => {
      // 饼状图1：考核结果分布
      const pieChart1Key = `pieChart1_${index}`
      if (traversalChartsRefs.value[pieChart1Key]) {
        const pieChart1 = echarts.init(traversalChartsRefs.value[pieChart1Key])
        pieChart1.setOption({
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '70%',
            data: [
              { value: 120, name: '优秀' },
              { value: 280, name: '合格' },
              { value: 75, name: '待改进' }
            ]
          }]
        })
      }

      // 饼状图2：改进情况分布
      const pieChart2Key = `pieChart2_${index}`
      if (traversalChartsRefs.value[pieChart2Key]) {
        const pieChart2 = echarts.init(traversalChartsRefs.value[pieChart2Key])
        pieChart2.setOption({
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '70%',
            data: [
              { value: 15, name: '已改进' },
              { value: 60, name: '待改进' },
              { value: 5, name: '未改进' }
            ]
          }]
        })
      }
    })

    // 第二个遍历的图表
    traversalData2.value.forEach((item, index) => {
      // 柱状图：考核分数分布
      const barChartKey = `barChart_${index}`
      if (traversalChartsRefs.value[barChartKey]) {
        const barChart = echarts.init(traversalChartsRefs.value[barChartKey])
        barChart.setOption({
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['90-100分', '80-89分', '70-79分', '60-69分', '60分以下'] },
          yAxis: { type: 'value' },
          series: [{ type: 'bar', data: [85, 120, 95, 60, 20], itemStyle: { color: '#3b82f6' } }]
        })
      }

      // 饼状图：岗位分布
      const pieChart3Key = `pieChart3_${index}`
      if (traversalChartsRefs.value[pieChart3Key]) {
        const pieChart3 = echarts.init(traversalChartsRefs.value[pieChart3Key])
        pieChart3.setOption({
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '70%',
            data: [
              { value: 150, name: '安检员' },
              { value: 120, name: '设备操作员' },
              { value: 80, name: '管理人员' },
              { value: 50, name: '其他' }
            ]
          }]
        })
      }
    })
  })
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  const charts = [
    overallBarChartInstance,
    participantPieChartInstance,
    departmentComparisonChartInstance,
    brigadePieChart1Instance,
    brigadePieChart2Instance,
    positionPieChart1Instance,
    positionPieChart2Instance
  ]
  charts.forEach(chart => {
    if (chart) chart.resize()
  })
}

// 获取数据
const getList = async () => {
  loading.value = true
  try {
    const res = await getNonCadreMonthlyScoreSum(queryParams)
    // 这里可以根据实际API返回的数据更新图表和表格数据
    console.log('获取汇总数据:', res)
  } catch (error) {
    console.error('获取汇总数据失败:', error)
    ElMessage.error('获取汇总数据失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  getList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  getList()
}

// 导出
const handleExport = async () => {
  try {
    ElMessage.success('导出功能开发中')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  initCharts()
  initTraversalCharts()
  window.addEventListener('resize', handleResize)
  getList()
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  // 销毁图表实例
  const charts = [
    overallBarChartInstance,
    participantPieChartInstance,
    departmentComparisonChartInstance,
    brigadePieChart1Instance,
    brigadePieChart2Instance,
    positionPieChart1Instance,
    positionPieChart2Instance
  ]
  charts.forEach(chart => {
    if (chart) chart.dispose()
  })
})
</script>

<style lang="less" scoped>
.app-container {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.export-button {
  margin-left: auto;
}

.main-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.summary-table-card {
  margin-bottom: 20px;
}

.chart-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  text-align: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.pie-charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  height: 350px;
}

.pie-chart {
  width: 100%;
  height: 100%;
}

:deep(.el-table) {
  .el-table__header th {
    background-color: #f5f7fa;
    font-weight: 600;
  }
}

/* 遍历样式 */
.traversal-section {
  margin-bottom: 30px;
}

.traversal-container {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.traversal-header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  border-bottom: 1px solid #dcdfe6;
  text-align: left;
}

.traversal-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px;
}

.table-section {
  min-height: 400px;
}

.chart-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  height: 400px;
}

.pie-chart-container, .bar-chart-container {
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 10px;
  background-color: #fff;
}

.pie-chart-title, .chart-title {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 10px;
  text-align: center;
}

.pie-chart, .bar-chart {
  flex: 1;
  min-height: 300px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .pie-charts-container {
    grid-template-columns: 1fr;
  }
  
  .traversal-content {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .chart-section {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .pie-chart, .bar-chart {
    min-height: 250px;
  }
}

@media (max-width: 768px) {
  .traversal-content {
    padding: 15px;
  }
  
  .chart-section {
    gap: 10px;
  }
  
  .pie-chart-container, .bar-chart-container {
    padding: 8px;
  }
}
</style>