<script setup lang="tsx">
import { computed, reactive, ref } from 'vue';
import { ElTag } from 'element-plus';
import { SYSTEM_LOGIN_RESULT_DICT_CODE, SYSTEM_LOGIN_TYPE_DICT_CODE } from '@/constants/dict';
import { fetchExportLoginLog, fetchGetLoginLog, fetchGetLoginLogPage } from '@/service/api';
import { useAuth } from '@/hooks/business/auth';
import { useDict } from '@/hooks/business/dict';
import { useUIPaginatedTable } from '@/hooks/common/table';
import BusinessTableActionCell, { type BusinessTableAction } from '@/components/custom/business-table-action-cell';
import DictText from '@/components/custom/dict-text.vue';
import LogDetailDialog from '../shared/log-detail-dialog.vue';
import { type LogDetailSection, LogPermission, downloadBlob, formatDateTime, getLogExportFileName } from '../shared';
import LoginLogSearch from './modules/search.vue';
import IconMdiEyeOutline from '~icons/mdi/eye-outline';

defineOptions({ name: 'LoginLogTab' });

type LoginLogPageResponse = Awaited<ReturnType<typeof fetchGetLoginLogPage>>;

function createSearchParams(): Api.SystemLog.Login.SearchParams {
  return {
    pageNo: 1,
    pageSize: 10,
    userIp: undefined,
    username: undefined,
    status: undefined,
    createTime: undefined
  };
}

function transformPageResult(response: LoginLogPageResponse, pageNo: number, pageSize: number) {
  if (!response.error && response.data) {
    return {
      data: response.data.list,
      pageNum: pageNo,
      pageSize,
      total: response.data.total
    };
  }

  return {
    data: [],
    pageNum: 1,
    pageSize,
    total: 0
  };
}

const { hasAuth } = useAuth();
const { getLabel: getLoginResultLabel } = useDict(SYSTEM_LOGIN_RESULT_DICT_CODE);
const searchParams = reactive(createSearchParams());
const detailVisible = ref(false);
const currentRow = ref<Api.SystemLog.Login.Log | null>(null);
const exporting = ref(false);
const canExport = computed(() => hasAuth(LogPermission.LoginExport));

function getLoginResultTagType(result: Api.SystemLog.Login.Log['result']) {
  const label = getLoginResultLabel(result, '');

  return label.includes('成功') ? 'success' : 'danger';
}

const detailSections: LogDetailSection[] = [
  {
    title: '基础信息',
    fields: [
      { label: '日志编号', key: 'id' },
      { label: '日志类型', key: 'logType', type: 'dict', dictCode: SYSTEM_LOGIN_TYPE_DICT_CODE },
      { label: '用户编号', key: 'userId' },
      { label: '账号', key: 'username' },
      { label: '登录结果', key: 'result', type: 'dict', dictCode: SYSTEM_LOGIN_RESULT_DICT_CODE },
      { label: '登录时间', key: 'createTime', type: 'datetime' }
    ]
  },
  {
    title: '访问上下文',
    fields: [
      { label: '链路追踪编号', key: 'traceId' },
      { label: '登录IP', key: 'userIp' },
      { label: '浏览器UA', key: 'userAgent', type: 'multiline' }
    ]
  }
];

const { columns, columnChecks, data, loading, getData, getDataByPage, mobilePagination } = useUIPaginatedTable<
  LoginLogPageResponse,
  Api.SystemLog.Login.Log
