<template>
  <div class="right-list-toobar">
    <el-toolbar>
      <el-button :plain="true" @click="refresh"><i class="fa fa-refresh"></i>刷新</el-button>
      <el-col>当前报表：被访主机分析</el-col>
      <el-col align="right">
        <el-date-picker id="host-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 :plain="true" @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="host" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="item" label="名称"></el-table-column>
        <el-table-column prop="rate" label="PV比例"></el-table-column>
        <el-table-column prop="host" label="PV"></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="host-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 :plain="true" @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'
const MAX_CHART_ITEM_COUNT = 10 // 饼图最多显示数
export default {
  components: {
    echarts: Echarts
  },
  data() {
    return {
      chartLoading: false,
      dataLoading: false,
      host: [], // 被访主机
      hostDataArray: [], // 被访主机图表配置数据
      trend: [], // 被访主机点击量数据
      dateRangeValue: [],
      startDate: '', // 搜索框日期范围
      endDate: '',
      trendDialog: false, // 趋势查看框
      tdateRangeValue: [],
      tStartDate: '', // 趋势查看框日期范围
      tEndDate: '',
      item: '', // 当前被访主机名称
      xData: [], // 趋势图表数据
      yData: [],
      chartOptions: {},
      trendOption: {}

    }
  },
  methods: {
    async showChart() {
      // 指定图表的配置项和数据
      var hostOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}'
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          right: '50px',
          data: this.hostDataArray.map(function (obj) { return obj.item })
        },
        series: [
          {
            name: '被访主机',
            type: 'pie',
            center: ['45%', '50%'],
            radius: [0, '55%'],
            data: this.hostDataArray.sort(function (a, b) { return a.value - b.value }),
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 200
            }
          }
        ]
      }
      this.chartOptions = hostOption
    },
    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.loadHost()
    },
    check() {
      this.loadHost()
    },
    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 loadTrend() {
      this.chartLoading = true
      let startdate = this.tStartDate
      let enddate = this.tEndDate
      let item = this.item
      let type = 'Source'
      let subType = 'Host'
      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 loadHost() {
      this.dataLoading = true
      let startdate = this.startDate
      let enddate = this.endDate
      let resp
      try {
        resp = await axios.get('/ui/stats/host', {
          params: {
            startdate,
            enddate
          }
        })
        this.dataLoading = false
      } catch (e) {
        this.dataLoading = false
        return
      }
      if (resp.data.status !== 1) {
        return resp.data
      }
      this.host = resp.data.data
      // 配置被访主机图表数据
      let chartData = this.host.map(function (obj) {
        return {
          name: obj.item,
          value: obj.host
        }
      })
      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.hostDataArray = chartData

      this.showChart()
    },
    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.loadHost()
  }
}

</script>

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

</style>
