<template>
  <div class="portStats">
      <Row class="portStats__query">
        <span>{{$t('date')}}：</span>
        <Col>
            <DatePicker :value="dateRange" :options="optionsFuture" type="daterange" placement="bottom-end" style="width: 400px" @on-change="changeDateRange"></DatePicker>
        </Col>

        <span style="margin-left: 30px;">{{$t('app_key')}}：</span>
        <Input class="" clearable v-model="statAppKey" :placeholder="$t('statAppKey_tip')" style="width: 250px" />

        <Button type="primary" class="portStats__query__btn" @click="getQuery">{{$t('refresh')}}</Button>
    </Row>
    <div ref="myChart" id="my_chart" :style="{width: '100%', height: '400px'}"></div>
    <Table border width="80%" :columns="columnsList" :data="appData" :loading="appLoad" class="portStats__tab">
    </Table>
  </div>
</template>

<script>
import { GetAppStatReport } from '@/api/stats'
import { getToken, defaultDateRange } from '@/libs/util'
import echarts from 'echarts'
export default {
  data () {
    return {
      token: getToken(),
      appLoad: false,
      xAxisTimeData: [], // 时间数据
      allData: [], // 全部注册
      appData: [], // 全部数据
      dateRange: ['', ''],
      statAppKey: '', // 为空时表示全部应用
      columnsList: [
        {
          title: this.$t('date'),
          key: 'stat_day',
          align: 'center'
        },
        {
          title: this.$t('app_key'),
          key: 'app_key',
          align: 'center'
        },
        {
          title: this.$t('API_traffic_statistics'),
          key: 'api_request_times',
          align: 'center'
        },
        {
          title: this.$t('active_app_num'),
          key: 'app_key_visit',
          align: 'center'
        },
        {
          title: this.$t('UV'),
          key: 'user_visit',
          align: 'center'
        },
        {
          title: this.$t('total_app_num'),
          key: 'total_app',
          align: 'center'
        },
        {
          title: this.$t('total_user_num'),
          key: 'total_user',
          align: 'center'
        },
        {
          title: this.$t('total_order_num'),
          key: 'total_order',
          align: 'center'
        },
      ],
      optionsFuture: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      }
    }
  },
  created () {
    let dr = defaultDateRange()
    this.dateRange[0] = dr.starttime
    this.dateRange[1] = dr.endtime
    this.getQuery()
  },
  mounted () {
  },
  methods: {
    getQuery () {
      this.appLoad = true
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('stat_app_key', this.statAppKey)
      console.log(this.dateRange)
      formdata.append('start_day', this.dateRange[0])
      formdata.append('end_day', this.dateRange[1])
      GetAppStatReport(formdata).then(res => {
        this.appData = res.data.report
        this.xAxisTimeData = []
        this.allData = []
        this.appLoad = false
        this.appData.forEach(item => {
          this.xAxisTimeData.push(item.stat_day)
          this.allData.push(item.api_request_times)
        })
        this.createEchars()
      })
    },
    changeDateRange (e) {
      // 包含结束当天
      this.dateRange = [e[0] + ' 00:00:00', e[1] + ' 23:59:59']
    },
    createEchars () {
      let myChartData = echarts.init(this.$refs.myChart)
      let option = {
        // 标题
        title: {
          text: this.$t('statistics_app')
        },
        tooltip: {
          trigger: 'axis'
        },
        // 标注
        legend: {
          right: '20%',
          data: [this.$t('API_traffic_statistics')]
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        // X轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisTimeData
        },
        // Y轴
        yAxis: {
          type: 'value'
        },
        // 显示
        series: [
          {
            name: this.$t('API_traffic_statistics'),
            type: 'line',
            data: this.allData,
            markPoint: {
              data: [
                { type: 'max', name: this.$t('max_value') },
                { type: 'min', name: this.$t('min_value') }
              ]
            },
            markLine: {
              data: [
                { type: 'average', name: this.$t('agv_value') }
              ]
            }
          }
        ]
      }
      myChartData.setOption(option)
      // 建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）。超过了div的界限（红色边框）
      window.addEventListener('resize', function () { myChartData.resize() })
    }
  }

}
</script>

<style  lang="scss" scoped>
.portStats{
  &__query{
    height:72px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 30px;
    &__btn{
      margin-left: 30px;
    }
  }
  &__tab{
    background: #fff;
    border-radius: 10px;
  }
}
#my_chart{
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 20px;
}
/deep/.ivu-input{
  text-align: center;
}
</style>
