<template>
  <div class="layout-no-cols reports-info">
    <div>
      <el-card class="box-card" style="margin-bottom:20px;">
        <div slot="header" class="clearfix">
          <el-button type="text" size="small" @click="showReportChart" style="cursor:pointer;float:right;">
              <i class="fa fa-refresh f14"></i> 刷新</el-button>
          <h4 class="f18 bold">报表信息</h4>
        </div>
        <div style="min-height:250px;" v-loading="reportChartLoading">
          <el-row>
            <el-col :span="6" class="report-item-wrap" v-for="(item,index) in reportChartData" :key="index">
              <el-row class="report-item">
                <el-col :span=8>
                  <div class="report-item-icon"  :class="item.code"><i class="fa" :class="reportIcons[index]"></i></div>
                </el-col>
                <el-col :span="16">
                  <em v-text="item.value"></em>
                  <h4 v-text="item.name"></h4>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-row :gutter="18">
        <el-col :span="12" v-for="(item, index) in resourceOptions" :key="index" :id="'chart_' + index">
          <el-card class="box-card" style="margin:0 0 20px">
            <div v-loading="dashbordChartLoading">
              <echarts :options="item" height="300px"></echarts>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-card class="box-card" style="margin-top:0px;">
        <div slot="header" class="clearfix">
          <el-button type="text" size="small" @click="loadTableData" style="cursor:pointer;float:right;">
              <i class="fa fa-refresh f14"></i> 刷新</el-button>
          <h4 class="f18 bold">检测信息</h4>
        </div>
        <el-table :data="detectors" tooltip-effect="dark" style="width: 100%" v-loading="tableDataLoading">
          <el-table-column type="index" label="序号" width="76" align="center"></el-table-column>
          <el-table-column prop="name" label="名称" width="150" align="center"></el-table-column>
          <el-table-column prop="code" label="项" width="180" align="center"></el-table-column>
          <el-table-column label="结果" width="76" align="center">
            <template slot-scope="scope">
              <i class="fa fa-check icon-success" v-if="scope.row.result==='Y'"></i>
              <i class="fa fa-times icon-danger" v-else></i>
            </template>
          </el-table-column>
          <el-table-column label="信息">
            <template slot-scope="scope">
              <div v-html="scope.row.info"></div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import Echarts from '@src/components/Echarts.vue'
import util from '@src/common/util.js'

