<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Operlog } from '#/api/monitor/operlog/model';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  cleanOperlog,
  deleteOperlog,
  exportOperlog,
  operlogList,
} from '#/api/monitor/operlog/operlog';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, tableColumns } from './config-data';
import OperLogDrawerComp from './operlog-drawer.vue';

const [OperLogDrawer, operLogDrawerApi] = useVbenDrawer({
  connectedComponent: OperLogDrawerComp,
});

const formOptions: VbenFormProps = {
  schema: querySchema(),
  wrapperClass: 'grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'operTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await operlogList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 批量删除岗位
async function removeOperLog() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  const operIds = checkData.map((item: Operlog) => item.operId);
  if (operIds.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${operIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteOperlog(operIds);
    await basicTableApi.reload();
  });
}
// 编辑岗位
function handleViewer(operlog: Operlog) {
  operLogDrawerApi.setData(operlog).open();
}
// 导出操作日志
async function exportOperLogata() {
  await commonDownloadExcel(
    exportOperlog,
    '操作日志数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 清空操作日志
function cleanAll() {
  ElMessageBox.confirm(`确定要清空所有操作日志数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await cleanOperlog();
    await basicTableApi.reload();
  });
}
// 获取状态字典值
const dictRef = ref<DictOption[]>([]);
// 获取操作类型
const operTypeRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.SYS_COMMON_STATUS);
  operTypeRef.value = await getDictOptions(DictEnum.SYS_OPER_TYPE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="操作日志列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportOperLogata"
            v-access:code="['monitor:operlog:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="removeOperLog"
            v-access:code="['monitor:operlog:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="danger"
            @click="cleanAll"
            v-access:code="['monitor:operlog:remove']"
          >
            清空
          </ElButton>
        </ElSpace>
      </template>
      <template #businessType="{ row }">
        <DictTag :dicts="operTypeRef" :value="row.businessType" />
      </template>
      <template #status="{ row }">
        <DictTag :dicts="dictRef" :value="row.status" />
      </template>
      <template #costTime="{ row }">
        <span>{{ `${row.costTime}毫秒` }}</span>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleViewer(row)"
            v-access:code="['monitor:operlog:query']"
          >
            详情
          </ElButton>
        </ElSpace>
      </template>
    </BasicTable>
    <OperLogDrawer />
  </Page>
</template>