>({
  paginationProps: {
    currentPage: searchParams.pageNo,
    pageSize: searchParams.pageSize
  },
  api: () => fetchGetLoginLogPage(searchParams),
  transform: response => transformPageResult(response, searchParams.pageNo ?? 1, searchParams.pageSize ?? 10),
  onPaginationParamsChange: params => {
    searchParams.pageNo = params.currentPage ?? 1;
    searchParams.pageSize = params.pageSize ?? 10;
  },
  columns: () => [
    { prop: 'index', type: 'index', label: '序号', width: 64 },
    {
      prop: 'username',
      label: '账号',
      minWidth: 140,
      showOverflowTooltip: true
    },
    {
      prop: 'logType',
      label: '日志类型',
      minWidth: 120,
      formatter: row => <DictText dictCode={SYSTEM_LOGIN_TYPE_DICT_CODE} value={row.logType} />
    },
    {
      prop: 'result',
      label: '登录结果',
      minWidth: 80,
      formatter: row => (
        <ElTag type={getLoginResultTagType(row.result)}>
          <DictText dictCode={SYSTEM_LOGIN_RESULT_DICT_CODE} value={row.result} />
        </ElTag>
      )
    },
    {
      prop: 'userIp',
      label: '登录IP',
      minWidth: 140,
      showOverflowTooltip: true
    },
    {
      prop: 'createTime',
      label: '登录时间',
      minWidth: 180,
      formatter: row => formatDateTime(row.createTime)
    },
    {
      prop: 'operate',
      label: '操作',
      width: 90,
      align: 'center',
      fixed: 'right',
      formatter: row => <BusinessTableActionCell actions={getRowActions(row)} variant="icon" />
    }
  ]
});

function getRowActions(row: Api.SystemLog.Login.Log): BusinessTableAction[] {
  return [
    {
      key: 'view',
      label: '查看',
      buttonType: 'primary',
      icon: IconMdiEyeOutline,
      onClick: () => openDetail(row)
    }
  ];
}

function openDetail(row: Api.SystemLog.Login.Log) {
  currentRow.value = row;
  detailVisible.value = true;
}

async function reloadTable(page = searchParams.pageNo) {
  await getDataByPage(page);
}

function resetSearchParams() {
  Object.assign(searchParams, createSearchParams());
  reloadTable(1);
}

function handleSearch() {
  reloadTable(1);
}

async function handleExport() {
  exporting.value = true;
  const { error, data: blob } = await fetchExportLoginLog(searchParams);
  exporting.value = false;

  if (error || !blob) {
    return;
  }

  downloadBlob(blob, getLogExportFileName('登录日志'));
}
</script>

<template>
  <div class="h-full min-h-0 flex-col-stretch gap-16px overflow-hidden">
    <LoginLogSearch v-model:model="searchParams" @reset="resetSearchParams" @search="handleSearch" />

    <ElCard class="flex-1-hidden card-wrapper" body-class="business-table-card-body">
      <template #header>
        <div class="flex items-center justify-between gap-12px">
          <div class="flex items-center gap-10px">
            <p>登录日志列表</p>
            <ElTag effect="plain">{{ mobilePagination.total || data.length }}</ElTag>
          </div>
          <TableHeaderOperation
            v-model:columns="columnChecks"
            :disabled-delete="true"
            :loading="loading"
            @refresh="getData"
          >
            <template #default>
              <ElButton v-if="canExport" plain type="primary" :loading="exporting" @click="handleExport">
                <template #icon>
                  <icon-mdi-download class="text-icon" />
                </template>
                导出
              </ElButton>
            </template>
          </TableHeaderOperation>
        </div>
      </template>

      <div class="flex-1">
        <ElTable v-loading="loading" height="100%" border row-key="id" :data="data">
          <ElTableColumn v-for="col in columns" :key="String(col.prop)" v-bind="col" />
        </ElTable>
      </div>

      <div class="mt-20px flex justify-end">
        <ElPagination
          v-if="mobilePagination.total"
          layout="total,prev,pager,next,sizes"
          v-bind="mobilePagination"
          @current-change="mobilePagination['current-change']"
          @size-change="mobilePagination['size-change']"
        />
      </div>
    </ElCard>

    <LogDetailDialog
      v-model:visible="detailVisible"
      title="登录日志详情"
      :row-data="currentRow"
      :sections="detailSections"
      :fetch-detail="fetchGetLoginLog"
    />
  </div>
</template>