export default {
  components: {
    echarts: Echarts
  },
  data() {
    return {
      timerObj: {
        timer: null,
        count: 15000
      }, // 定时器相关
      xData: [],
      resourceChart: null, // 资源监视图表数据
      reportChartData: [],
      reportChartOptions: {},
      reportChartLoading: true, // 报表信息数据加载状态
      dashbordChartLoading: true, // 资源监视数据加载状态
      tableDataLoading: true, // 数据表格数据加载状态
      detectors: [], // 数据表格数据
      chartList: [], // 资源监视列表
      initDashBordData: [] // 资源监视数据初始值
    }
  },
  computed: {
    resourceOptions() {
      if (this.resourceChart !== null) {
        var charts = []
        for (let i = 0; i < this.resourceChart.length; i++) {
          let chartItem = this.resourceChart[i]
          if (chartItem.chartType === 'line') {
            charts.push(this.buildLineOptions(chartItem))
          } else {
            charts.push(this.buildDiskChartOptions(chartItem))
          }
        }
        return charts
      } else {
        return [{}, {}, {}, {}]
      }
    },
    reportIcons() {
      var icons = []
      for (let i = 0; i < this.reportChartData.length; i++) {
        let code = this.reportChartData[i].code
        let icon = 'fa-area-chart'
        if (code === 'ZDBranch') {
          icon = 'fa-sitemap'
        } else if (code === 'ZDRole') {
          icon = 'fa-users'
        } else if (code === 'ZDUser') {
          icon = 'fa-user'
        } else if (code === 'ZCSite') {
          icon = 'fa-home'
        } else if (code === 'ZCCatalog') {
          icon = 'fa-list'
        } else if (code === 'ZCContent') {
          icon = 'fa-file-text-o'
        } else if (code === 'ZCResources') {
          icon = 'fa-database'
        } else if (code === 'ZCTemplate') {
          icon = 'fa-file-code-o'
        }
        icons.push(icon)
      }
      return icons
    }
  },
  methods: {
    // 显示所有chart/table
    showAllChart() {
      this.showReportChart()
      this.showDashboardChart(true)
      this.loadTableData()
    },
    // 设置自动刷新资源监视图表
    setAutoRefreshDashBoard() {
      const self = this
      this.timerObj['timer'] = setInterval(function () {
        self.showDashboardChart(false)
        self.timerObj['count']--
        if (!self.timerObj['count'] || !self.$route.path.endsWith('platform/detector')) {
          self.clearInterval()
        }
      }, 2000)
    },
    clearInterval() {
      this.timerObj['timer'] !== null && clearInterval(this.timerObj['timer'])
    },
    // 加载数据表格数据
    async loadTableData() {
      this.tableDataLoading = true
      let resp
      try {
        resp = await axios.get('/ui/detectors')
      } catch (e) {
        this.tableDataLoading = false
        return
      }
      this.tableDataLoading = false
      this.detectors = resp.data.status === 1 ? resp.data.data : []
    },
    // 构建线型图表
    buildLineOptions(opts) {
      return {
        title: {
          text: '资源监视'
        },
        legend: {
          show: true,
          right: '50px',
          selectedMode: false,
          data: [{
            name: opts.label,
            icon: 'circle'
          }]
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          show: false,
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          boundaryGap: [0, '100%']
        },
        series: [{
          name: opts.label,
          type: 'line',
          smooth: true,
          symbol: 'none',
          sampling: 'average',
          itemStyle: {
            normal: {
              color: opts.color[0]
            }
          },
          areaStyle: {
            normal: {
              color: new window.echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: opts.color[1]
              }, {
                offset: 1,
                color: opts.color[2]
              }])
            }
          },
          data: opts.value
        }]
      }
    },
    // 构建磁盘图表
    buildDiskChartOptions(data) {
      let pathArr = []

      let totalArr = []

      let usedArr = []

      let freeArr = []

      let ratioArr = []

      let yAxisArr = []

      let emptyArr = []
      if (data.value && data.value.length > 0) {
        for (let i = 0; i < data.value.length; i++) {
          let diskObj = data.value[i]
          if (diskObj.total > 5) { // 大于5G的磁盘才纳入统计图表显示
            pathArr.push(diskObj.path)
            totalArr.push(diskObj.total)
            usedArr.push(diskObj.used)
            freeArr.push(diskObj.free)
            ratioArr.push(diskObj.ratio)
            yAxisArr.push('Disk #' + (i + 1))
            emptyArr.push(0)
          }
        }
      }
      // 容器元素的宽度
      let containerElementWidth = document.getElementById('chart_3').offsetWidth
      let textDisplayWidth = 60
      let scale = this.toDecimal(textDisplayWidth / (containerElementWidth - textDisplayWidth))
      let maxTotalSpace = totalArr.reduce((a, b) => b > a ? b : a)
      let minSpaceCanDisplay = this.toDecimal(maxTotalSpace * scale)

      // 处理已使用空间的文本显示位置，空间不够时，不显示
      let complexUsedArr = []
      usedArr.forEach(used => {
        if (used < minSpaceCanDisplay) {
          let label = {
            value: used,
            label: {
              normal: {
                show: false
              }
            }
          }
          complexUsedArr.push(label)
        } else {
          complexUsedArr.push(used)
        }
      })
      // 处理空闲空间的文本显示位置，空间不够时，显示在右边
      let complexFreeArr = []
      freeArr.forEach(free => {
        if (free < minSpaceCanDisplay) {
          let label = {
            value: free,
            label: {
              normal: {
                position: 'right'
              }
            }
          }
          complexFreeArr.push(label)
        } else {
          complexFreeArr.push(free)
        }
      })
      return {
        title: {
          text: '资源监视'
        },
        color: ['#5CAB34'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params, ticket, callback) {
            let idx = params[0].dataIndex

            return `${yAxisArr[idx]}<br />盘符：${pathArr[idx]}<br />总空间：${totalArr[idx]} G<br />已用空间：${usedArr[idx]}G<br />空闲空间：${freeArr[idx]}G<br />使用率：${ratioArr[idx]}`
          }
        },
        legend: {
          show: true,
          right: '50px',
          selectedMode: false,
          data: [{
            name: data.label || '磁盘使用率',
            icon: 'circle'
          }]
        },
        grid: {
          left: '3%',
          right: scale * 100 + '%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: yAxisArr
        },
        series: [{
          name: '已用空间',
          type: 'bar',
          stack: '总量',
          label: {
            normal: {
              formatter: '{c}G',
              rich: {
                a: {
                  fontWeight: 'bold'
                }
              },
              position: 'insideRight',
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: function (value) {
                let index = value.dataIndex
                let ratioStr = ratioArr[index]
                let ratio = parseFloat(ratioStr.replace('%', ''))
                if (ratio >= 95) {
                  return '#F56C6C'
                } else if (ratio >= 50) {
                  return '#E6A23C'
                } else {
                  return '#67C23A'
                }
              }
            }
          },
          data: complexUsedArr
        },
        {
          name: '空闲空间',
          type: 'bar',
          stack: '总量',
          label: {
            normal: {
              show: true,
              formatter: '{c}G',
              position: 'insideRight'
            }
          },
          itemStyle: {
            normal: {
              color: '#cccccc'
            }
          },
          data: complexFreeArr
        },
        { //  空值，加上用于显示右上角的legend如果非必须可以考虑去掉
          name: data.label || '磁盘使用率',
          type: 'bar',
          stack: '总量',
          label: {
            normal: {
              show: false
            }
          },
          data: emptyArr
        }
        ]
      }
    },
    toDecimal(x) {
      var f = parseFloat(x)
      f = Math.round(x * 100) / 100
      return f
    },
    async loadResourceCharts() {
      const resp = await axios.get('/ui/detectors/initchartdata')
      this.resourceChart = resp.data.status === 1 ? resp.data.data.chartData : null
      this.xData = resp.data.status === 1 ? resp.data.data.xData : null
    },
    // 加载资源监视列表
    async loadChartlist() {
      let res = await axios.get('/ui/detectors/chartlist')
      let data = res.data
      this.chartList = data.status === 1 ? data.data : []
    },
    // 显示报表信息图表
    async showReportChart() {
      this.reportChartLoading = true
      let res
      try {
        res = await axios.get('/ui/detectors/reportchartdata')
      } catch (e) {
        this.reportChartLoading = false
        return
      }
      this.reportChartLoading = false
      let data = res.data
      this.reportChartData = data.status === 1 ? data.data : []
    },

    // 显示资源监视图表
    async showDashboardChart(showLoading) {
      this.dashbordChartLoading = showLoading
      let res
      try {
        res = await axios.get('/ui/detectors/chartdata')
      } catch (e) {
        this.dashbordChartLoading = false
        return
      }
      let data = res.data
      let chartdata = data.status === 1 ? data.data : []
      this.initDashBordData = !this.initDashBordData.length ? [...chartdata] : this.initDashBordData
      if (this.xData.length >= 30) {
        this.xData.shift()
      }
      this.xData.push(util.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'))
      for (let i = 0; i < chartdata.length - 1; i++) {
        if (this.xData.length >= 30) {
          this.resourceChart[i].value.shift()
        }
        this.resourceChart[i].value.push(chartdata[i].value)
      }
    }
  },
  async created() {
    await util.loadJS('lib/echarts.common.min.js')
    this.loadResourceCharts()
    this.loadChartlist()
    this.showAllChart()
    this.setAutoRefreshDashBoard()
  }
}

</script>
<style scoped>
  .card-title {
    font-size: 16px;
    display: inline-block;
    line-height: 28px;
    padding: 2px 14px 0;
    border-bottom: 1px solid #97c2ff;
    color: #5c769a;
    font-weight: normal;
  }
  .report-item-wrap {
    padding:10px;
  }
  .report-item{
    background:#FAFAFA;
    border:solid 1px #EBEEF5;
    padding:10px;
    text-align: center;
  }
  .report-item-icon{
    font-size:30px;
    line-height: 62px;
  }
  .report-item em {
    font-size:32px;
    color:#495057;
    font-style:bold;
 }
 .report-item h4{
   font-size:15px;
   color:#9aa0ac !important;
   font-style:normal;
 }
</style>
<style>
.reports-info {margin: 0 10px;}
.reports-info .box-card .el-card__header {padding: 0 20px;}
.reports-info .box-card .el-card__header h4 {height: 60px; line-height: 60px;}
.reports-info .box-card .el-button--text {height: 60px;}
</style>
