<template>
  <div class="basediv">
    <!--span>监控报表</span-->
    <el-form inline>
      <el-form-item v-if="roles[0] === '1'" label="选择开发者">
        <el-select
          v-if="roles[0] === '1'"
          v-model="user"
          filterable
          placeholder="请选择开发者"
          clearable
          @change="getMyApps">
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择应用">
        <el-select v-model="app" clearable @change="getMyApis">
          <el-option
            v-for="item in apps"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择API">
        <el-select v-model="api" clearable>
          <el-option
            v-for="item in apis"
            :key="item.api.id"
            :label="item.api.name"
            :value="item.api.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="统计项">
        <el-radio v-model="reportItem" label="1" @change="initOption">调用量</el-radio>
      </el-form-item>
      <el-form-item label="监控项">
        <div v-if="reportItem === '1'">
          <el-checkbox v-model="monitorItem1" label="调用成功"/>
          <el-checkbox v-model="monitorItem2" label="调用失败"/>
        </div>
        <div v-if="reportItem === '2'">
          <el-checkbox v-model="monitorItem1" label="QPS峰值"/>
        </div>
      </el-form-item>
      <el-form-item label="时间段">
        <el-date-picker
          v-model="logTime"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          @change="dateChanged"
        />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="enableSearch" type="primary" @click="btn_search">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="8">
        <div v-if="reportItem ==='1'">
          <span v-if="monitorItem1 === true && byReport==='1'">调用成功 <span
            style="font-size: 18px;color: lightskyblue">{{ successCount }}   </span></span>
          <span v-if="monitorItem2 === true && byReport==='1'" style="margin-left:10px;"> 调用失败 <span
            style="font-size: 18px;color: lightgreen">{{ failCount }}</span></span><br>
        </div>
        <div v-if="reportItem ==='2'">
          <span>QPS峰值 <span style="font-size: 18px;color: lightskyblue">{{ qpsCount }}   </span></span>
        </div>
      </el-col>
      <!--      <el-col :span="8">-->
      <!--        <div style="float: right;margin-right: 30px">-->
      <!--          <el-radio v-model="byReport" label="1">图表</el-radio>-->
      <!--          <el-radio v-model="byReport" label="2" @change="clearTimer()">报表</el-radio>-->
      <!--        </div>-->
      <!--      </el-col>-->
      <el-col :span="8">
        <div v-if="byReport==='1'" style="float: right;margin-right: 30px">
          <el-radio v-if="radioRealTime" v-model="byHourOrDay" label="3" @change="startRealTimer">实时</el-radio>
          <el-radio v-if="radioHour" v-model="byHourOrDay" label="1" @change="clearTimer">按时</el-radio>
          <el-radio v-if="radioDay" v-model="byHourOrDay" label="2" @change="clearTimer">按日</el-radio>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <br>
        <div v-show="byReport === '1'" id="report" class="chart">
          <span/>
        </div>
        <!--        <el-table-->
        <!--          ref="multipleTable"-->
        <!--          :data="apiReportData"-->
        <!--          :highlight-current-row="true"-->
        <!--          class="eltable"-->
        <!--          border>-->
        <!--          <el-table-column-->
        <!--            prop="id"-->
        <!--            label="序号"/>-->
        <!--          <el-table-column-->
        <!--            prop="apiName"-->
        <!--            label="接口名称"/>-->
        <!--          <el-table-column-->
        <!--            prop="appName"-->
        <!--            label="应用名称"/>-->
        <!--          <el-table-column-->
        <!--            prop="userName"-->
        <!--            label="开发者"/>-->
        <!--          <el-table-column-->
        <!--            prop="total"-->
        <!--            label="总调用量"/>-->
        <!--          <el-table-column-->
        <!--            prop="failCount"-->
        <!--            label="调用失败"/>-->
        <!--          <el-table-column-->
        <!--            prop="failRate"-->
        <!--            label="失败率"/>-->
        <!--        </el-table>-->
      </el-col>
    </el-row>
    <el-row v-if="monitorItem2" v-show="byReport === '1'" class="reporttable">
      <el-col :span="24">
        <span>调用失败详情</span><br><br>
        <el-table
          ref="multipleTable"
          :data="tableData"
          :highlight-current-row="true"
          :border="true">
          <el-table-column
            prop="errorCode"
            label="错误码"/>
          <el-table-column
            prop="message"
            label="失败详情"/>
          <el-table-column
            prop="time"
            label="失败次数"/>
          <el-table-column
            prop="description"
            label="描述"/>
          <el-table-column
            prop="apiName"
            label="API"/>
          <el-table-column
            prop="suggestion"
            label="处理意见"/>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as echarts from 'echarts'
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'Create',
  data() {
    return {
      enableSearch: false,
      loading: false,
      radioRealTime: true,
      radioHour: true,
      radioDay: false,
      user: '',
      users: [],
      allApiObject: {
        api: { id: '全部', name: '全部' },
        app: null,
        callLimit: 0,
        id: '',
        qpsApply: '',
        qpsLimit: '',
        status: ''
      },
      allAppObject: { id: '全部', name: '全部' },
      app: '',
      api: '',
      reportItem: '1',
      monitorItem1: true,
      monitorItem2: false,
      logTime: [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
        new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              // start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
      },
      myChart: {},
      apps: [],
      apis: [],
      successCount: 0,
      failCount: 0,
      qpsCount: 0,
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      timer: '',
      byHourOrDay: '1', // 1=按时 2=按日 3=按秒(实时)
      byReport: '1', // 1=图标 2=报表
      reportDialogVisible: true,
      apiReportData: []
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  mounted() {
    this.myChart = echarts.init(document.getElementById('report'))
    this.initOption()
  },
  created() {
    if (this.roles[0] === '1') {
      this.getdAllUser()
    }
    if (this.$route.query.userId !== '' && this.$route.query.userId !== undefined) {
      this.user = this.$route.query.userId
    }
    this.getMyApps()
    if (this.$route.query.appId !== '' && this.$route.query.appId !== undefined) {
      this.app = this.$route.query.appId
      this.getMyApis()
    } else if (this.$route.query.apiId !== '' && this.$route.query.apiId !== undefined) {
      this.getMyAllApis()
      this.api = this.$route.query.apiId
      this.app = '全部'
    } else if (this.$route.query.appId === undefined) {
      this.app = '全部'
      this.api = '全部'
    }
  },
  beforeDestroy() {
    this.clearTimer()
    console.log('destroyed')
  },
  methods: {
    dateChanged() {
      var beginDate = ''
      var endDate = ''
      if (this.logTime[0] !== undefined && this.logTime[0] !== '') {
        beginDate = moment(this.logTime[0]).format('YYYY-MM-DD')
      }
      if (this.logTime[1] !== undefined && this.logTime[1] !== '') {
        endDate = moment(this.logTime[1]).format('YYYY-MM-DD')
      }
      if (beginDate === moment(new Date()).format('YYYY-MM-DD') && beginDate === endDate) {
        // 显示 实时和按时
        console.log('显示实时和按时')
        this.radioRealTime = true
        this.radioHour = true
        this.radioDay = false
        this.clearTimer()
        this.byHourOrDay = '1'
      } else if (beginDate !== moment(new Date()).format('YYYY-MM-DD') && beginDate === endDate) {
        // 显示 按时
        console.log('显示按时')
        this.radioRealTime = false
        this.radioHour = true
        this.radioDay = false
        this.clearTimer()
        this.byHourOrDay = '1'
      } else {
        // 显示 按日
        console.log('显示按日')
        this.radioRealTime = false
        this.radioHour = false
        this.radioDay = true
        this.clearTimer()
        this.byHourOrDay = '2'
      }
      this.loading = false
    },
    initOption() {
      if (this.reportItem === '1') {
        if (this.monitorItem1 === true && this.monitorItem2 === true) {
          this.myChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              data: []
            },
            yAxis: {},
            series: [{
              name: '调用成功',
              type: 'line',
              data: []
            },
            {
              name: '调用失败',
              type: 'line',
              data: []
            }]
          })
        } else if (this.monitorItem1 === true && this.monitorItem2 === false) {
          this.myChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              data: []
            },
            yAxis: {},
            series: [{
              name: '调用成功',
              type: 'line',
              data: []
            },
            {
              name: '',
              type: 'line',
              data: []
            }]
          })
        } else if (this.this.monitorItem1 === false && this.monitorItem2 === true) {
          this.myChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              data: []
            },
            yAxis: {},
            series: [{
              name: '',
              type: 'line',
              data: null
            },
            {
              name: '调用失败',
              type: 'line',
              data: []
            }]
          })
        } else if (this.this.monitorItem1 === false && this.monitorItem2 === false) {
          this.myChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              data: []
            },
            yAxis: {},
            series: [{
              name: '',
              type: 'line',
              data: []
            },
            {
              name: '',
              type: 'line',
              data: []
            }]
          })
        }
      } else if (this.reportItem === '2') {
        this.myChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['QPS峰值']
          },
          xAxis: {
            data: []
          },
          yAxis: {},
          series: [{
            name: 'QPS峰值',
            type: 'line',
            data: []
          }]
        })
      }
    },
    timerFun() {
      // console.log('timing')
      this.btn_search()
    },
    startRealTimer() {
      this.enableSearch = true
      this.startTimer()
    },
    startTimer() {
      console.log('start timer')
      this.timer = setInterval(this.timerFun, 1000)
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        console.log('clear timer')
      }
      this.enableSearch = false
    },
    getdAllUser() {
      var vm = this
      axios.get(process.env.BASE_API + '/user/listdevelopers', {
        params: {}
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.users = []
        } else {
          vm.users = obj.data
          vm.totalDeveloperNum = obj.total
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    getMyApps() {
      this.app = '全部'
      const vm = this
      axios.get(process.env.BASE_API + '/app/list', {
        params: {
          tag: this.tag,
          status: this.select_value,
          id: this.user
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apps = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.apps = obj.data
            vm.apps.unshift(vm.allAppObject)
          } else {
            vm.apps = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    getMyApis() {
      this.api = ''
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/listbyappid', {
        params: {
          appId: this.app
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apis = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.apis = obj.data
            vm.apis.unshift(vm.allApiObject)
            vm.api = '全部'
          } else {
            vm.apis = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    getMyAllApis() {
      // 当应用选择“全部”的时候，获取接口列表
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/getmyallapis', {
        params: {
          appId: this.app
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apis = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.apis = obj.data
            vm.apis.unshift(vm.allApiObject)
          } else {
            vm.apis = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_search() {
      const vm = this
      var beginDate = ''
      var endDate = ''
      if (this.loading === true) {
        return
      }
      this.loading = true
      if (this.logTime[0] !== undefined && this.logTime[0] !== '') {
        beginDate = moment(this.logTime[0]).format('YYYY-MM-DD')
      }
      if (this.logTime[1] !== undefined && this.logTime[1] !== '') {
        endDate = moment(this.logTime[1]).format('YYYY-MM-DD')
      }
      if (this.app === '' || this.app === 'undefined') {
        this.$message.info('请选择要监控的应用')
        return
      }
      if (this.api === '' || this.api === 'undefined') {
        this.$message.info('请选择要监控的接口')
        return
      }
      if (this.byReport === '1') {
        // axios.get(process.env.BASE_API + '/apilog/getapireport', {
        //   params: {
        //     selectUser: this.user,
        //     appId: this.app,
        //     apiId: this.api,
        //     beginDate: beginDate,
        //     endDate: endDate
        //   }
        // }).then(function(response) {
        //   vm.loading = false
        //   const obj = response.data
        //   if (obj.code !== 10000) {
        //     // vm.$message.error(obj.message)
        //     vm.apiReportData = []
        //   } else {
        //     if (obj.data) {
        //       vm.apiReportData = obj.data
        //     } else {
        //       vm.apiReportData = []
        //     }
        //     // vm.apiReportData = obj.data
        //   }
        // }).catch(function(error) {
        //   vm.loading = false
        //   alert(error)
        // })
        axios.get(process.env.BASE_API + '/apilog/getreportbyapi', {
          params: {
            selectUser: this.user,
            appId: this.app,
            apiId: this.api,
            reportItem: this.reportItem,
            monitorSuccess: this.monitorItem1,
            monitorFail: this.monitorItem2,
            byHourOrDay: this.byHourOrDay,
            beginDate: beginDate,
            endDate: endDate
          }
        }).then(function(response) {
          console.log(response)
          vm.loading = false
          var obj = response.data
          if (obj.code !== 10000) {
            vm.$message.error(obj.message)
            vm.apis = []
          } else {
            if (vm.reportItem === '1') {
              vm.allData = obj.data.failDetais
              if (obj.data.failDetais === undefined) {
                return
              }
              if (obj.data.failDetais.length > vm.pageSize) {
                vm.tableData = obj.data.failDetais.slice(0, vm.pageSize)
              } else {
                vm.tableData = obj.data.failDetais
              }
              vm.successCount = obj.data.success
              vm.failCount = obj.data.failed
              if (vm.monitorItem1 === true && vm.monitorItem2 === true) {
                vm.myChart.setOption({
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: ['调用成功', '调用失败']
                  },
                  xAxis: {
                    data: obj.data.categories
                  },
                  yAxis: {},
                  series: [{
                    name: '调用成功',
                    type: 'line',
                    data: obj.data.successList
                  },
                  {
                    name: '调用失败',
                    type: 'line',
                    data: obj.data.failedList
                  }]
                })
              } else if (vm.monitorItem1 === true && vm.monitorItem2 === false) {
                vm.myChart.setOption({
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: ['调用成功', '调用失败']
                  },
                  xAxis: {
                    data: obj.data.categories
                  },
                  yAxis: {},
                  series: [{
                    name: '调用成功',
                    type: 'line',
                    data: obj.data.successList
                  },
                  {
                    name: '',
                    type: 'line',
                    data: null
                  }]
                })
              } else if (vm.monitorItem1 === false && vm.monitorItem2 === true) {
                vm.myChart.setOption({
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: ['调用成功', '调用失败']
                  },
                  xAxis: {
                    data: obj.data.categories
                  },
                  yAxis: {},
                  series: [{
                    name: '',
                    type: 'line',
                    data: null
                  },
                  {
                    name: '调用失败',
                    type: 'line',
                    data: obj.data.failedList
                  }]
                })
              } else if (vm.monitorItem1 === false && vm.monitorItem2 === false) {
                vm.myChart.setOption({
                  tooltip: {
                    trigger: 'axis'
                  },
                  legend: {
                    data: ['调用成功', '调用失败']
                  },
                  xAxis: {
                    data: obj.data.categories
                  },
                  yAxis: {},
                  series: [{
                    name: '',
                    type: 'line',
                    data: null
                  },
                  {
                    name: '',
                    type: 'line',
                    data: null
                  }]
                })
              }
            } else if (vm.reportItem === '2') {
              vm.qpsCount = obj.data.qps
              vm.myChart.setOption({
                xAxis: {
                  type: 'category',
                  boundaryGap: false,
                  data: obj.data.categories
                },
                yAxis: {
                  type: 'value'
                },
                series: [{
                  data: obj.data.qpsList,
                  type: 'line',
                  areaStyle: {}
                },
                {
                  name: '',
                  type: 'line',
                  data: null
                }]
              })
            }
          }
        }).catch(function(error) {
          vm.loading = false
          alert(error)
        })
      }
    }
  }
}
</script>

<style scoped>
.basediv {
  margin-left: 30px;
}

.chart {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.reporttable {
  margin-left: 20px;
  margin-top: 30px;
  margin-right: 20px;
  margin-bottom: 50px;
}
</style>
