<template>
  <div>
    <div class="chart-box" v-if="mode == 'all' || mode == 'line'">
      <h3>新增客户</h3>
      <v-chart v-loading="loading" class="chart" :options="options" />
    </div>
    <div class="chart-box" v-if="mode == 'all' || mode == 'table'">
      <h3>新增客户 <small>最近七天</small></h3>
      <el-table v-loading="loading" :data="tableData"  border  center  style="width: 100%; margin-top: 16px">
        <el-table-column v-for="(item, index) in tableTitle" :key="index" :label="item" :prop="index == 0 ? 'label': item"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

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

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

export default {
  name: 'NewUsers',
  props: ['value', 'mode'],
  data () {
    return {
      loading: false,
      dataset: [],
      tableTitle: [ '类型' ],
      lineOpt: {
        color: ["purple", "green"],
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["新用户数", "授权注册"]
        },
        toolbox: {},
        xAxis: {
          type: "category",
        },
        yAxis: {},
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            type: 'slider',
            start: 0,
            end: 100
          },
        ],
        series: [
          {
            name: "新用户数",
            type: "line",
          },
          {
            name: "授权注册",
            type: "line",
          }
        ]
      },
    }
  },
  computed: {
    options () {
      return {
        ...this.lineOpt,
        dataset: {
          dimensions: ['date', 'userCount', 'authorizationCount'],
          source: this.dataset
        }
      }
    },
    tableData () {
      return this.dataset.reduce((acc, item, index) => {
          const { date, userCount, authorizationCount } = item
          const row1 = {
            ...acc[0],
            [`${date}`]: userCount,
          }
          const row2 = {
            ...acc[1],
            [`${date}`]: authorizationCount,
          }

          this.tableTitle = this.tableTitle.concat(`${date}`) // eslint-disable-line

          return [row1, row2];          
        }, [{ label: '新增用户', }, { label: '授权注册', } ])
    }
  },
  mounted () {
    const endDate = new Date()
    const startDate = dayjs().subtract(7, 'day').toDate()

    this.getData({ startDate, endDate })
  },
  methods: {
    ...mapActions(['getNewsUserCount']),
    getData(filters) {
      this.loadding = true
      this.getNewsUserCount(filters).then((data) => {
        this.dataset = data || []
        this.loading = false
      }).catch((err) => {
        this.loading = false
      })
    },
  },
}
</script>

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