<template>
  <div class="container">
    <Breadcrumb :items="['核销中心', '登录日志']" />
    <a-card class="general-card" title="登录日志">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="loginName" label="登录名">
                  <a-input
                    v-model="formModel.loginName"
                    placeholder="请输入登录名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="登录状态">
                  <a-select
                    v-model="formModel.status"
                    placeholder="请选择登录状态"
                    allow-clear
                  >
                    <a-option :value="1">登录成功</a-option>
                    <a-option :value="0">登录失败</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="dateRange" label="登录时间">
                  <a-range-picker
                    v-model="formModel.dateRange"
                    style="width: 100%"
                    :shortcuts="dateShortcuts"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col flex="172px" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <a-table
        row-key="id"
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50, 100],
          showPageSize: true,
          showTotal: true,
          showJumper: true
        }"
        :columns="columns"
        :data="renderData"
        :scroll="{ x: 1400 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #status="{ record }">
          <a-tag v-if="record.status === 1" color="green">登录成功</a-tag>
          <a-tag v-else-if="record.status === 0" color="red">登录失败</a-tag>
          <a-tag v-else color="gray">未知</a-tag>
        </template>
        <template #browser="{ record }">
          <a-tooltip :content="record.userAgent">
            <span>{{ record.browser || '-' }}</span>
          </a-tooltip>
        </template>
        <template #os="{ record }">
          <span>{{ record.os || '-' }}</span>
        </template>
        <template #operations="{ record }">
          <a-space size="small">
            <a-tooltip content="查看详情">
              <a-button size="small" @click="showDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </a-table>

      <!-- 详情弹窗 -->
      <DetailModal
        v-model:visible="detailModalVisible"
        :login-log-id="selectedLoginLogId"
      />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import Breadcrumb from '@/components/breadcrumb/index.vue';
import useLoading from '@/hooks/loading';
import type { Pagination } from '@/types/global';
import { Message } from '@arco-design/web-vue';
import { apiClient } from '@/api';
import { KamiInternalModelEntityV1SysUserLoginLog } from '@/api/generated/models';
import DetailModal from './components/detail-modal.vue';

const { loading, setLoading } = useLoading();

// 生成搜索参数ID
const generateSearchId = () => {
  return Date.now().toString();
};

const searchId = ref(generateSearchId());

// 表单模型
const formModel = reactive({
  loginName: '',
  status: undefined as number | undefined,
  dateRange: undefined as [string, string] | undefined
});

// 基础分页配置
const basePagination: Pagination = {
  current: 1,
  pageSize: 20
};

const pagination = reactive({ ...basePagination });

// 表格数据
const renderData = ref<KamiInternalModelEntityV1SysUserLoginLog[]>([]);

// 详情弹窗
const detailModalVisible = ref(false);
const selectedLoginLogId = ref<number>();

// 日期快捷选项
const dateShortcuts = [
  {
    label: '今天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    label: '昨天',
    value: () => {
      const end = new Date();
      const start = new Date();
      end.setDate(end.getDate() - 1);
      end.setHours(23, 59, 59, 999);
      start.setDate(start.getDate() - 1);
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    label: '最近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  },
  {
    label: '最近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 30);
      return [start, end];
    }
  }
];

// 表格列配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80
  },
  {
    title: '登录名',
    dataIndex: 'loginName',
    width: 120
  },
  {
    title: '登录IP',
    dataIndex: 'ipAddr',
    width: 140
  },
  {
    title: '登录地点',
    dataIndex: 'loginLocation',
    width: 160,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '浏览器',
    dataIndex: 'browser',
    width: 120,
    slotName: 'browser'
  },
  {
    title: '操作系统',
    dataIndex: 'os',
    width: 120,
    slotName: 'os'
  },
  {
    title: '登录状态',
    dataIndex: 'status',
    width: 100,
    slotName: 'status'
  },
  {
    title: '登录时长',
    dataIndex: 'loginTime',
    width: 100
  },
  {
    title: '登录时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    slotName: 'operations',
    width: 100,
    fixed: 'right'
  }
];

// 获取数据
const fetchData = async (
  params: { current?: number; pageSize?: number } = {}
) => {
  setLoading(true);
  try {
    const { current = 1, pageSize = pagination.pageSize } = params;

    const requestParams = {
      current,
      pageSize,
      loginName: formModel.loginName || undefined,
      status: formModel.status,
      startTime: formModel.dateRange?.[0],
      endTime: formModel.dateRange?.[1]
    };

    const response = await apiClient.apiSysUserLoginLogListGet(requestParams);

    if (response.data) {
      renderData.value = response.data.list || [];
      pagination.current = current;
      pagination.total = response.data.total || 0;
    }
  } catch (error) {
    console.error('获取登录日志失败:', error);
    Message.error('获取登录日志失败');
  } finally {
    setLoading(false);
  }
};

// 搜索
const search = () => {
  fetchData({ current: 1 });
  searchId.value = generateSearchId();
};

// 重置
const reset = () => {
  formModel.loginName = '';
  formModel.status = undefined;
  formModel.dateRange = undefined;
  fetchData({ current: 1 });
};

// 分页变化
const onPageChange = (current: number) => {
  fetchData({ current });
};

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  fetchData({ current: 1 });
};

// 显示详情
const showDetail = (record: KamiInternalModelEntityV1SysUserLoginLog) => {
  selectedLoginLogId.value = record.id;
  detailModalVisible.value = true;
};

onMounted(() => {
  fetchData();
});
</script>
