<template>
  <div class="right-list-toobar">
    <el-toolbar>
      <div class="toolbar-body-flex">
        <div class="toolbat-body-flex-item">
          <el-button @click="refresh">
            <i class="fa fa-refresh"></i>刷新
          </el-button>
          <span>当前报表：</span>
          <span v-if="!item">一级栏目点击排行</span>
          <span v-else>
            <span style="color:#285;">{{currentReport}}</span>下子栏目点击排行
          </span>
        </div>
        <div class="toolbat-body-flex-item search-bar">
          <tree-select style="width:auto" :value.sync="catalogInnercode" :clearable="true" :items="catalogTree" :itemsOptions="treeItemsOptions" @click-change="refresh" placeholder="请选择栏目"></tree-select>
          <el-date-picker class="date-top" id="catalogHit-date-picker1" v-model="dateRangeValue" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择日期范围" @change="dateRangeChange"></el-date-picker>
          <el-button @click="check" class="button" type="primary"><slot name="button">查看</slot></el-button>
        </div>
      </div>
    </el-toolbar>
    <div v-loading="dataLoading">
      <echarts :options="chartOptions" height="300px"></echarts>
      <div style="margin:10px"></div>
      <el-table :data="catalogHit" tooltip-effect="dark" style="width: 100%" :default-sort="{prop: 'pv', order: 'descending'}">
        <!-- <el-table-column prop="itemName" label="栏目名称"></el-table-column> -->
        <el-table-column label="栏目名称">
           <template slot-scope="scope">
            <a v-if="!scope.row.isLeaf" href="javascript:void(0);" @click="itemView(scope.row.item, scope.row.itemName)">{{scope.row.itemName}}</a>
            <span v-else>{{scope.row.itemName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="PV比例"></el-table-column>
        <el-table-column prop="PV" label="PV"></el-table-column>
        <el-table-column prop="stickTime" label="页均停留时间"></el-table-column>
        <el-table-column label="趋势">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="showTrend(scope.row.item,scope.row.itemName)">时间趋势</a>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 趋势查看框 -->
    <el-dialog title="时间趋势" :visible.sync="trendDialog">
      <div>
        <el-date-picker id="catalogHit-date-picker2" v-model="tdateRangeValue" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择日期范围" @change="tdateRangeChange"></el-date-picker>&nbsp;
        <el-button @click="trendCheck">查看</el-button>
      </div>
      <div class="chart-trend" style="margin-top:20px" v-loading="chartLoading">
        <echarts :options="trendOption" height="300px"></echarts>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Echarts from '@src/components/Echarts.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
const MAX_CHART_ITEM_COUNT = 10 // 饼图最多显示数
export default {
  components: {
    echarts: Echarts,
    'tree-select': TreeSelect
  },
  data() {
    return {
      chartLoading: false,
      dataLoading: false,
      catalogHit: [], // 被访栏目
      catalogHitDataArray: [], // 被访栏目图表配置数据
      trend: [], // 栏目点击量数据
      dateRangeValue: [],
      startDate: '', // 搜索框日期范围
      endDate: '',
      trendDialog: false, // 趋势查看框
      tdateRangeValue: [],
      tStartDate: '', // 趋势查看框日期范围
      tEndDate: '',
      item: '', // 当前栏目
      itemName: '',
      xData: [], // 趋势图表数据
      yData: [],
      currentReport: '', // 当前报表
      chartOptions: {},
      trendOption: {},
      treeItemsOptions: {
        children: 'children',
        label: 'name',
        key: 'innerCode'
      },
      catalogTree: [], // 栏目列表
      catalogInnercode: ''
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (!to.params.ID) {
      this.item = ''
    } else {
      this.item = to.params.ID
      this.currentReport = to.params.name
    }
    this.loadCatalogHit()
    next()
  },
  methods: {
    async showChart() {
      // 指定图表的配置项和数据
      var catalogHitOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}'
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          right: '50px',
          data: this.catalogHitDataArray.map(function (obj) { return obj.name })
        },
        series: [
          {
            name: '栏目',
            type: 'pie',
            center: ['45%', '50%'],
            radius: [0, '55%'],
            data: this.catalogHitDataArray.sort(function (a, b) { return a.value - b.value }),
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 200
            }
          }
        ]
      }
      this.chartOptions = catalogHitOption
    },
    // 趋势图表
    async showTrendChart() {
      var trendOption = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: [this.itemName]
        },
        xAxis: {
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {
        },
        series: [
          {
            name: this.itemName,
            type: 'line',
            symbol: 'none',
            smooth: true,
            data: this.yData
          }
        ]
      }
      this.trendOption = trendOption
    },
    dateRangeChange(val) {
      if (val && val instanceof Array) {
        this.startDate = val[0]
        this.endDate = val[1]
      } else {
        this.dateRangeValue = []
        this.startDate = ''
        this.endDate = ''
      }
    },
    tdateRangeChange(val) {
      if (val && val instanceof Array) {
        this.tStartDate = val[0]
        this.tEndDate = val[1]
      } else {
        this.tdateRangeValue = []
        this.startDate = ''
        this.endDate = ''
      }
    },
    refresh() {
      this.loadCatalogHit()
    },
    check() {
      this.loadCatalogHit()
    },
    showTrend(item, itemName) {
      this.item = item
      this.itemName = itemName
      this.tdateRangeValue = this.dateRangeValue
      this.tStartDate = this.startDate
      this.tEndDate = this.endDate
      this.trendDialog = true
      this.loadTrend()
    },
    trendCheck() {
      this.loadTrend()
    },

    itemView(code, name) {
      if (code) {
        this.$router.push({ params: { ID: code, name: name } })
      }
    },

    async loadCatalogHit() {
      this.dataLoading = true
      let resp
      try {
        resp = await axios.get('/ui/stats/cataloghit', {
          params: {
            code: this.item,
            startdate: this.startDate,
            enddate: this.endDate,
            catalogInnercode: this.catalogInnercode
          }
        })
        this.dataLoading = false
      } catch (e) {
        this.dataLoading = false
        return
      }
      if (resp.data.status !== 1) {
        return resp.data
      }
      this.catalogHit = resp.data.data
      let chartData = this.catalogHit.map(function (obj) {
        return {
          name: obj.itemName,
          value: obj.PV
        }
      })
      if (chartData.length > MAX_CHART_ITEM_COUNT) {
        let chartDataTemp = chartData.splice(MAX_CHART_ITEM_COUNT)
        let otherValue = _.sum(_.map(chartDataTemp, 'value'))
        chartData.push({
          name: '其他',
          value: otherValue
        })
      }
      this.catalogHitDataArray = chartData
      this.showChart()
    },
    async loadTrend() {
      this.chartLoading = true
      let startdate = this.tStartDate
      let enddate = this.tEndDate
      let item = this.item
      let type = 'Catalog'
      let subType = 'PV'
      let resp
      try {
        resp = await axios.get('/ui/stats/trend', {
          params: {
            startdate,
            enddate,
            item,
            type,
            subType
          }
        })
        this.chartLoading = false
      } catch (e) {
        this.chartLoading = false
        return
      }
      if (resp.data.status !== 1) {
        return resp.data
      }
      this.trend = resp.data.data
      this.xData = this.trend.map(function (obj) { return obj.date })
      let yName = this.item
      this.yData = this.trend.map(function (obj) { return obj[yName] })
      this.showTrendChart()
    },
    async initDate() {
      this.dataLoading = true
      let res
      try {
        res = await axios.get('/ui/stats/summary/initdate')
        this.dataLoading = false
      } catch (e) {
        this.dataLoading = false
        return
      }
      if (res.data.status === 1) {
        this.startDate = res.data.data.startDate
        this.endDate = res.data.data.endDate
        this.dateRangeValue = []
        this.dateRangeValue.push(this.startDate)
        this.dateRangeValue.push(this.endDate)
      }
    }
  },
  async created() {
    await this.initDate()
    this.loadCatalogHit()
    axios.get('/ui/catalog').then(res => {
      this.catalogTree = res.data.data
    })
  }
}

</script>

<style scoped>
.padding-top-bottom .search-bar {
  padding-bottom: 5px;
}
.toolbar-body-flex{
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.date-top {
  top: 1px;
}
</style>
