<template>
  <el-tabs
    class="redis-fullheight"
    v-model="activeName"
    @tab-click="handleClick"
    :tab-position="tabPosition"
  >
    <el-tab-pane label="Redis图表信息" name="first">
      <div style="display: flex; justify-content: space-around">
        <div>
          <h1 class="tabletit">Radis 内存实时占用情况（KB）</h1>
          <div id="Memory" :style="{width: '400px', height: '400px'}"></div>
        </div>
        <div>
          <h1 class="tabletit">Radis Key 实时数量（个）</h1>
          <div id="Keys" :style="{width: '400px', height: '400px'}"></div>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane label="Redis表格信息" style="height: 100%" name="second" >
      <!-- <h1 class="tabletit">Redis 详细信息</h1> -->
      <div class="request fullheight">
        <div style="display: flex">
          <el-button type="primary" class="load" size="mini" @click="loadings()"
            >刷新</el-button
          >
        </div>
        <el-table
          :data="
            tableData.slice((currpage - 1) * pagesize, currpage * pagesize)
          "
          v-loading="loading"
          border
          stripe
          style="width: 100%"
          height="485px"
        >
          <el-table-column
            label="序号"
            width="50px"
            align="center"
            type="index"
          >
          </el-table-column>
          <el-table-column
            prop="key"
            label="参数"
            width="200px"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="value"
            label="当前值"
            width="200px"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currpage"
          :page-sizes="[10, 100, 200, 300, 400]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        >
        </el-pagination>
      </div>
    </el-tab-pane>
    <!-- Redis缓存信息  -->
    <el-tab-pane label="Redis缓存信息" name="three">
      <div class="fullheight request">
        <div style="display: flex">
          <el-input
            v-model="input"
            placeholder="请输入key值名称搜索"
            style="width: 40%; margin-bottom: 10px"
            clearable
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 10px; margin-bottom: 10px"
            @click="handelSearch"
          >
            <i class="el-icon-search"> 搜索 </i>
          </el-button>
          <el-button
            type="info"
            style="margin-left: 10px; margin-bottom: 10px"
            @click="handelRefresh"
          >
            <i class="el-icon-refresh"> 重置 </i>
          </el-button>
        </div>

        <el-table
          :data="data.slice((currpage - 1) * pagesize, currpage * pagesize)"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
          height="485px"
        >
          <el-table-column
            label="序号"
            align="center"
            width="50px"
            type="index"
          >
          </el-table-column>
          <el-table-column prop="key" label="参数" align="center">
          </el-table-column>
          <el-table-column prop="sn" label="操作" width="250px" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="showCache(scope)">查看</el-button>
              <el-button type="danger" @click="clickTest(scope)"
                >清除缓存</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currpage"
          :page-sizes="[10, 100, 200, 300, 400]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.length"
        >
        </el-pagination>
      </div>

      <ht-sidebar-dialog
        width="50%"
        title="任务执行器信息"
        class="sp-manager__dialog"
        :closeOnClickModal="true"
        :visible="dialogVisible"
        :before-close="beforeCloseDialog"
      >
        <el-form>
          <el-form-item label="KEY">
            <el-input :value="sequence.key"></el-input>
          </el-form-item>
          <el-form-item label="VALUE">
            <el-input
              type="textarea"
              rows="35"
              :value="sequence.value"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- <el-input
          readonly
          placeholder="请输入内容"
          v-model="sequence.key"
        >
          <template slot="prepend">
            <div :style="{width: '100px', display: 'inline-block'}">
              KEY
            </div>
          </template>
        </el-input>
        <el-input
          readonly
          placeholder="请输入内容"
          v-model="sequence.value"
        >
          <template slot="prepend">
            <div :style="{width: '100px', display: 'inline-block'}">
              VALUE
            </div>
          </template>
        </el-input> -->

        <div slot="footer" style="text-align: right">
          <el-button @click="beforeCloseDialog" type="danger">关闭</el-button>
        </div>
      </ht-sidebar-dialog>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import * as echarts from 'echarts'
