<template>
  <div class="layout-no-cols nginx-sync-info">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="f18 bold">同步目录</span>
      </div>
      <el-row v-loading="dataLoading">
        <el-col :span="10">
          <div class="folder-item">
            <div class="server-icon">
              <i class="fa fa-server"></i>
              <span class="status-icon status-icon-1" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.1s;animation-delay: 0.1s;"></span>
              <span class="status-icon status-icon-2" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.3s;animation-delay: 0.4s;"></span>
              <span class="status-icon status-icon-3" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.5s;animation-delay: 0.5s;"></span>
            </div>
            <dl>
              <dt>源目录</dt>
              <dd v-text="origFolder"></dd>
            </dl>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="server-data-arrow"><i class="animated infinite fa fa-send" :class="{'sendFly': !dataLoading}"></i></div>
        </el-col>
        <el-col :span="10">
          <div class="folder-item">
            <div class="server-icon">
              <i class="fa fa-server"></i>
              <span class="status-icon status-icon-1" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.4s;animation-delay: 0.4s;"></span>
              <span class="status-icon status-icon-2" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.3s;animation-delay: 0.2s;"></span>
              <span class="status-icon status-icon-3" :class="{'serverLight': !dataLoading}" style="-webkit-animation-delay: 0.7s;animation-delay: 0.7s;"></span>
            </div>
            <dl>
              <dt>目标目录</dt>
              <dd v-text="destFolder"></dd>
            </dl>
          </div>
        </el-col>
      </el-row>
    </el-card>
      <div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="f18 bold">实时数据</span>
          </div>
          <div>
            <div style="min-height:200px;" v-loading="dataLoading">
              <el-row>
                <el-col :span="8" class="report-item-wrap" v-for="(item,index) in reportData" :key="index">
                  <div class="report-item">
                    <div>
                      <em v-text="item.value"></em>
                      <span v-text="item.labelExtra"></span>
                    </div>
                    <h4 v-text="item.label"></h4>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>

      </div>

      <div class="charts">
        <el-row :gutter="18">
          <el-col :span="12" v-for="(item, index) in resourceOptions" :key="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>

      </div>

      <div style="display:none;">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="f18 bold">同步日志</span>
          </div>
          <div v-loading="dataLoading">
            <textarea></textarea>
          </div>
        </el-card>
      </div>
  </div>
