<template>
  <div class="mod-demo-echarts">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div :id="'J_chartLineBox' + id" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import * as echarts from 'echarts'
  export default {
    props: {
      id: {
        type: Number,
        default: 1
      },
      showId: {
        type: Number,
        default: 0
      },
      name: {
        type: String,
        default: ''
      },
      dataList: {
        type: Array,
        default: () => {
          return []
        }
      },
      lastDataList: {
        type: Array,
        default: () => {
          return []
        }
      }
    },
    data () {
      return {
        chartLine: null
      }
    },
    watch: {
      showId: function (v) {
        if (v === this.id) {
          this.initChartLine()
        }
      }
    },
    mounted () {
      this.initChartLine()
    },
    activated () {
      // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
      if (this.chartLine) {
        this.chartLine.resize()
      }
    },
    methods: {
      // 折线图
      initChartLine () {
        if (this.chartLine) {
          this.chartLine.dispose()
        }
        var option = {
          title: {
            text: this.name
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: [ '当前', '上一个单位' ]
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.dataList.map(item => {
              return item.time
            })
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '当前',
              type: 'line',
              data: this.dataList.map(item => {
                return item.value
              })
            },
            {
              name: '上一个单位',
              type: 'line',
              data: this.lastDataList.map(item => {
                return item.value
              })
            }
          ]
        }
        this.chartLine = echarts.init(document.getElementById('J_chartLineBox' + this.id))
        this.chartLine.setOption(option)
        window.addEventListener('resize', () => {
          this.chartLine.resize()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .mod-demo-echarts {
    > .el-alert {
      margin-bottom: 10px;
    }
    > .el-row {
      margin-top: -10px;
      margin-bottom: -10px;
      .el-col {
        padding-top: 10px;
        padding-bottom: 10px;
      }
    }
    .chart-box {
      min-height: 300px;
    }
  }
</style>
