<!--
 * @Author: your name
 * @Date: 2022-04-11 15:07:47
 * @LastEditTime: 2022-04-12 09:55:18
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /gassafety-progress/gassafetyprogress-web/src/views/operationMonitor/xunjianxuncha/topChars/left.vue
-->
<template>
  <div class="charsCom all-flex-h">
    <div class="title">巡检巡查任务</div>
    <div class="two all-flex">
      <div id="chars" class="chars" style="width: 100%; height: 300px;"></div>
    </div>
  </div>
</template>

<script>
import { getPatrolChars } from "@/api/inspectionWork/linePatrol";

export default {
  components: {
  },
  data(){
    return{
      year:'2025-',
      totalObj: {
        taskTotal: 0,
        taskFeedbackTotal: 0
      },
      chartInstance: null // 用于保存echarts实例
    }
  },
  created(){
    this.getChars();
  },
  mounted() {
    // 确保DOM渲染完成后再初始化图表
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    // 组件销毁前销毁echarts实例，避免内存泄漏
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods:{
    // 初始化图表
    initChart() {
      const chartDom = document.getElementById('chars');
      if (!chartDom) {
        console.error('图表容器未找到');
        return;
      }

      try {
        // 使用全局挂载的echarts
        this.chartInstance = this.$echarts.init(chartDom);

        // 初始空配置 - 竖向柱状图
        const option = {
          title: {
            text: '各公司巡检次数统计',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const data = params[0];
              return `${data.name}<br/>巡检次数: ${data.value}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              fontSize: 12,
              interval: 0,
              rotate: 30, // 如果公司名称太长，可以旋转角度
              width: 80,
              overflow: 'truncate'
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            name: '巡检次数',
            axisLabel: {
              fontSize: 12
            }
          },
          series: [
            {
              name: '巡检次数',
              type: 'bar',
              data: [],
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#188df0' },
                  { offset: 0.5, color: '#1d8cf3' },
                  { offset: 1, color: '#83bff6' }
                ])
              },
              emphasis: {
                itemStyle: {
                  color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#2378f7' },
                    { offset: 0.7, color: '#2378f7' },
                    { offset: 1, color: '#83bff6' }
                  ])
                }
              },
              barWidth: '50%',
              label: {
                show: true,
                position: 'top',
                formatter: '{c}'
              }
            }
          ]
        };

        this.chartInstance.setOption(option);

        // 窗口大小改变时重绘图表
        window.addEventListener('resize', this.handleResize);
      } catch (error) {
        console.error('初始化图表失败:', error);
      }
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    // 获取数据并更新图表
    getChars() {
      getPatrolChars(this.year).then(res =>{
        if(res.code == 200){
          console.log("res", res);
          // 更新图表数据
          this.updateChart(res.data);
        }
      }).catch(error => {
        console.error("获取巡检数据失败:", error);
      });
    },

    // 更新图表数据
    updateChart(data) {
      if (!this.chartInstance || !data) return;

      // 对数据进行排序（从大到小）
      const combined = data.enterpriseName.map((name, index) => ({
        name,
        value: data.numbers[index] || 0
      }));

      // 按巡检次数降序排序
      combined.sort((a, b) => b.value - a.value);

      // 提取排序后的数据
      const sortedNames = combined.map(item => item.name);
      const sortedValues = combined.map(item => item.value);

      // 更新图表配置 - 竖向柱状图
      const option = {
        xAxis: {
          data: sortedNames
        },
        series: [{
          data: sortedValues
        }]
      };

      this.chartInstance.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
.charsCom {
  width: 100%;
  height: 100%;
  color: #333333;
}
.title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 7px;
}
.two {
  flex: 1;
  > .left {
    margin-right: 70px;
  }
  > .right {
  }
  > div {
    font-size: 16px;
    flex: 1;
  }
  .left,
  .right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .first {
      margin-bottom: 6px;
      text-align: left;
      .text {
        display: inline-block;
        margin-right: 8px;
      }
    }
    .second {
      width: 213px;
      height: 30px;
      line-height: 30px;
      box-sizing: border-box;
      box-shadow: 0px 0px 3px 1px #dddddd;
      margin-bottom: 19px;

      > div {
        text-align: center;

        &.left {
          color: #1d8cf3;
        }
        &.right {
          color: #00c3f1;
        }
      }
    }
    .third {
      text-align: center;
      width: 213px;
      margin-bottom: 24px;
    }
    .fifth {
      flex: 1;
      padding-top: 5px;
      .contant {
        width: 120px;
        height: 120px;
        margin: 0 auto;
      }
    }
  }
}
</style>
