<script setup lang="tsx">
import { ref } from 'vue';
import { type DataTableSortState, NButton, NPopconfirm, NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDownLoadFile } from '@/hooks/common/download';
import { $t } from '@/locales';
import { getDicts } from '@/service/api/system/dict';
import { useAppStore } from '@/store/modules/app';
import { cleanLogininfor, delLogininfor, list } from '@/service/api/monitor/loginlog';
import LoginlogSearch from '@/views/system/log_login-log/modules/loginlog-search.vue';

defineOptions({
  name: 'LoginLog'
});

const appStore = useAppStore();
const { loading: exportLoading, downLoadExcelPost } = useDownLoadFile();

const statusOptions = ref<Api.SystemManage.DictInfo[]>([]);
getDicts('sys_common_status').then(response => {
  if (!response.error) {
    statusOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: list,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    ipaddr: null,
    userName: null,
    status: null,
    params: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'infoId',
      title: '访问编号',
      align: 'center'
    },
    {
      key: 'userName',
      title: '用户名称',
      align: 'center'
    },
    {
      key: 'ipaddr',
      title: '登录地址',
      align: 'center'
    },
    {
      key: 'loginLocation',
      title: '登录地点',
      align: 'center'
    },
    {
      key: 'browser',
      title: '浏览器类型',
      align: 'center'
    },
    {
      key: 'os',
      title: '操作系统',
      align: 'center'
    },
    {
      key: 'status',
      title: '登录状态',
      align: 'center',
      render: row => {
        if (row.status === null) {
          return null;
        }
        const obj = statusOptions.value.find(item => item.dictValue === row.status.toString());
        return <NTag type={obj?.listClass === 'danger' ? 'error' : obj?.listClass}>{obj?.dictLabel}</NTag>;
      }
    },
    {
      key: 'loginTime',
      title: '登录日期',
      align: 'center',
      sorter: true
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          <NPopconfirm onPositiveClick={() => handleDelete(row.infoId)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { checkedRowKeys, onDeleted, onBatchDeleted } = useTableOperate(data, getData);

// 单个删除
function handleDelete(id: Api.SystemManage.Loginlog['infoId']) {
  delLogininfor([id]).then(res => {
    if (res.error) return;
    onDeleted();
  });
}

// 批量删除
function handleBatchDelete() {
  delLogininfor(checkedRowKeys.value as Api.SystemManage.Loginlog['infoId'][]).then(res => {
    if (res.error) return;
    onBatchDeleted();
  });
}

function handleClear() {
  cleanLogininfor().then(res => {
    if (res.error) return;
    getDataByPage();
  });
}

// 导出
function handleExport() {
  downLoadExcelPost('/monitor/logininfor/export', searchParams);
}

function handleSorterChange(sorter: DataTableSortState) {
  console.log('handleSorterChange', sorter);
  searchParams.orderByColumn = sorter.columnKey as string;
  searchParams.isAsc = sorter.order === 'ascend' ? 'asc' : sorter.order === 'descend' ? 'desc' : null;
  getDataByPage();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <LoginlogSearch
      v-model:model="searchParams"
      :status-options="statusOptions"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard title="操作日志" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add-btn="false"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleExport">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              导出
            </NButton>
            <NPopconfirm @positive-click="handleClear">
              <template #trigger>
                <NButton size="small" ghost type="error">
                  <template #icon>
                    <SvgIcon icon="mdi:delete-outline"></SvgIcon>
                  </template>
                  清空
                </NButton>
              </template>
              确认清空操作日志吗？
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="({ infoId }) => infoId"
        :pagination="mobilePagination"
        class="sm:h-full"
        @update:sorter="handleSorterChange"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
