<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="24" class="card-box">
        <el-card>
          <div slot="header"><span><i class="el-icon-monitor"></i> 基本信息</span></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%">
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf"><div class="cell">缓存类型</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cacheTypeText }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">运行模式</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cacheModeText }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">总键数</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ displayDbSize }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">写入次数</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cache.info.write_count }}</div></td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf"><div class="cell">命中次数</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cache.info.hit_count }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">未命中次数</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cache.info.miss_count }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">过期清理次数</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ cache.info.expired_count }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">命中率</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ hitRateText }}</div></td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf"><div class="cell">统计说明</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">进程内累计统计</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">监控范围</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">当前应用实例</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">图表数据项</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ commandStats.length }}</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">监控采样时间</div></td>
                  <td class="el-table__cell is-leaf"><div class="cell">{{ sampleTime }}</div></td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12" class="card-box">
        <el-card>
          <div slot="header"><span><i class="el-icon-pie-chart"></i> 命令统计</span></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="commandstats" style="height: 420px" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="12" class="card-box">
        <el-card>
          <div slot="header"><span><i class="el-icon-odometer"></i> 缓存命中概览</span></div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="usedmemory" style="height: 420px" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getCache } from "@/api/monitor/cache"
import * as echarts from "echarts"

export default {
  name: "Cache",
  data() {
    return {
      // 统计命令信息
      commandstats: null,
      // 缓存统计
      usedmemory: null,
      // cache信息
      cache: {
        info: {
          cache_type: "IN_MEMORY",
          cache_mode: "single-instance",
          key_size: 0,
          hit_count: 0,
          miss_count: 0,
          expired_count: 0,
          write_count: 0
        },
        dbSize: 0,
        commandStats: []
      },
      sampleTime: "-",
      resizeHandler: null
    }
  },
  created() {
    this.openLoading()
    this.getList()
  },
  beforeDestroy() {
    if (this.resizeHandler) {
      window.removeEventListener("resize", this.resizeHandler)
    }
    if (this.commandstats) {
      this.commandstats.dispose()
    }
    if (this.usedmemory) {
      this.usedmemory.dispose()
    }
  },
  computed: {
    cacheTypeText() {
      return this.formatCacheType(this.cache.info.cache_type)
    },
    cacheModeText() {
      return this.formatCacheMode(this.cache.info.cache_mode)
    },
    displayDbSize() {
      return this.toNumber(this.cache.dbSize || this.cache.info.key_size)
    },
    hitRateText() {
      const hitCount = this.toNumber(this.cache.info.hit_count)
      const missCount = this.toNumber(this.cache.info.miss_count)
      const total = hitCount + missCount
      if (!total) {
        return "0.00%"
      }
      return ((hitCount / total) * 100).toFixed(2) + "%"
    },
    commandStats() {
      return this.normalizeCommandStats(this.cache.commandStats)
    }
  },
  methods: {
    /** 查缓存询信息 */
    getList() {
      getCache().then((response) => {
        this.cache = this.normalizeCacheData(response.data)
        this.sampleTime = this.formatSampleTime(new Date())
        this.$modal.closeLoading()
        this.$nextTick(() => {
          this.renderCharts()
        })
      }).catch(() => {
        this.cache = this.normalizeCacheData()
        this.sampleTime = "-"
        this.$modal.closeLoading()
      })
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载缓存监控数据，请稍候！")
    },
    normalizeCacheData(data) {
      const source = data || {}
      const info = source.info || {}
      return {
        info: {
          cache_type: info.cache_type || "IN_MEMORY",
          cache_mode: info.cache_mode || "single-instance",
          key_size: this.toNumber(info.key_size),
          hit_count: this.toNumber(info.hit_count),
          miss_count: this.toNumber(info.miss_count),
          expired_count: this.toNumber(info.expired_count),
          write_count: this.toNumber(info.write_count)
        },
        dbSize: this.toNumber(source.dbSize || info.key_size),
        commandStats: source.commandStats || []
      }
    },
    normalizeCommandStats(commandStats) {
      const stats = Array.isArray(commandStats) ? commandStats : []
      return stats.map((item) => ({
        name: this.statLabel(item.name),
        value: this.toNumber(item.value)
      }))
    },
    statLabel(name) {
      const labelMap = {
        hit_count: "命中次数",
        miss_count: "未命中次数",
        expired_count: "过期清理次数",
        write_count: "写入次数"
      }
      return labelMap[name] || name || "未命名统计"
    },
    formatCacheType(type) {
      const typeMap = {
        IN_MEMORY: "进程内缓存"
      }
      return typeMap[type] || type || "-"
    },
    formatCacheMode(mode) {
      const modeMap = {
        "single-instance": "单实例"
      }
      return modeMap[mode] || mode || "-"
    },
    formatSampleTime(date) {
      const current = date || new Date()
      const pad = (value) => String(value).padStart(2, "0")
      return `${current.getFullYear()}-${pad(current.getMonth() + 1)}-${pad(current.getDate())} ${pad(current.getHours())}:${pad(current.getMinutes())}:${pad(current.getSeconds())}`
    },
    toNumber(value) {
      const parsedValue = Number(value)
      return Number.isFinite(parsedValue) ? parsedValue : 0
    },
    renderCharts() {
      if (!this.commandstats) {
        this.commandstats = echarts.init(this.$refs.commandstats, "macarons")
      }
      if (!this.usedmemory) {
        this.usedmemory = echarts.init(this.$refs.usedmemory, "macarons")
      }
      this.commandstats.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series: [
          {
            name: "缓存统计",
            type: "pie",
            roseType: "radius",
            radius: [15, 95],
            center: ["50%", "38%"],
            data: this.commandStats,
            animationEasing: "cubicInOut",
            animationDuration: 1000
          }
        ]
      })
      this.usedmemory.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        xAxis: {
          type: "category",
          data: this.commandStats.map((item) => item.name),
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: "value",
          minInterval: 1
        },
        series: [
          {
            name: "统计次数",
            type: "bar",
            barMaxWidth: 48,
            data: this.commandStats.map((item) => item.value)
          }
        ]
      })
      if (!this.resizeHandler) {
        this.resizeHandler = () => {
          this.commandstats && this.commandstats.resize()
          this.usedmemory && this.usedmemory.resize()
        }
        window.addEventListener("resize", this.resizeHandler)
      }
    }
  }
}
</script>
