<template>
  <div>
    <div class="chart-box" v-if="mode === 'all' || mode === 'lines'">
      <header-cell>
        <h3>用户行为 <small>{{subtitle}}</small></h3>
        <select-building slot="action" v-if="selectBuilding" @change="handleBuildingChange"></select-building>
      </header-cell>
      <v-chart class="chart" v-loading="loading" :options="options" />
    </div>
    <div class="chart-box" v-if="mode === 'all' || mode === 'table'">
      <el-table :data="tableData"  border  center  style="width: 100%" height="400">
        <el-table-column label="访问事件" prop="eventName"></el-table-column>
        <el-table-column label="访问用户" prop="userName"></el-table-column>
        <el-table-column label="访问次数">
          <template slot-scope="scope">
            <el-button type="text" @click="showDetail(scope.row)">{{scope.row.accessCount}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="首次访问时间" prop="visitTime"></el-table-column>
        <el-table-column label="离开时间" prop="leaveTime"></el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="访问记录"
      :visible.sync="dialogVisible"
      width="50%">
      <el-table v-loading="detailData.length > 0" :data="detailData"  border  center  style="width: 100%" height="400">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="访问时间" prop="visitTime"></el-table-column>
        <el-table-column label="离开时间" prop="leaveTime"></el-table-column>
      </el-table>
    </el-dialog>
  </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 HeaderCell from '@/components/HeaderCell'
import { createNamespacedHelpers } from "vuex"

const { mapActions } = createNamespacedHelpers("indexEcharts")

export default {
  name: 'UserBehavior',
  components: {
    HeaderCell,
  },
  props: [
    'value',
    'subtitle',
    'dataZoom',
    'selectBuilding',
    'mode',
  ],
  data() {
    return {
      loading: false,
      dataset: {},
      dialogVisible: false,
      detailData: [],
      baseOpt: {
        legend: { show: true, zlevel: 10 },
        color: ['#8954BA', '#175DFB', '#0BB963', '#27DEFF', '#E713D2', '#E71313'],
        tooltip: {
          trigger: 'axis'
        },
        xAxis: { type: 'time' },
        yAxis: {},
      },
    }
  },
  computed: {
    tableData () {
      return (this.dataset.data || {}).records || []
    },
    options() {
      const seriesMaker = (this.dataset.selectUserBehavior || []).reduce((series, item) => {
        let { date, activityCount, activity } = item
        date = dayjs(date).format('YYYY-MM-DD')
        if (!activityCount) activityCount = 0

        // 使用对象, 可以去重
        series[`${activity}`] = (series[`${activity}`] || []).concat([[ date, activityCount ]])

        return series;
      }, {})

      const dataZoom = this.dataZoom ? 
        [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            type: 'slider',
            start: 0,
            end: 100
          },
        ] : undefined

      return {
        ...this.baseOpt,
        dataZoom,
        series: Object.keys(seriesMaker).map(x => {
          return {
            type: 'line',
            name: x,
            data: seriesMaker[x],
          }
        }),
      }
    }
  },
  methods: {
    ...mapActions([
      'getUserBehaviorSummary',
      'getUserBehaviorProfile',
    ]),
    getData(filers) {
      this.loading = true
      this.getUserBehaviorSummary(filers).then((data) => {
        this.dataset = data || {}
        this.loading = false
      }).catch(() => {
        this.loading = true
      })
    },
    showDetail (row) {
      this.detailData = []
      this.dialogVisible = true
      this.getUserBehaviorProfile({ event: row.event, personId: row.personId }).then((data) => {
        this.detailData = data
      })
    },
    handleBuildingChange (e) {
      this.getData({ buildingId: e })
    },
  },
  mounted () {
    const endDate = new Date()
    const startDate = dayjs().subtract(7, 'day').toDate()

    this.getData({ startDate, endDate, pageSize: 9999 })
  },
}
</script>

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