<template>
  <div class="trendChartPage">
    <div class="btns">
      <el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div ref="trendChart" class="trendChart" />
  </div>
</template>

<script>
import ChartOption from './module.js'
export default {
  props: {
    chartData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      options: [
        {
          value: '1',
          label: '销售额趋势'
        },
        {
          value: '2',
          label: '访问量趋势'
        }
      ],
      value: '销售额趋势',
      chart: new ChartOption('trendChart'),
    }
  },
  watch: {
    chartData: {
      handler (nVal, oVal) {
        this.setOptions(this.chart.chart, nVal)
      },
      deep: true
    },
    value: {
      handler (nVal, oVal) {
        this.setOptions(this.chart.chart, this.chartData)
      }
    }
  },
  mounted () {
    this.initChart(this.chart)
  },
  methods: {
    initChart (chartObj) {
      chartObj.chart = this.$echarts.init(this.$refs[chartObj.name])
      this.setOptions(chartObj.chart, this.chartData)
    },
    setOptions (chart, data) {
      chart.setOption({
        title: {
          text: this.value === '1' ? '销售额趋势' : '访问量趋势',
          x: 'center',
          y: 'bottom'
        },
        xAxis: {
          type: 'category',
          data: data.times || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            itemStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            name: this.value === '1' ? '销售' : '访问量',
            type: 'bar',
            data: this.value === '1' ? data.moneys : data.totals
          }
        ]
      })
    }
  }
}
</script>

<style scoped lang="scss">
.trendChartPage{
  width: 100%;
  height: 100%;
  position: relative;
  .btns{
    display: flex;
    justify-content: flex-end;
  }
  .trendChart{
    width: 100%;
    height: 100%;
  }
}
</style>
