<script setup lang="ts">
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { CacheDetail } from '#/api/monitor/cache/model';

import { computed, ref } from 'vue';

import { Page, useVbenForm } from '@vben/common-ui';
import { Clear, Contents, Keys, Memory, Refresh } from '@vben/icons';
import { preferences } from '@vben/preferences';

import { ElMessage } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  clearCacheAll,
  deleteCacheKey,
  deleteCacheName,
  getCacheDetail,
  getCacheKey,
  getCacheList,
} from '#/api/monitor/cache/cache';
import { useAuthStore } from '#/store';

import { cacheColumns, formSchema, keyColumns } from './config-data';

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  commonConfig: {
    disabled: true,
    componentProps: {
      placeholder: '',
    },
  },
  schema: formSchema(),
});

const gridOptions: VxeGridProps = {
  columns: cacheColumns,
  rowClassName: 'hover:cursor-pointer',
  rowConfig: {
    isCurrent: true,
    isHover: true,
    useKey: true,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        const resp = await getCacheList();
        return { items: resp };
      },
    },
  },
  pagerConfig: {
    enabled: false,
  },
};
const keyGridOptions: VxeGridProps = {
  columns: keyColumns,
  rowClassName: 'hover:cursor-pointer',
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        const resp = await getCacheKey(formValues.cacheName);
        const itemArr = resp.map((item) => ({
          value: item.replace(`${formValues.cacheName}:`, ''),
        }));
        return { items: itemArr };
      },
    },
  },
  pagerConfig: {
    enabled: false,
  },
};
// 定义点击缓存列表的数据
const cacheNameRef = ref<string>('');
// 点击左侧缓存列表item
const gridEvents: VxeGridListeners<CacheDetail> = {
  cellClick: ({ row }) => {
    const repCacheName = row.cacheName.slice(
      0,
      Math.max(0, row.cacheName.lastIndexOf(':')),
    );
    cacheNameRef.value = repCacheName;
    keyTableApi.query({ cacheName: repCacheName });
  },
};
const [CacheTable, cacheTableApi] = useVbenVxeGrid({
  gridEvents,
  gridClass: 'p-0',
  gridOptions,
});
// 点击中间Key列表item
const keyGridEvents: VxeGridListeners = {
  cellClick: async ({ row }) => {
    const cacheFromData = await getCacheDetail(row.value);
    await formApi.setValues(cacheFromData);
  },
};
const [KeyTable, keyTableApi] = useVbenVxeGrid({
  gridEvents: keyGridEvents,
  gridClass: 'p-0',
  gridOptions: keyGridOptions,
});
// 删除键名
async function deleteHandleName(cacheDetail: CacheDetail) {
  await deleteCacheName(cacheDetail.cacheName);
  await cacheTableApi.query();
}
// 删除Key
async function deleteHandleKey(data: any) {
  await deleteCacheKey(data.value);
  await keyTableApi.query();
}
// 刷新操作 1是刷新缓列表  2是刷新键名列表
async function refreshHandle(type: number) {
  if (type === 1) {
    await cacheTableApi.query();
  } else {
    if (cacheNameRef.value) {
      await keyTableApi.query({ cacheName: cacheNameRef.value });
    } else {
      ElMessage.warning('请先点击一条缓存列表中的数据');
    }
  }
}
// 清空所有
const authStore = useAuthStore();
async function clearAllHandle() {
  await clearCacheAll();
  await authStore.logout(false);
}
// 监听主题颜色变化
const colorPrimary = computed(() => {
  return preferences.theme.colorPrimary;
});
</script>

<template>
  <Page auto-content-height>
    <div class="grid h-full w-full grid-cols-3 gap-4 overflow-hidden">
      <ElCard>
        <div class="mb-2 flex items-center gap-0.5 text-[16px]">
          <Memory />
          <span>缓存列表</span>
          <Refresh class="ml-auto" @click="refreshHandle(1)" />
        </div>
        <CacheTable>
          <template #action="{ row }">
            <div class="flex w-full justify-center">
              <Clear
                width="20"
                height="20"
                :color="colorPrimary"
                @click="deleteHandleName(row)"
              />
            </div>
          </template>
        </CacheTable>
      </ElCard>
      <ElCard>
        <div class="mb-2 flex items-center gap-0.5 text-[16px]">
          <Keys />
          <span>键名列表</span>
          <Refresh class="ml-auto" @click="refreshHandle(2)" />
        </div>
        <KeyTable>
          <template #cacheKey="{ row }">
            <div>
              {{ row }}
            </div>
          </template>
          <template #action="{ row }">
            <div class="flex w-full justify-center">
              <Clear
                width="20"
                height="20"
                :color="colorPrimary"
                @click="deleteHandleKey(row)"
              />
            </div>
          </template>
        </KeyTable>
      </ElCard>
      <ElCard>
        <div class="mb-2 flex items-center gap-0.5 text-[16px]">
          <Contents />
          <span>缓存内容</span>
          <Clear class="ml-auto" @click="clearAllHandle" />
        </div>
        <Form />
      </ElCard>
    </div>
  </Page>
</template>
