<template>
  <div class="right-list-toobar">
    <el-toolbar>
      <el-button @click="refresh"><i class="fa fa-refresh"></i>刷新</el-button>
      <el-col>当前报表：搜索引擎</el-col>
      <el-col align="right">
        <el-date-picker id="searchEngine-date-picker1" v-model="dateRangeValue" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择日期范围" @change="dateRangeChange"></el-date-picker>&nbsp;
        <el-button @click="check" class="button" type="primary"><slot name="button">查看</slot></el-button>
      </el-col>
    </el-toolbar>
    <div v-loading="dataLoading">
      <echarts :options="chartOptions" height="300px"></echarts>
      <div style="margin:10px">

      </div>
      <el-table :data="searchEngine" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="item" label="名称"></el-table-column>
        <el-table-column prop="rate" label="比例"></el-table-column>
        <el-table-column prop="searchEngine" label="UV"></el-table-column>
        <el-table-column label="趋势">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="showTrend(scope.row.item)">时间趋势</a>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 趋势查看框 -->
    <el-dialog title="时间趋势" :visible.sync="trendDialog">
      <div>
        <el-date-picker id="searchEngine-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">
        <echarts :options="trendOption" height="300px"></echarts>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Echarts from '@src/components/Echarts.vue'
const MAX_CHART_ITEM_COUNT = 10 // 饼图最多显示数
export default {
  components: {
    echarts: Echarts
  },
  data() {
    return {
      dataLoading: false,
      searchEngine: [], // 搜索引擎
      searchEngineDataArray: [], // 搜索引擎图表配置数据
      trend: [], // 搜索引擎趋势数据
      dateRangeValue: [],
      startDate: '', // 搜索框日期范围
      endDate: '',
      trendDialog: false, // 趋势查看框
      tdateRangeValue: [],
      tStartDate: '', // 趋势查看框日期范围
      tEndDate: '',
      xData: [], // 趋势图表配饰数据
      yData: [],
      item: '', // 当前项
      chartOptions: {},
      trendOption: {}
    }
  },
  methods: {
    async showChart() {
      // 指定图表的配置项和数据
      var searchEngineOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}'
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          right: '50px',
          data: this.searchEngineDataArray.map(function (obj) { return obj.name })
        },
        series: [
          {
            name: '搜索引擎',
            type: 'pie',
            center: ['45%', '50%'],
            radius: [0, '55%'],
            data: this.searchEngineDataArray.sort(function (a, b) { return a.value - b.value }),
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 200
            }
          }
        ]
      }
      this.chartOptions = searchEngineOption
    },
    // 趋势图表
    async showTrendChart() {
      var trendOption = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.item
        },
        xAxis: {
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {

        },
        series: [
          {
            name: this.item,
            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.loadSearchEngine()
    },
    check() {
      this.loadSearchEngine()
    },
    showTrend(item) {
      this.item = item
      this.tdateRangeValue = this.dateRangeValue
      this.tStartDate = this.startDate
      this.tEndDate = this.endDate
      this.trendDialog = true
      this.loadTrend()
    },
    trendCheck() {
      this.loadTrend()
    },
    async loadSearchEngine() {
      this.dataLoading = true
      let startdate = this.startDate
      let enddate = this.endDate
      let resp
      try {
        resp = await axios.get('/ui/stats/searchengine', {
          params: {
            startdate,
            enddate
          }
        })
        this.dataLoading = false
      } catch (e) {
        this.dataLoading = false
        return
      }
      if (resp.data.status !== 1) {
        return resp.data
      }
      this.searchEngine = resp.data.data
      // 初始化搜索引擎饼图数据
      let chartData = this.searchEngine.map(function (obj) {
        return {
          name: obj.item,
          value: obj.searchEngine
        }
      })
      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.searchEngineDataArray = chartData

      this.showChart()
    },
    async loadTrend() {
      let startdate = this.tStartDate
      let enddate = this.tEndDate
      let item = this.item
      let type = 'Source'
      let subType = 'SearchEngine'
      let resp = await axios.get('/ui/stats/trend', {
        params: {
          startdate,
          enddate,
          item,
          type,
          subType
        }
      })
      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() {
      let res = await axios.get('/ui/stats/summary/initdate')
      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.loadSearchEngine()
  }
}

</script>

<style scoped>
  .padding-top-bottom .search-bar {
    padding-bottom: 5px;
  }

</style>
