<template>
  <div class="chart-box">
    <header-cell>
      <h3>转化率</h3>
      <el-select v-model="theStatis" @change="getData" slot="action">
        <el-option v-for="item in statisTypes" :label="item.label" :value="item.value" :key="item.value"></el-option>
      </el-select>
    </header-cell>
    <v-chart class="chart" :options="options" />
  </div>
</template>

<script>
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/tooltip'
import { createNamespacedHelpers } from "vuex"

const { mapActions } = createNamespacedHelpers("indexEcharts");

export default {
  name: 'UserConversion',
  components: {
    'v-chart': ECharts,
    HeaderCell: () => import('@/components/HeaderCell'),
  },
  props: [ 'value' ],
  data () {
    return {
      defaultOpt: {
        legend: {},
        color: ['#8B7FE2', '#DDDDDD'],
        tooltip: {},
        series: {
          type: 'pie',
          name: '转化率',
          radius: ['50%', '70%'],
        }
      },

      theStatis : 'building_save',
      theCurrent: [],
      statisTypes: [
        { label: '项目收藏', value: 'building_save' },
        { label: '项目转发', value: 'building_share' },
        { label: '活动收藏', value: 'activity_save' },
        { label: '活动转发', value: 'activity_share' },
        { label: '资讯收藏', value: 'news_save' },
        { label: '资讯转发', value: 'news_share' },
        { label: '活动报名', value: 'activity_sign' },
        { label: '授权手机', value: 'authorization_phone' },
      ],
      // 各统计结果
      dataset: {},
    }
  },
  computed: {
    options () {
      return {
        ...this.defaultOpt,
        series: {
          ...this.defaultOpt.series,
          data: this.theCurrent,
        }
      }
    }
  },
  methods: {
    ...mapActions(['getUserConversionRate']),
    getData(e) {
      console.log('e: ', e)
      this.getUserConversionRate({ conversion: e }).then(this.setDataset)
      // if (!this.dataset[e]) {
      //   this.getUserConversionRate({ conversion: e }).then(this.setDataset)
      // } else {
      //   this.theCurrent = this.dataset[e]
      // }
    },
    setDataset(data) {      
      const { pvNum, ...other } = data['data_count']

      // 获取第一个值
      let num = 0
      for (let v of Object.keys(other)) {
        num = other[v]
        break
      }


      if (pvNum < num) {
        this.theCurrent = []
      } else {
        this.theCurrent = [
          { name: this.getStatisName(), value: num },
          { name: '其余', value: pvNum - num },
        ]
      }
      
      this.dataset[this.theStatis] = this.theCurrent
    },
    getStatisName() {
      return this.statisTypes.filter(x => x.value === this.theStatis)[0].label
    }
  },
  mounted () {
    this.getUserConversionRate({ conversion: this.theStatis }).then(this.setDataset)
  }
}
</script>

<style lang="scss" src="./style.scss"></style>
