<template>
  <PageWrapper>
    <div class="cache-box">
      <n-card title="缓存列表">
        <n-data-table
          :style="{ minHeight: fwbHeight + 'px' }"
          :scroll="{ x: '100%', y: fwbHeight + 'px' }"
          :data="cacheNameData"
          :columns="cacheNameColumns"
          :row-props="rowNameProps"
          :row-key="(row) => row.cacheName"
          :checked-row-keys="cacheName"
          @update:checked-row-keys="handleNameChange"
        >
        </n-data-table>
      </n-card>
      <n-card title="键名列表">
        <n-data-table
          :columns="cacheKeyColumns"
          :row-key="(row) => row.cacheKey"
          :checked-row-keys="cacheKey"
          :row-props="rowKeyProps"
          :style="{ minHeight: fwbHeight + 'px' }"
          :scroll="{ x: '100%', y: fwbHeight + 'px' }"
          :data="cacheKeyData"
          @update:checked-row-keys="handleKeyChange"
        >
          >
        </n-data-table>
      </n-card>
      <n-card>
        <template #header>
          <div class="clearfix">
            <span>缓存内容</span>
            <n-button @click="clearAll" style="float: right; padding: 3px 0" type="text">
              <template #icon>
                <RedoOutlined />
              </template>
              清理全部
            </n-button>
          </div>
        </template>
        <n-form
          ref="form"
          :model="formData"
          :label-col="{ style: { width: '80px' } }"
          layout="vertical"
          v-if="cacheKeyData.length > 0"
        >
          <n-form-item label="缓存名称：">
            <n-input v-model:value="formData.cacheName" />
          </n-form-item>
          <n-form-item label="缓存键值：">
            <n-input v-model:value="formData.cacheKey" />
          </n-form-item>
          <n-form-item label="缓存内容：">
            <n-input v-model:value="formData.cacheValue" type="textarea" />
          </n-form-item>
        </n-form>
        <div v-else>暂无数据</div>
      </n-card>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, h } from 'vue';
  import { RedoOutlined, DeleteOutlined } from '@vicons/antd';
  import {
    getCacheNames,
    getCacheKeys,
    getCacheValue,
    deleteCacheName,
    deleteCacheKey,
    deleteCacheAll,
  } from '@/api/monitor/caches';
  import { TableAction } from '@/components/Table';
  import { renderIcon } from '@/utils';
  import { useMessage, useDialog } from 'naive-ui';
  import { cacheNameColumns } from './cacheNameColumns';
  import { cacheKeyColumns } from './cacheKeyColumns';

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

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

  const cacheNameColumns = [
    {
      type: 'selection',
      width: 50,
      fixed: 'left',
      multiple: false,
    },
    {
      title: '缓存名称',
      key: 'cacheName',
    },
    {
      title: '备注',
      key: 'message',
    },
    {
      title: '操作',
      fixed: 'right',
      key: 'action',
      width: 100,
      render(record) {
        return h(TableAction as any, {
          style: 'button',
          actions: [
            {
              label: '删除',
              icon: renderIcon(DeleteOutlined),
              type: 'error',
              onClick: handleDelete.bind(null, record, 'cacheName'),
            },
          ],
        });
      },
    },
  ];
  const cacheKeyColumns = [
    {
      type: 'selection',
      width: 50,
      fixed: 'left',
      multiple: false,
    },
    {
      title: '缓存键名',
      key: 'cacheKey',
    },
    {
      title: '操作',
      fixed: 'right',
      key: 'action',
      width: 100,
      render(record) {
        return h(TableAction as any, {
          style: 'button',
          actions: [
            {
              label: '删除',
              icon: renderIcon(DeleteOutlined),
              type: 'error',
              onClick: handleDelete.bind(null, record, 'cacheKey'),
            },
          ],
        });
      },
    },
  ];

  const rowNameProps = (row) => {
    console.log(row);
    return {
      style: 'cursor: pointer;',
      onClick: () => {
        cacheName.value = [row.cacheName];
        loadCachekeys();
      },
    };
  };
  const rowKeyProps = (row) => {
    return {
      style: 'cursor: pointer;',
      onClick: () => {
        cacheKey.value = [row.cacheKey];
        loadCacheValue();
      },
    };
  };

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

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

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

  /**
   * 加载缓存key列表
   */
  const loadCachekeys = async () => {
    let datas = [];
    const result = await getCacheKeys(cacheName.value[0]);
    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] : '';
    if (cacheKey.value) {
      loadCacheValue();
    }
  };

  /**
   * 加载缓存value列表
   */
  const loadCacheValue = async () => {
    const data = await getCacheValue({
      cacheName: cacheName.value[0],
      cacheKey: cacheKey.value[0],
    });
    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) => {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: 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>
