<template>
  <div>
<!--    <span style="margin: 10px">统计区间：</span>-->
<!--    <el-date-picker-->
<!--      style="margin: 10px"-->
<!--      v-model="value2"-->
<!--      type="daterange"-->
<!--      align="right"-->
<!--      unlink-panels-->
<!--      range-separator="至"-->
<!--      start-placeholder="开始日期"-->
<!--      end-placeholder="结束日期"-->
<!--      :picker-options="pickerOptions" >-->
<!--    </el-date-picker>-->
    <div ref="barChart" style="width: 700px; height: 400px;margin-top: 3%"></div>  <!-- 这里指定了柱状图的宽高 -->
  </div>
</template>

<script>
import { getMaterialsChangeStatistics } 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: {
    // value2(val) {
    //   if(val){
    //     this.getList()
    //   }
    // },
    dateRange(newVal, oldVal) {
      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() {
      // if (Array.isArray(this.value2) && this.value2.length === 2) {
      //   this.queryParams.startTime = this.formatDate(this.value2[0])
      //   this.queryParams.endTime = this.formatDate(this.value2[1])
      // }
      getMaterialsChangeStatistics(this.queryParams).then(response => {
        console.log(response, '物资柜状态统计--更换次数')
        this.cabinetData = response.data // 获取数据后保存
        this.renderChart()  // 数据获取完后渲染图表
      })
    },

    // 渲染柱状图
    renderChart() {
      if (this.cabinetData.length === 0) return

      // 初始化图表实例
      this.chartInstance = echarts.init(this.$refs.barChart)

      // 提取 X 轴和 Y 轴的数据
      const materialTypeName = this.cabinetData.map(item => item.materialsTypeName)
      const allCount = this.cabinetData.map(item => item.allCount)
      const expireCount=this.cabinetData.map(item=>item.expireCount)
      const badCount=this.cabinetData.map(item=>item.badCount)
      // 配置图表的选项
      const options = {
        title: {
          text: '物资更换统计',
          left: 'center',
          top: '0%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ['正常更换次数','过期更换次数','损坏更换次数'],
          top: '5%',  // 调整图例距离顶部的距离，确保图例在标题下方
          left: 'center',  // 图例居中显示
        },
        xAxis: [
          {
            type: 'category',
            data: materialTypeName,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '次数',
            axisLabel: {
              formatter: '{value} '  // 修改单位为 次
            },
            splitLine: {
              show: false  // 隐藏纵向的网格线
            }
          }
        ],
        series: [
          {
            name: '正常更换次数',  // 修改为适当的名称
            type: 'bar',
            stack: 'Ad',  // 启用堆叠效果
            barWidth: '25%',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 次';  // 修改单位为 次
              }
            },
            data: allCount,
            itemStyle: {
              color: '#5470c6',  // 设置柱子的颜色为蓝色（你可以根据需要修改）
            }
          },
          {
            name: '过期更换次数',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: expireCount,
            itemStyle: {
              color: '#91cc75',  // 设置柱子的颜色为蓝色（你可以根据需要修改）
            }
          },
          {
            name: '损坏更换次数',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: badCount,
            itemStyle: {
              color: '#fac858',  // 设置柱子的颜色为蓝色（你可以根据需要修改）
            }
          }
        ]
      };

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

<style scoped lang="scss">
/* 如果需要更改图表的样式，可以在这里添加 */
</style>
