<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-toolbar>
    <div v-loading="dataLoading">
      <echarts :options="chartOptions" height="300px"></echarts>
      <div style="margin:10px">

      </div>
      <el-table :data="language" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="item" label="名称"></el-table-column>
        <el-table-column prop="language" label="PV数量"></el-table-column>
        <el-table-column prop="rate" label="比例"></el-table-column>
        <el-table-column label="趋势">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="showTrend(scope.row)">{{scope.row.trend}}</a>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 趋势查看框 -->
    <el-dialog title="时间趋势" :visible.sync="trendDialog">
      <div>
        日期范围:&nbsp;
        <el-date-picker id="language-date-picker" v-model="trendDateRange" type="daterange" placeholder="选择日期范围"></el-date-picker>&nbsp;&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 util from '@src/common/util.js'
import Echarts from '@src/components/Echarts.vue'
const MAX_CHART_ITEM_COUNT = 10 // 饼图最多显示数
export default {
  components: {
    echarts: Echarts
  },
  data() {
    return {
      dataLoading: false,
      language: [], // 语言
      languageDateArray: [], // 语言图表配置数据
      languageTrend: [], // 语言趋势数据
      trendDialog: false, // 趋势查看框
      trendDateRange: [], // 趋势查看框日期范围
      trendChartLegend: [], // 趋势图表配饰数据
      trendChartSeries: [],
      temTrendItem: '',
      temTrendLangItem: '',
      chartOptions: {},
      trendOption: {}
    }
  },
  methods: {
    async showChart() {
      // 指定图表的配置项和数据
      var languageOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}'
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          right: '50px',
          data: this.languageDataArray.map(function (obj) { return obj.name })
        },
        series: [
          {
            name: '语言',
            type: 'pie',
            center: ['45%', '50%'],
            radius: [0, '55%'],
            data: this.languageDataArray.sort(function (a, b) { return a.value - b.value }),
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 200
            }
          }
        ]
      }
      this.chartOptions = languageOption
    },
    async showTrendChart() {
      var trendOption = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.trendChartLegend
        },
        xAxis: {
          boundaryGap: false,
          data: this.languageTrend.map(function (obj) { return obj.date })
        },
        yAxis: {

        },
        series: [
          {
            name: this.temTrendItem,
            type: 'line',
            symbol: 'none',
            smooth: true,
            data: this.trendChartSeries
          }
        ]
      }
      this.trendOption = trendOption
    },
    refresh() {
      this.getLanguageEchars()
    },
    async showTrend(row) {
      this.trendDateRange = []
      var currentDate = new Date()
      // 时间区段为30天
      currentDate.setDate(currentDate.getDate() - 30)
      let startDate = util.formatDate(currentDate, 'yyyy-MM-dd')
      let endDate = util.formatDate(new Date(), 'yyyy-MM-dd')
      this.trendDateRange.push(currentDate)
      this.trendDateRange.push(new Date())
      this.trendDialog = true
      this.temTrendItem = row.item
      let temItem = row.item.toLowerCase()
      this.temTrendLangItem = row.langItem
      this.trendChartLegend.pop()
      this.trendChartLegend.push(row.item)

      let params = {
        startDate: startDate,
        endDate: endDate,
        type: 'Client',
        subType: 'language',
        item: row.langItem
      }
      let res = await axios.get('/ui/stats/trendreport', {params: params}).catch(e => console.log(e))
      let data = res.data
      this.languageTrend = data.data
      this.trendChartSeries = this.languageTrend.map(function (obj) { return obj[temItem] })
      this.showTrendChart()
    },
    async trendCheck() {
      if (this.trendDateRange && this.trendDateRange.length === 2 && this.trendDateRange[0] && this.trendDateRange[1]) {
        let startDate = util.formatDate(this.trendDateRange[0], 'yyyy-MM-dd')
        let endDate = util.formatDate(this.trendDateRange[1], 'yyyy-MM-dd')
        let temItem = this.temTrendItem.toLowerCase()
        let params = {
          startDate: startDate,
          endDate: endDate,
          type: 'Client',
          subType: 'language',
          item: this.temTrendLangItem
        }
        let res = await axios.get('/ui/stats/trendreport', {params: params}).catch(e => console.log(e))
        let data = res.data
        this.languageTrend = data.data
        this.trendChartSeries = this.languageTrend.map(function (obj) { return obj[temItem] })
        this.showTrendChart()
      } else {
        this.$alert('请选择日期范围', '提示', 'warning')
      }
    },
    async getLanguageTableData() {
      this.dataLoading = true
      let res
      try {
        res = await axios.get('/ui/stats/clientreport', {
          params: {
            subType: 'Language',
            showType: 'DataTable'
          }
        })
        this.dataLoading = false
      } catch (e) {
        this.dataLoading = false
        return
      }
      let data = res.data
      this.language = data.data
    },
    async getLanguageEchars() {
      let params = {
        subType: 'Language',
        showType: 'ECharts'
      }
      let res = await axios.get('/ui/stats/clientreport', {params: params}).catch(e => console.log(e))
      let data = res.data
      this.language = data.data
      // 初始化语言饼图数据
      let chartData = this.language.map(function (obj) {
        return {
          name: obj.item,
          value: obj.language
        }
      })
      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.languageDataArray = chartData
      this.showChart()
      this.getLanguageTableData()
    }
  },
  created() {
    this.getLanguageTableData()
  },
  mounted() {
    this.getLanguageEchars()
  }
}

</script>

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

</style>
