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

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

import { onMounted, ref } from 'vue';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  cleanloginInfo,
  deleteloginInfo,
  exportloginInfo,
  loginInfoList,
  unLockUser,
} from '#/api/monitor/logininfo/logininfo';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, tableColumns } from './config-data';

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 loginInfoList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 批量删除登录日志
async function removeLoginLog() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  const loginIds = checkData.map((item: LoginInfo) => item.infoId);
  if (loginIds.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${loginIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteloginInfo(loginIds);
    await basicTableApi.reload();
  });
}

// 导出登录日志
async function exportLoginLogata() {
  await commonDownloadExcel(
    exportloginInfo,
    '登录日志数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 清空登录日志
function cleanAll() {
  ElMessageBox.confirm(`确定要清空所有登录日志数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await cleanloginInfo();
    await basicTableApi.reload();
  });
}
// 解锁
function unlock() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  if (checkData.length <= 0) {
    return;
  }
  const { userName } = checkData[0];
  ElMessageBox.confirm(`确定要解锁账号为${userName}的用户吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await unLockUser(userName);
    await basicTableApi.reload();
  });
}
// 获取状态字典值
const dictRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.SYS_COMMON_STATUS);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="登录日志列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportLoginLogata"
            v-access:code="['monitor:logininfor:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="removeLoginLog"
            v-access:code="['monitor:logininfor:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="danger"
            @click="cleanAll"
            v-access:code="['monitor:logininfor:remove']"
          >
            清空
          </ElButton>
          <ElButton
            type="primary"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="unlock"
            v-access:code="['monitor:logininfor:unlock']"
          >
            解锁
          </ElButton>
        </ElSpace>
      </template>
      <template #status="{ row }">
        <DictTag :dicts="dictRef" :value="row.status" />
      </template>
    </BasicTable>
  </Page>
</template>
