<template>
  <div class="portStats">
     <!-- <p>接口统计</p> -->
      <Row class="portStats__query">
        <span>{{$t('date')}}：</span>
        <Col>
            <DatePicker :value="dateRange" :options="optionsFuture" format="yyyy-MM-dd" type="daterange" placement="bottom-end" style="width: 400px" @on-change="changeDateRange"></DatePicker>
        </Col>
        <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>
  </div>
</template>

<script>
import { GetDataFlowApi } from '@/api/stats'
import { getToken, defaultDateRange } from '@/libs/util'
import echarts from 'echarts'
export default {
  data () {
    return {
      token: getToken(),
      xAxisTimeData: [], // 时间数据
      allData: [], // 全部注册
      statusArr: [], // 状态
      statusData: [], // 不同状态的数据
      dataStatusObj: [{}],
      colorArr: ['#ff00ea', '#9000ff', '#2d8cf0', '#1935be', '#ff9900', '#ffcc00', '#ff4800'],
      dataColorArr: [],
      dateRange: ['', ''],
      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()
  },
  methods: {
    // 刷新统计
    getQuery () {
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      formdata.append('start_time', this.dateRange[0])
      formdata.append('end_time', this.dateRange[1])
      GetDataFlowApi(formdata).then(res => {
        /* 刷新清空  防止数据叠加 */
        this.statusArr = []
        this.statusData = []
        this.dataStatusObj = [{}]

        const loginData = res.data.data
        this.xAxisTimeData = []
        res.data.ret.forEach(item => {
          this.statusData.push({ status: item, data: [] })
          item = this.$t('ret_status') + ' ' + item
          this.statusArr.push(item)
          this.dataStatusObj.push({})
        })
        loginData.forEach(item => {
          this.xAxisTimeData.push(item.time)
          for (let i in item) {
            this.statusData.forEach(itemStatus => {
              if (Number(i) === itemStatus.status) {
                itemStatus.data.push(item[i])
              }
            })
          }
        })
        this.statusArr.forEach((item, index) => {
          if (item === (this.$t('ret_status') + ' 200')) {
            this.dataColorArr.push('#139554')
          } else if (item === (this.$t('ret_status') + ' 400')) {
            this.dataColorArr.push('#ff0000')
          } else {
            this.dataColorArr.push(this.colorArr[index])
          }
          this.statusData.forEach(itemData => {
            if (Number(item.replace(/[^0-9]/ig, '')) === itemData.status) {
              this.dataStatusObj[index].data = itemData.data
            }
          })
          this.dataStatusObj[index].name = item
          this.dataStatusObj[index].smooth = true
          this.dataStatusObj[index].areaStyle = {}
          this.dataStatusObj[index].stack = this.$t('total')
          // this.dataStatusObj[index].data = this.statusData[index].data
        })
        this.dataStatusObj.forEach(item => {
          item.type = 'line'
        })
        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('API_traffic_statistics')
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          right: '10%',
          data: this.statusArr
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.xAxisTimeData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: this.dataStatusObj,
        color: this.dataColorArr
      }
      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;
    }
  }
}
#my_chart{
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
}
/deep/.ivu-input{
  text-align: center;
}
</style>
