<template>
  <div>
    <Row :gutter="20">
      <i-col :xs="12" :md="8" :lg="6" v-for="(infor, i) in inforCardData" :key="`infor-${i}`" style="height: 150px;padding-bottom: 10px;color:#333;">
        <router-link v-if = "i === 0" :to="{name:'applicationList', query:{key:'0'}}">
          <infor-card shadow :color="infor.color" :icon="infor.icon" :icon-size="36" style="border-radius: 10px;">
            <count-to :end="infor.count" count-class="count-style"/>
            <p style="color:#999999">{{ infor.title }}</p>
          </infor-card>
        </router-link>

        <router-link v-else-if = "i === 1" :to="{name:'userList'}">
          <infor-card shadow :color="infor.color" :icon="infor.icon" :icon-size="36" style="border-radius: 10px;">
            <count-to :end="infor.count" count-class="count-style"/>
                <p style="color:#999999">{{ infor.title }}</p>
          </infor-card>
        </router-link>

        <infor-card v-else shadow :color="infor.color" :icon="infor.icon" :icon-size="36" style="border-radius: 10px;">
          <count-to :end="infor.count" count-class="count-style"/>
          <p style="color:#999999">{{ infor.title }}</p>
        </infor-card>
      </i-col>
    </Row>

    <Table border width="80%" :columns="columnsList" :data="statReport" class="portStats__tab">
        <template slot-scope="{ row }" slot="name">
            <strong>{{ row.name }}</strong>
        </template>
    </Table>

    <h3>{{this.$t('yesterday_active_app')}}({{statReportYesterday.length}})</h3>
    <Table border width="80%" :columns="columnsListYesterday" :data="statReportYesterday" class="portStats__tab">
    </Table>

    <div ref="myChart" id="my_chart" class="content-layer" :style="{width: '100%', height: '400px', margin: '20px 0'}"></div>
    <Card class="homeCard">
        <p>{{$t('operating_environment')}}：<small><span v-for="item in systemInfo" :key='item.id'>{{ item.content }} / </span></small></p>
    </Card>
  </div>
</template>

<script>
import InforCard from '_c/info-card'
import { GetDataFlowApi, GetAppDailyStatReport } from '@/api/stats'
import CountTo from '_c/count-to'
import { ChartPie, ChartBar } from '_c/charts'
import Example from './example.vue'
import { indexGetIndexData } from '@/api/home'
import { getToken } from '@/libs/util'
import echarts from 'echarts'
export default {
  name: 'home',
  components: {
    InforCard,
    CountTo,
    ChartPie,
    ChartBar,
    Example
  },
  data () {
    return {
      // objjj: { name: '状态码:200', type: 'line', stack: '总量' },
      token: getToken(),
      statusArr: [], // 状态
      statusData: [], // 不同状态的数据
      statReport: [],
      statReportYesterday: [],
      dataStatusObj: [{}],
      colorArr: ['#ff00ea', '#9000ff', '#2d8cf0', '#1935be', '#ff9900', '#ffcc00', '#ff4800'],
      dataColorArr: [],
      xAxisTimeData: [], // 时间数据
      systemInfo: [], // 运行环境
      columnsList: [
        {
          title: this.$t('date'),
          key: 'stat_day',
          align: 'center'
        },
        {
          title: this.$t('total_order_num'),
          key: 'total_order',
          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('active_app_num'),
          key: 'app_key_visit',
          align: 'center'
        },
        {
          title: 'UV',
          key: 'user_visit',
          align: 'center'
        },
        {
          title: this.$t('api_request_times'),
          key: 'api_request_times',
          align: 'center'
        }
      ],
      columnsListYesterday: [
        {
          title: this.$t('date'),
          key: 'stat_day',
          align: 'center'
        },
        {
          title: this.$t('app_key'),
          key: 'app_key',
          align: 'center'
        },
        {
          title: this.$t('active_app_num'),
          key: 'app_key_visit',
          align: 'center'
        },
        {
          title: 'UV',
          key: 'user_visit',
          align: 'center'
        },
        {
          title: this.$t('api_request_times'),
          key: 'api_request_times',
          align: 'center'
        }
      ],
      inforCardData: [
        { title: this.$t('app_to_be_reviewed'), icon: 'md-apps', count: 0, color: '#ed3f14' },
        { title: this.$t('total_accounts'), icon: 'ios-people', count: 0, color: '#ff9900' },
        { title: this.$t('today_api_request'), icon: 'md-analytics', count: 0, color: '#2d8cf0' },
        { title: this.$t('total_api'), icon: 'md-git-network', count: 0, color: '#19be6b' }
      ]
    }
  },
  // 获取首页数据
  created () {
    const formdata = new FormData()
    formdata.append('access_token', this.token)
    indexGetIndexData(formdata).then(res => {
      const resData = res
      if (resData.ret === 200) {
        this.inforCardData[0].count = resData.data.to_verify_apps // todo
        this.inforCardData[1].count = resData.data.users
        this.inforCardData[2].count = resData.data.requestTime
        this.inforCardData[3].count = resData.data.apiNum
        this.systemInfo = resData.data.systemInfo
      } else {
        this.$Message.error(resData.msg)
      }
    })

    GetAppDailyStatReport(formdata).then(res => {
      if (res.ret === 200) {
        this.statReport = res.data.report
        this.statReportYesterday = res.data.report_yesterday
      }
    })
  },
  mounted () {
    this.getQuery()
  },
  methods: {
    turnPage () {
      this.$router.push({ name: 'paltform_permissions_assign' })
    },
    // 接口数据统计
    getQuery () {
      const formdata = new FormData()
      formdata.append('access_token', this.token)
      GetDataFlowApi(formdata).then(res => {
        // this.statusArr = []
        res.data.ret.forEach(item => {
          this.statusData.push({ status: item, data: [] })
          item = this.$t('ret_status') + item
          this.statusArr.push(item)
          this.dataStatusObj.push({})
        })
        const loginData = res.data.data
        this.xAxisTimeData = []
        this.$nextTick(() => {
          loginData.forEach((item, index) => {
            this.xAxisTimeData.push(item.time) // 获取时间
            for (let i in item) {
              this.statusData.forEach(itemStatus => {
                // console.log(i, itemStatus.status, 'itemmmmmmm')
                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()
        })
      })
    },
    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: '4%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.xAxisTimeData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        /* series: [
          {
            name: '状态码:200',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            data: this.allData
          },
          {
            name: '状态码:400',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            data: this.allData
          }
        ], */
        series: this.dataStatusObj,
        // series: this.objjj,
        color: this.dataColorArr
      }
      myChartData.setOption(option)
      // 建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）。超过了div的界限（红色边框）
      window.addEventListener('resize', function () { myChartData.resize() })
    }
  }
}
</script>

<style lang="less">
.count-style{
  font-size: 50px;
}
.homeCard{
  background: #fff;
  border-radius: 10px;
}
</style>
