<template>
  <div class="charts-container">

    <!-- 单个堆叠柱状图 -->
    <div id="stackedBarChart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
import { getCabinetStatistics } from '@/api/mes/statisticians'
import * as echarts from 'echarts'

export default {
  name: 'warehouseEquipmentUsageStatus',
  props: {
    startTime: {
      type: String,
      default: ''
    },
    endTime: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      cabinetData: [], // 存储请求到的柜子数据
      chartInstance: null, // 存储柱状图实例
      value2: this.getDefaultDateRange(),
      queryParams: {
        startTime: null,
        endTime: null
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {
    dateRange() {
      return {
        startTime: this.startTime,
        endTime: this.endTime
      }
    }
  },
  watch: {
    dateRange(newVal) {
      if (newVal.startTime && newVal.endTime) {
        this.queryParams.startTime = newVal.startTime
        this.queryParams.endTime = newVal.endTime
        this.getList()
      }
    }
  },
  mounted() {
    // this.getList()
  },
  methods: {
    getDefaultDateRange() {
      const today = new Date()
      const oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
      return [oneMonthAgo, today]
    },
    formatDate(date) {
      const year = date.getFullYear().toString().padStart(2, '0')
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 请求数据
    getList() {
      getCabinetStatistics(this.queryParams).then(response => {
        console.log(response, '物资柜状态统计--物资柜异常数据统计')
        this.cabinetData = response.data // 获取数据后保存

        // 在数据加载完成后渲染图表
        this.$nextTick(() => {
          this.renderChart() // 在 DOM 更新完后再执行渲染
        })
      })
    },

    // 渲染堆叠柱状图
    renderChart() {
      const chartElement = document.getElementById('stackedBarChart')
      if (chartElement) {
        // 初始化柱状图实例
        this.chartInstance = echarts.init(chartElement)

        // 提取物资柜名称和异常数据
        const cabinetNames = this.cabinetData.map(cabinet => cabinet.cabinetName)
        const misplaceData = this.cabinetData.map(cabinet => cabinet.misplaceCount || 0)
        const timeoutData = this.cabinetData.map(cabinet => cabinet.openTimeoutCount || 0)

        // 配置柱状图的选项
        const options = {
          title: {
            text: '物资柜异常统计',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['物资错放', '超时未关'],
            top: '5%',
            left: 'center',
            textStyle: {
              fontSize: 14
            }
          },

          xAxis: {
            type: 'category',
            data: cabinetNames, // 横坐标为物资柜名称
            axisLabel: {
              rotate: 0, // 如果名称过长，可以旋转标签
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value',
            name: '次数',
            splitLine: {
              show: false  // 隐藏纵向的网格线
            }
          },
          series: [
            {
              name: '物资错放',
              type: 'bar',
              stack: '异常情况',
              barWidth: '25',
              data: misplaceData, // 物资错放数据
              itemStyle: {
                color: '#5470c6' // 蓝色
              }
            },
            {
              name: '超时未关',
              type: 'bar',
              stack: '异常情况',
              data: timeoutData, // 超时未关数据
              itemStyle: {
                color: '#91cc75' // 绿色
              }
            }
          ]
        }

        // 设置图表的配置项
        this.chartInstance.setOption(options)
      }
    }
  },
  beforeDestroy() {
    // 销毁图表实例，避免内存泄漏
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  }
}
</script>

<style scoped lang="scss">
.charts-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}
</style>
