<template>
  <PageWrapper>
    <div class="cache-box">
      <a-card title="缓存列表">
        <a-table
          :style="{ minHeight: fwbHeight + 'px' }"
          :scroll="{ x: '100%', y: fwbHeight + 'px' }"
          :dataSource="cacheNameData"
          :columns="cacheNameColumns"
          row-key="cacheName"
          :customRow="onCheckedCacheName"
          :rowSelection="{
            type: 'radio',
            selectedRowKeys: selectedName,
            onChange: handleNameChange,
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="danger" @click="handleDelete(record, 'cacheName')">
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </template>
          </template>
        </a-table>
      </a-card>
      <a-card title="键名列表">
        <a-table
          :columns="cacheKeyColumns"
          row-key="cacheKey"
          :style="{ minHeight: fwbHeight + 'px' }"
          :scroll="{ x: '100%', y: fwbHeight + 'px' }"
          :dataSource="cacheKeyData"
          :customRow="onCheckedCachKey"
          :rowSelection="{ type: 'radio', selectedRowKeys: selectedKey, onChange: handleKeyChange }"
        >
          >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="danger" @click="handleDelete(record, 'cacheKey')">
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </template>
          </template>
        </a-table>
      </a-card>
      <a-card>
        <template #title>
          <div class="clearfix">
            <span>缓存内容</span>
            <a-button @click="clearAll" style="float: right; padding: 3px 0" type="text">
              <template #icon><RedoOutlined /></template>
              清理全部
            </a-button>
          </div>
        </template>
        <a-form
          ref="form"
          :model="formData"
          :label-col="{ style: { width: '80px' } }"
          layout="vertical"
          v-if="cacheKeyData.length > 0"
        >
          <a-form-item label="缓存名称：">
            <a-input v-model:value="formData.cacheName" />
          </a-form-item>
          <a-form-item label="缓存键值：">
            <a-input v-model:value="formData.cacheKey" />
          </a-form-item>
          <a-form-item label="缓存内容：">
            <a-input v-model:value="formData.cacheValue" type="textarea" />
          </a-form-item>
        </a-form>
        <div v-else>暂无数据</div>
      </a-card>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import { RedoOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import {
    getCacheNames,
    getCacheKeys,
    getCacheValue,
    deleteCacheName,
    deleteCacheKey,
    deleteCacheAll,
  } from '@/api/monitor/caches';
  import { Modal, message } from 'ant-design-vue';
  import { cacheNameColumns } from './cacheNameColumns';
  import { cacheKeyColumns } from './cacheKeyColumns';

  /**
   * 定义参数变量
   */
  const cacheNameData = ref([]);
  const cacheKeyData = ref([]);

  const selectedName = ref([]);
  const selectedKey = ref([]);

  /**
   * 定义表单数据
   */
  const formData = reactive({
    cacheKey: '',
    cacheName: '',
    cacheValue: '',
    message: '',
  });
  const cacheName = ref('');
  const cacheKey = ref('');
  const fwbHeight = document.body.clientHeight - 320;

  /**
   * 选择缓存名发生变化事件
   * @param record 参数
   */
  const onCheckedCacheName = (record) => {
    return {
      onClick: () => {
        cacheName.value = record.cacheName;
        selectedName.value = [];
        selectedName.value.push(cacheName.value);
        if (cacheName.value) {
          loadCachekeys();
        }
      },
    };
  };

  /**
   * 执行名称发生变化
   * @param value 参数
   */
  const handleNameChange = (value) => {
    cacheName.value = value[0];
    selectedName.value = value;
    if (cacheName.value) {
      loadCachekeys();
    }
  };

  /**
   * 选择缓存key
   * @param record 参数
   */
  const onCheckedCachKey = (record) => {
    return {
      onClick: () => {
        cacheKey.value = record.cacheKey;
        selectedKey.value = [];
        selectedKey.value.push(cacheKey.value);
        if (cacheKey.value) {
          loadCacheValue();
        }
      },
    };
  };

  /**
   * 执行缓存KEY发生变化
   * @param value 参数
   */
  const handleKeyChange = (value) => {
    cacheKey.value = value[0];
    selectedKey.value = value;
    if (cacheKey.value) {
      loadCacheValue();
    }
  };

  /**
   * 加载缓存名列表
   */
  const loadCacheNames = async () => {
    const result = await getCacheNames();
    cacheNameData.value = result;
    cacheName.value = result.length > 0 ? result[0].cacheName : '';
    selectedName.value = [];
    selectedName.value.push(cacheName.value);
    if (cacheName.value) {
      loadCachekeys();
    }
  };

  /**
   * 加载缓存key列表
   */
  const loadCachekeys = async () => {
    let datas = [];
    const result = await getCacheKeys(cacheName.value);
    result.map((item) => {
      let len = item.split(':').length;
      datas.push({
        cacheKey: item.split(':')[len - 1],
      });
    });
    cacheKeyData.value = datas;
    cacheKey.value = datas.length > 0 ? datas[0].cacheKey : '';
    selectedKey.value = [];
    selectedKey.value.push(cacheKey.value);
    if (cacheKey.value) {
      loadCacheValue();
    }
  };

  /**
   * 加载缓存value列表
   */
  const loadCacheValue = async () => {
    const data = await getCacheValue({ cacheName: cacheName.value, cacheKey: cacheKey.value });
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
  };

  /**
   * 执行删除
   * @param row 数据行
   * @param type 类型
   */
  const handleDelete = async (row, type) => {
    Modal.confirm({
      title: '提示',
      content: '确定要删除？',
      onOk: async () => {
        if (type == 'cacheName') {
          await deleteCacheName(row.cacheName);
          message.success('删除成功');
          loadCacheNames();
        } else {
          await deleteCacheKey(row.cacheKey);
          message.success('删除成功');
          loadCachekeys();
        }
      },
    });
  };

  /**
   * 清楚全部缓存
   */
  const clearAll = async () => {
    Modal.confirm({
      title: '提示',
      content: '确定要清理全部？',
      onOk: async () => {
        await deleteCacheAll();
        loadCacheNames();
      },
    });
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    loadCacheNames();
  });
</script>
<style lang="less">
  .cache-box {
    display: flex;
    > .ant-card {
      flex: 1;
      &:nth-child(2) {
        margin: 0 15px;
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
