<template>
  <el-row :gutter="20">
    <!-- 个人工单完成情况的空心饼图 -->
    <el-col :span="12" v-if="showPersonalWorkOrderChart">
      <div class="chart-container floating-card">
        <div ref="personalWorkOrderChart" class="chart"></div>
      </div>
    </el-col>
    
    <!-- 个人工分统计的曲线图 -->
    <el-col :span="12" v-if="showPersonalPointsChart">
      <div class="chart-container floating-card">
        <div ref="personalPointsChart" class="chart"></div>
      </div>
    </el-col>
    
    <!-- 扣分工单列表 -->
    <el-col :span="24" v-if="showDeductionPointList">
      <div class="table-container floating-card">
        <div class="table-title">扣分工单反馈列表</div>
        <el-table :data="deductionPointList" style="width: 100%;margin-top: 20px;" :empty-text="deductionPointListEmptyText">
          <el-table-column prop="code" label="工单编码" width="400"></el-table-column>
          <el-table-column prop="deductionPoint" label="扣分值" width="200">
            <template #default="scope">
              <span v-if="scope && scope.row" style="color: red;">
                {{ scope.row.deductionPoint }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="扣分原因"></el-table-column>
          <el-table-column prop="status" label="处理状态" width="200">
            <template #default="scope">
              <span v-if="scope && scope.row">
                <el-tag v-if="scope.row.status === '0'" type="warning">待反馈</el-tag>
                <el-tag v-else-if="scope.row.status === '1'" type="success">已处理</el-tag>
                <el-tag v-else type="info">未知</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <span v-if="scope && scope.row">
                <el-button 
                  type="text" 
                  style="color: #165dff"
                  @click="handleFeedback(scope.row)"
                >
                  反馈
                </el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import * as echarts from 'echarts';
import { getChartData } from '@/api/system/dashboard';

export default {
  name: 'ChartsGroupThree',
  props: {
    postType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      personalWorkOrderChart: null,
      personalPointsChart: null,
      showPersonalWorkOrderChart: true, // 控制个人工单完成情况图表的显示
      showPersonalPointsChart: true, // 控制个人工分统计图表的显示
      deductionPointList: [], // 扣分工单列表数据
      showDeductionPointList: false, // 控制扣分工单列表的显示
      deductionPointListEmptyText: '当前没有扣分工单' // 空数据时的提示文本
    }
  },
  watch: {
    postType: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          // 当 postType 变化时重新获取数据
          this.fetchChartData();
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.initCharts()
  },
  beforeDestroy() {
    // 销毁图表实例
    const charts = [this.personalWorkOrderChart, this.personalPointsChart];
    charts.forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.personalWorkOrderChart = echarts.init(this.$refs.personalWorkOrderChart)
      this.personalPointsChart = echarts.init(this.$refs.personalPointsChart)
      
      // 获取图表数据
      this.fetchChartData();
    },
    
    // 获取图表数据
    async fetchChartData() {
      try {
        const response = await getChartData();
        
        // 处理个人工单完成情况数据
        if (response && response.userOrderStatistics) {
          // 更新个人工单完成情况图表
          this.updatePersonalWorkOrderChart(response.userOrderStatistics);
        } else {
          // 如果没有获取到数据，隐藏图表
          this.showPersonalWorkOrderChart = false;
          // 销毁图表实例
          if (this.personalWorkOrderChart) {
            this.personalWorkOrderChart.dispose();
            this.personalWorkOrderChart = null;
          }
        }
        
        // 处理个人工分统计数据
        if (response && response.userPointStatistics) {
          // 更新个人工分统计图表
          this.updatePersonalPointsChart(response.userPointStatistics);
        } else {
          // 如果没有获取到数据，隐藏图表
          this.showPersonalPointsChart = false;
          // 销毁图表实例
          if (this.personalPointsChart) {
            this.personalPointsChart.dispose();
            this.personalPointsChart = null;
          }
        }
        
        // 处理扣分工单列表数据
        if (response && response.deductionPointStatistics !== null && response.deductionPointStatistics !== undefined) {
          // 当deductionPointStatistics不为null时显示列表
          this.showDeductionPointList = true;
          this.deductionPointList = response.deductionPointStatistics;
        } else {
          // 当deductionPointStatistics为null时隐藏列表
          this.showDeductionPointList = false;
          this.deductionPointList = [];
        }
      } catch (error) {
        console.error('获取图表数据失败:', error);
        // 出错时隐藏图表
        this.showPersonalWorkOrderChart = false;
        this.showPersonalPointsChart = false;
        // 销毁图表实例
        if (this.personalWorkOrderChart) {
          this.personalWorkOrderChart.dispose();
          this.personalWorkOrderChart = null;
        }
        if (this.personalPointsChart) {
          this.personalPointsChart.dispose();
          this.personalPointsChart = null;
        }
        // 出错时隐藏列表
        this.showDeductionPointList = false;
        this.deductionPointList = [];
      }
    },
    
    // 计算轴的最大值和间隔的新方法
    calculateAxisRange(maxValue) {
      // 预定义的数组
      const presetValues = [1, 2, 3, 4, 5, 10, 15, 20, 25, 50, 100, 150, 200, 250, 300, 500, 1000, 2000, 5000];
      
      let selectedValue = maxValue/9;
      let maxAxisValue1 = Math.floor(selectedValue) * 10;
      let numForm = 10;
      for (let i = 0; i < presetValues.length; i++) {
        const numFormI = maxValue/presetValues[i];
        if (numFormI>=1 && numFormI<=9) {
          selectedValue = presetValues[i];
          const numFormII = Math.floor(numFormI);
          if (numFormII<numFormI) {
            numForm = numFormII+1;
          }else{
            numForm = numFormII;
          }
          maxAxisValue1 = selectedValue * numForm;
          break;
        }
      }
      const maxAxisValue = maxAxisValue1;
      const interval = selectedValue;
      return { maxAxisValue, interval };
    },
    
    // 更新个人工单完成情况图表
    updatePersonalWorkOrderChart(userOrderStatistics) {
      // 处理后台传回的数据格式 [{"key":"已完成","value":"45"}]
      let data = [];
      
      if (userOrderStatistics && Array.isArray(userOrderStatistics) && userOrderStatistics.length > 0) {
        // 从后台数据中提取状态和数量
        data = userOrderStatistics.map(item => ({
          name: item.key,
          value: parseInt(item.value) || 0
        }));
        // 显示图表
        this.showPersonalWorkOrderChart = true;
      } else {
        // 隐藏图表
        this.showPersonalWorkOrderChart = false;
        // 销毁图表实例
        if (this.personalWorkOrderChart) {
          this.personalWorkOrderChart.dispose();
          this.personalWorkOrderChart = null;
        }
        return;
      }
      
      // 定义固定颜色数组
      const fixedColors = [
        'rgba(82, 196, 26, 0.7)',   // 第一个颜色
        'rgba(250, 173, 20, 0.7)',  // 第二个颜色
        'rgba(22, 93, 255, 0.7)'    // 第三个颜色
      ];
      
      // 个人工单完成情况的空心饼图
      const personalWorkOrderOption = {
        title: {
          text: '个人工单完成情况',
          left: 'left',
          top: 'top'
        },
        tooltip: {
          show: true,
          trigger: 'item',
          padding: [1, 5],
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: 'rgba(0, 0, 0, 0.7)',
          textStyle: {
            color: '#fff'
          },
          formatter: function(params) {
            return `
              <div style="font-weight:bold; font-size:12px;">${params.name}</div>
              <div style="display: flex; align-items: center; font-size:12px;">
                <span style="display:inline-block; width:12px; height:12px; background:${params.color};margin-right: 4px;box-shadow: 0 0 0 0.5px white;"></span>
                <span >${params.value}</span>
              </div>
            `;
          },
        },
        legend: {
          orient: 'horizontal', // 水平分布
          left: 'center', // 居中
          bottom: '0', // 底部
        },
        series: [
          {
            name: '工单状态',
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            type: 'pie',
            radius: ['50%', '75%'], // 空心饼图
            center: ['50%', '50%'],
            data: data.map((item, index) => ({
              name: item.name,
              value: item.value,
              itemStyle: { 
                color: index < 3 ? fixedColors[index] : `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)` 
              }
            })),
            emphasis: {
              scale: false,
            }
          }
        ]
      }
      
      // 初始化图表实例（如果还没有）
      if (!this.personalWorkOrderChart) {
        this.personalWorkOrderChart = echarts.init(this.$refs.personalWorkOrderChart);
      }
      
      // 设置个人工单完成情况图表配置
      this.personalWorkOrderChart.setOption(personalWorkOrderOption, true);
    },
    
    // 更新个人工分统计图表
    updatePersonalPointsChart(userPointStatistics) {
      // 处理后台传回的数据格式 [{"key":"周一","value":"25"}]
      let names = [];
      let values = [];
      
      if (userPointStatistics && Array.isArray(userPointStatistics) && userPointStatistics.length > 0) {
        // 从后台数据中提取日期和工分值
        names = userPointStatistics.map(item => item.key);
        values = userPointStatistics.map(item => parseInt(item.value) || 0);
        // 显示图表
        this.showPersonalPointsChart = true;
      } else {
        // 隐藏图表
        this.showPersonalPointsChart = false;
        // 销毁图表实例
        if (this.personalPointsChart) {
          this.personalPointsChart.dispose();
          this.personalPointsChart = null;
        }
        return;
      }
      
      // 使用新的计算方法
      const maxValue = Math.max(...values, 5); // 至少显示到5
      const { maxAxisValue, interval } = this.calculateAxisRange(maxValue);
      
      // 个人工分统计的曲线图（蓝色曲线，浅蓝色区域）
      const personalPointsOption = {
        title: {
          text: '个人工分统计',
          left: 'left',
          top: 'top'
        },
        grid: {
          left: '2%',   // 左边距 5%
          right: '2%',  // 右边距 5%
          top: '20%',   // 上边距（根据需求调整）
          bottom: '5%', // 下边距（根据需求调整）
          containLabel: true, // 确保标签在 grid 区域内
        },
        tooltip: {
          show: true,
          trigger: 'item',
          padding: [1, 5],
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: 'rgba(0, 0, 0, 0.7)',
          textStyle: {
            color: '#fff'
          },
          formatter: function(params) {
            return `
              <div style="font-weight:bold; font-size:12px;">${params.name}</div>
              <div style="display: flex; align-items: center; font-size:12px;">
                <span style="display:inline-block; width:12px; height:12px; background:${params.color};margin-right: 4px;box-shadow: 0 0 0 0.5px white;"></span>
                <span>工分数:</span>
                <span style="margin-left: 4px;">${params.value}</span>
              </div>
            `;
          },
        },
        xAxis: {
          type: 'category',
          data: names, // 日期
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(200, 200, 200, 0.3)',
              type: 'solid'
            }
          },
          // 确保0点也能显示x轴第一个名字
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: maxAxisValue,
          interval: interval,
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(200, 200, 200, 0.3)',
              type: 'solid'
            }
          }
        },
        series: [
          {
            name: '工分',
            data: values, // 工分值
            type: 'line',
            smooth: true,
            symbolSize: 8,
            lineStyle: {
              color: 'rgba(30, 144, 255, 0.8)', // 蓝色曲线
              width: 3
            },
            areaStyle: {
              color: 'rgba(30, 144, 255, 0.2)' // 浅蓝色区域
            }
          }
        ]
      }
      
      // 初始化图表实例（如果还没有）
      if (!this.personalPointsChart) {
        this.personalPointsChart = echarts.init(this.$refs.personalPointsChart);
      }
      
      // 设置个人工分统计图表配置
      this.personalPointsChart.setOption(personalPointsOption, true);
    },
    
    // 图表自适应
    resizeCharts() {
      const charts = [this.personalWorkOrderChart, this.personalPointsChart];
      charts.forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },
    
    // 处理反馈按钮点击事件
    handleFeedback(row) {
      // 这里可以添加反馈逻辑，比如打开一个对话框或跳转到反馈页面
      console.log('点击反馈按钮，工单信息：', row);
      this.$message.info('反馈功能待实现');
    }
  }
}
</script>

<style scoped>
/* 悬浮卡片通用样式 */
.floating-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
}

.floating-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
}

/* 图表样式 */
.chart-container {
  height: 340px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  box-sizing: border-box;
  backdrop-filter: blur(5px);
}

.chart-container:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
}

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

/* 表格容器样式 */
.table-container {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  box-sizing: border-box;
  backdrop-filter: blur(5px);
  position: relative;
}

/* 表格标题样式 - 与图表标题保持一致 */
.table-title {
  position: absolute;
  left: 20px;
  top: 10px;
  font-size: 18px; /* 与ECharts默认标题大小一致 */
  font-weight: bold;
  color: #333;
  z-index: 1;
}

.post-type-debug {
  margin-top: 10px;
  padding: 5px;
  background-color: #f0f0f0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}
</style>