import portal from '@/api/portal.js'
import req from '@/request.js'
export default {
  data() {
    return {
      input: '',
      activeName: 'first',
      tableData: [],
      key: {
        title: 'Radis Key 实时数量（个）',
        dataSource: [],
        y: '数量（个）',
        height: 340,
        num: [],
      },
      // 内存实时占用情况
      memory: {
        title: 'Radis 内存实时占用情况（KB）',
        dataSource: [],
        y: '内存（KB）',
        num: [],
      },
      loading: true,
      currpage: 1,
      pagesize: 10,
      // 定时器ID
      timer: null,
      // 定时器周期
      millisec: 3000,
      tabPosition: 'left',
      url: {
        keysSize: '/monitor/actuator/v1/redis/keysSize',
        memoryInfo: '/monitor/actuator/v1/redis/memoryInfo',
      },
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      data: [],
      dialogVisible: false,
      sequence: {},
      querySearch: [
        {
          label: 'key名称',
          prop: 'key',
        },
      ],
    }
  },
  mounted() {
    this.openTimer()
    this.loadRedisInfo()
    this.loadData()
    setTimeout(() => {
      this.getMemory()
      this.getKey()
      this.draw()
      this.draws()
    }, 3000)
  },
  beforeDestroy() {
    this.closeTimer()
  },
  methods: {
    handleClick(tab, event) {},

    openTimer() {
      this.getMemory()
      this.getKey()
      this.closeTimer()
      this.timer = setInterval(() => {
        if (this.$route.path === this.path) {
          this.getMemory()
          this.getKey()
        }
      }, this.millisec)
    },
    /** 关闭定时器 */
    closeTimer() {
      if (this.timer) clearInterval(this.timer)
    },
    /** 查询数据 */
    getMemory() {
      portal.getAction(this.url.memoryInfo).then((res) => {
        this.memory.dataSource.push(
          this.$moment(res.create_time).format('h:mm:ss')
        )
        let num = res.used_memory / 1000
        this.memory.num.push(num)
        this.draw()
      })
    },
    getKey() {
      portal.getAction(this.url.keysSize).then((res) => {
        this.key.dataSource.push(
          this.$moment(res.create_time).format('h:mm:ss')
        )
        let num = res.dbSize
        this.key.num.push(num)
        this.draws()
      })
    },
    //绘制echarts
    draw() {
      let chartDom = document.getElementById('Memory')
      let myChart = echarts.init(chartDom)
      let option
      option = {
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.memory.dataSource,
        },
        yAxis: {
          type: 'value',
        },

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        series: [
          {
            data: this.memory.num,
            type: 'line',
            areaStyle: {},
          },
        ],
      }
      option && myChart.setOption(option)
      //防止越界，重绘canvas
      window.onresize = myChart.resize
      myChart.setOption(option) //设置option
    },
    draws() {
      let chartDom = document.getElementById('Keys')
      let myChart = echarts.init(chartDom)
      let option
      option = {
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.key.dataSource,
        },
        yAxis: {
          type: 'value',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        series: [
          {
            data: this.key.num,
            type: 'line',
            areaStyle: {},
          },
        ],
      }
      option && myChart.setOption(option)
      //防止越界，重绘canvas
      window.onresize = myChart.resize
      myChart.setOption(option) //设置option
    },
    loadRedisInfo() {
      portal.getRedis().then((res) => {
        this.tableData = res
        this.loading = false
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
    },
    handleCurrentChange(val) {
      this.currpage = val
    },
    loadings() {
      this.loadRedisInfo()
    },
    // readis缓存
    loadData(param, cb) {
      // console.log(param)
      // let data = {}
      // if (param.querys) {
      //   data.key = param.querys[0].value
      // }
      // data = this.qs.stringify(data)
      portal.getAllCache(param).then((res) => {
        let arrAt = []
        // let i = 0
        for (let item in res) {
          // i = i + 1
          //console.log(i, '多次次')
          arrAt.push({key: item, value: res[item]})
        }
        this.data = arrAt
        // this.pageResult = {
        //   page: i / 50,
        //   pageSize: 50,
        //   total: i
        // }
        // this.$refs.htTable.loading = false
      })
    },
    showCache(data) {
      this.dialogVisible = true
      this.sequence.key = data.row.key
      this.sequence.value = JSON.stringify(data.row.value)
      console.log(this.sequence)
    },
    clickTest(data) {
      // console.log(key, 'key')
      //console.log(this.$refs.htTable.selection)
      // if (this.$refs.htTable.selection.length == 0) {
      //   this.$message({
      //     type: 'error',
      //     message: '请至少选择一条数据'
      //   })
      //   return
      // }
      // console.log(this.deleteCacheArray, 'array')
      portal.deleteCache(data.row.key).then((res) => {
        return this.loadData()
      })
    },
    beforeCloseDialog() {
      this.sysCache = {}
      this.dialogVisible = false
    },
    afterDelete() {
      this.$refs.htTable.load()
    },
    //redis缓存根据key值查询
    handelSearch() {
      let arr = []
      if (this.input !== '') {
        portal.getKeyCache(this.input).then((res) => {
          for (let item in res) {
            arr.push({key: item, value: res[item]})
          }
          this.currpage = 1
          this.data = arr
        })
      } else {
        this.loadData()
      }
    },
    //搜索重置按钮
    handelRefresh() {
      this.input = ''
      this.loadData()
    },
  },
}
</script>

<style lang="scss" scoped>
// /deep/ .ht-table{
//   height: 100%!important;
//   max-height: 100%!important;
// }
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}
.tabletit {
  font-size: 18px;
  padding: 10px 0;
}
.load {
  margin-bottom: 15px;
}
body {
  margin: 0;
}
/* 设置滚动条的样式 */
/deep/ ::-webkit-scrollbar {
  width: 8px;
  background-color: #fff;
}

/* 滚动槽 */
/deep/ ::-webkit-scrollbar-track {
  border-radius: 8px;
}

/* 滚动条滑块 */
/deep/ ::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background: #eee;
}
/deep/.el-table th {
  background: #eee !important;
  border-bottom: 1px solid #fff !important;
  border-right: 1px solid #fff !important;
}
/deep/.el-table th > .cell {
  font-family: Microsoft YaHei;
  font-size: 14px;
  font-weight: 700;
  color: #3c4353;
}
/deep/.el-button--mini {
  width: 56px;
  height: 31px;
}

.request {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
/deep/ .el-pagination {
  width: auto;
  background: #fff;
  position: static !important;
  margin-left: auto;
  padding: 5px 5px;
}
/deep/.el-tab-pane {
  height: 100%;
  /deep/ .el-tabs {
    height: 100% !important;
  }
}
#pane-Redismonitor /deep/ .el-tabs{
  height: 100% !important;
}
/deep/ .el-tabs__content {
  height: 100% !important;
}
.redis-fullheight.el-tabs--left{
 height: 100% !important;
}
</style>
