
<template>
      <el-card shadow="always" class="common-card-container common-card-container-body-no-padding time-range-card">
        <div slot="header" class="time-range-header">
          <span class="card-title">一周充放曲线</span>
          <date-range-select ref="dateRangeSelect" @updateDate="updateDate"/>
        </div>
        <div style="height: 310px" id="weekChart"></div>
      </el-card>
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/mixins/ems/resize'
import DateRangeSelect from '@/components/Ems/DateRangeSelect/index.vue'
import {getSevenChargeData} from '@/api/ems/dzjk'
export default {
  mixins: [resize],
  components: {DateRangeSelect},
  data() {
    return {
      chart: null,
      timeRange:[],
      siteId:'',
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 更新时间范围 重置图表
    updateDate(data){
      this.timeRange=data
      this.getWeekKData()
    },
    getWeekKData(){
      this.showLoading()
      const {siteId,timeRange}=this
      this.hideLoading()
      getSevenChargeData({siteId,startDate:timeRange[0],endDate:timeRange[1]}).then(response => {
        this.setOption(response?.data || [])
      }).finally(()=>this.hideLoading())
    },
    init(siteId){
      //初始化 清空数据
      this.siteId = siteId
      this.timeRange=[]
      this.deviceId=''
      this.$refs.dateRangeSelect.init()
    },
    initChart() {
      this.chart = echarts.init(document.querySelector('#weekChart'))
    },
    showLoading(){
      this.chart && this.chart.showLoading()
    },
    hideLoading(){
      this.chart && this.chart.hideLoading()
    },
    setOption(data,unit) {
      const source = [['日期','充电量','放电量']]
      data.forEach(item=>{
        source.push([item.ammeterDate, item.chargedCap,item.disChargedCap])
      })
      this.chart && this.chart.setOption({
        color:['#4472c4','#70ad47'],//所有充放电颜色保持统一
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          containLabel: true
        },
        legend: {
          left: 'center',
          bottom: '15',
        },
        xAxis: {
          type: 'category',
          name:unit,
          nameLocation:'center'
        },
        yAxis: [{
          type: 'value',
          name:'充电量/放电量kWh',
          axisLine: {
            lineStyle:{
              color: '#333333',
            },
            onZero:false
          }
        }],
        dataset:{
          source
        },
        series: [
          {
            yAxisIndex:0,
            type: 'bar',
          },
          {
            yAxisIndex:0,
            type: 'bar',
          },
        ]
      })
    }
  }
}
</script>
