<template>
  <div class="echart-bar" id="myChart"></div>
</template>
<script>
import * as echarts from 'echarts'
import { getChart } from '../api'
export default {
  props: {
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      options: {
        title: { text: '年龄分布' },
        tooltip: {
          trigger: 'item',
          formatter: function(data) {
            return data.name + '<br/>' + data.seriesName + '：' + data.value + '%' // 将小数转化为百分数显示
          }
        },
        // legend: {
        //   data: ['基金', '全网分布', '平均温度']
        // },
        grid: {
          top: '20%',
          bottom: 90
        },
        xAxis: {
          data: [],
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '百分比',
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#333'
              }
            },
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '基金',
            type: 'bar',
            barWidth: '50%',
            data: [],
            itemStyle: {
              normal: {
                color: '#68B8A4'
              }
            }
          }
        ]
      },
      echart: null
    }
  },
  watch: {
    value: {
      handler(v) {
        if (v.id) {
          this.options.xAxis.data = v.options.map(item => item.subject)
          this.options.title.text = v.subject
          this.$nextTick(() => {
            this.echart.setOption(this.options)
          })
          this.fetchEchartsData()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.echart = echarts.init(document.getElementById('myChart'))
  },
  methods: {
    fetchEchartsData() {
      const params = {
        option: this.value.tag
      }
      getChart(params).then(res => {
        if (res.code === 0 && res.data && Array.isArray(res.data.chart)) {
          this.options.series[0].data = res.data.chart.map(item => parseFloat(item.percent))
          this.echart.setOption(this.options)
        }
      })
    }
  }
}
</script>
<style scoped>
.echart-bar{
  width:100%;
  height:100%;
}
</style>