</template>
<script>
import Echarts from '@src/components/Echarts.vue'
import util from '@src/common/util.js'
const AUTO_REFRESH_REQUEST_COUNT = 10000 // 最大请求次数,避免长时间停留页面没有操作浪费服务器资源的情况
const AUTO_REFRESH_TIMER_INTERVAL = 3000 // 刷新数据请求间隔时间，单位为ms
let preSyncData = null // 上次同步数据，用于图表计算差值
export default {
  name: 'NginxSync',
  components: {
    echarts: Echarts
  },
  data() {
    return {
      timerObj: {
        timer: null, // 定时器对象
        count: 0 // 已请求次数
      },
      dataLoading: true,
      nginxData: {},
      dashbordChartLoading: false,
      resourceChart: null,
      xData: []
    }
  },
  created() {
    this.init()
  },
  computed: {
    // 源目录
    origFolder() {
      let nginxData = this.nginxData
      return nginxData && nginxData.origFolder ? nginxData.origFolder : '获取中'
    },
    // 目标目录
    destFolder() {
      let nginxData = this.nginxData
      return nginxData && nginxData.destFolder ? nginxData.destFolder : '获取中'
    },
    reportData() {
      let nginxData = this.nginxData
      if (nginxData && nginxData.destFolder) {
        let arr = []
        arr.push({ label: '总同步文件大小', value: nginxData.totalFileSize || 0, labelExtra: 'Mb' })
        arr.push({ label: '总同步文件数', value: nginxData.totalFileCount || 0, labelExtra: '个' })
        arr.push({ label: '删除文件大小', value: nginxData.syncFileSize || 0, labelExtra: 'Mb' })
        arr.push({ label: '删除文件数', value: nginxData.deleteFileCount || 0, labelExtra: '个' })
        arr.push({ label: '更新文件大小', value: nginxData.updateFileSize || 0, labelExtra: 'Mb' })
        arr.push({ label: '更新文件数', value: nginxData.updateFileCount || 0, labelExtra: '个' })
        // arr.push({ label: '传输速率', value: nginxData.speedRate || 0.00, labelExtra: 'Mb/s' })
        arr.push({ label: 'nginx当前连接数', value: nginxData.nginxActiveConnection || 0, labelExtra: '个' })
        arr.push({ label: 'nginx总请求数', value: nginxData.nginxHandledRequests || 0, labelExtra: '次' })
        arr.push({ label: 'nginx空闲连接数', value: nginxData.nginxWaitingCount || 0, labelExtra: '个' })
        return arr
      } else {
        return []
      }
    },
    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))
          }
        }
        return charts
      } else {
        return [{}, {}, {}, {}]
      }
    }
  },
  // 离开当前路由时清理掉定时任务
  beforeRouteLeave (to, from, next) {
    this.clearRefreshTimer()
    next()
  },
  methods: {
    async init () {
      this.requestData()
      await util.loadJS('lib/echarts.common.min.js')
      await this.loadResourceCharts()
      this.dataLoading = false
      this.startAutoRefreshData()
    },
    async requestData() {
      let ajaxData = await axios.get(`/ui/nginxsync?random=${Date.now()}`)
      if (ajaxData.data.status === 1) {
        this.nginxData = ajaxData.data.data
        this.freshChartData()
      } else {
        util.showResponseMessage(ajaxData.data)
      }
    },
    startAutoRefreshData() {
      this.timerObj.timer = setInterval(() => {
        this.requestData()
        this.timerObj.count++
        if (this.timerObj.count >= AUTO_REFRESH_REQUEST_COUNT) {
          this.clearRefreshTimer()
        }
      }, AUTO_REFRESH_TIMER_INTERVAL)
    },
    clearRefreshTimer() {
      this.timerObj['timer'] !== null && clearInterval(this.timerObj['timer'])
    },
    // 构建线型图表
    buildLineOptions(opts) {
      return {
        title: {
          text: opts.label
        },
        legend: {
          show: false,
          right: '50px',
          selectedMode: false,
          data: [{
            name: opts.label,
            icon: 'circle'
          }]
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          show: false,
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {
          type: 'value'
        },
        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
        }]
      }
    },
    async loadResourceCharts() {
      const resp = await axios.get('/ui/nginxsync/chartdata')
      this.resourceChart = resp.data.status === 1 ? resp.data.data.chartData : null
      this.xData = resp.data.status === 1 ? resp.data.data.xData : null
    },
    freshChartData() {
      if (preSyncData === null) {
        preSyncData = this.nginxData
        return null
      }
      if (this.xData.length >= 30) {
        this.xData.shift()
      }
      this.xData.push(util.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'))
      let fileCount = this.nginxData.totalFileCount - preSyncData.totalFileCount
      let fileSize = this.nginxData.totalFileSize - preSyncData.totalFileSize
      let activeCount = this.nginxData.nginxActiveConnection
      let requestTimes = this.nginxData.nginxHandledRequests - preSyncData.nginxHandledRequests
      var chartData = [fileCount, fileSize, activeCount, requestTimes]
      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])
      }
      preSyncData = this.nginxData
    }
  }
}
</script>
<style scoped>
  .folder-item {
    text-align:center
  }
  .server-icon{
    width:128px;
    height: 128px;
    margin: 0 auto;
    line-height:128px;
    text-align:center;
    border:solid 1px #dedede;
    border-radius:50%;
    position: relative;
  }
  .status-icon{
    width: 7px;
    height: 7px;
    display:block;
  border-radius: 50%;
    position: absolute;
    left: 85px;
    top: 40px;
    -webkit-animation-duration: 0.3s;
    animation-duration: 0.3s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
  }
  .status-icon-2{
    top: 58px;
  }
  .status-icon-3{
    top: 77px;
  }
  .server-icon i.fa {
    font-size:64px;
    color: #a3a3a3;
    line-height: inherit;
  }
  .folder-item dl{
    margin-top: 15px;
    line-height: 32px;
  }
  .folder-item dt {
    border-bottom: solid 1px #dedede;
    font-weight:bold;
    font-size:18px;
    line-height:inherit;
  }
  .folder-item dd {
    font-size:16px;
    line-height:inherit;
  }
  .server-data-arrow {
    text-align: center;
    padding-top: 47px;
  }
  .server-data-arrow i.fa {
    font-size: 32px;
    color:#a3a3a3;
  }
  .server-data-arrow i.fa:before {
    display:block;
    transform: rotate(40deg)
  }
  .report-item-wrap {
    padding: 10px;
  }
  .report-item {
    background:#FAFAFA;
    border:solid 1px #EBEEF5;
    padding: 35px 10px;
    cursor: default;
    text-align: center;
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
  }
  .report-item:hover {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1)
  }
  .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;
  }
  textarea {
    height: 500px;
    width: 100%;
    border: solid 1px #dedede;
    padding: 8px;
    border-radius: 4px;
  }
  .animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
.animated.infinite {
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}
@-webkit-keyframes sendFly {
  from {
    opacity: 0.3;
    -webkit-transform: translate3d(-250px, 0, 0);
    transform: translate3d(-250px, 0, 0);
  }
  50% {
    opacity: 1;
  }
  to {
    opacity: 0;
    -webkit-transform:translate3d(280px, 0, 0);
    transform:translate3d(280px, 0, 0);
  }
}
@keyframes sendFly {
  from {
    opacity: 0.3;
    -webkit-transform: translate3d(-250px, 0, 0);
    transform: translate3d(-250px, 0, 0);
  }

  50% {
    opacity: 1;
  }

  to {
    opacity: 0;
    -webkit-transform:translate3d(280px, 0, 0);
    transform:translate3d(280px, 0, 0);
  }
}
.sendFly {
  -webkit-animation-name: sendFly;
  animation-name: sendFly;
}
@-webkit-keyframes serverLight {
  from {
    background: #E7E7E7;
    opacity: 1;
  }
  to {
    background: #03FA83;
    opacity: 0;
  }
}
@keyframes serverLight {
  from {
    background: #E7E7E7;
    opacity: 0;
  }
  to {
    background: #03FA83;
    opacity: 1;
  }
}
.serverLight {
  -webkit-animation-name: serverLight;
  animation-name: serverLight;
}
</style>
<style>

</style>
