<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>统一登录日志</span>
        </div>
      </template>

      <!-- Filter Section -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="手机号">
            <el-input v-model="queryParams.mobile" placeholder="输入手机号" clearable @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="IP地址">
            <el-input v-model="queryParams.ip_address" placeholder="输入IP" clearable @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 100px" @change="handleSearch">
              <el-option label="成功" :value="1" />
              <el-option label="失败" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="登录方式">
            <el-select v-model="queryParams.login_method" placeholder="全部" clearable style="width: 150px" @change="handleSearch">
              <el-option label="统一页面" value="UNIFIED_PAGE" />
              <el-option label="自定义页面" value="CUSTOM_PAGE" />
              <el-option label="直接跳转" value="DIRECT_JUMP" />
              <el-option label="平台间跳转" value="INTER_PLATFORM" />
            </el-select>
          </el-form-item>
          <el-form-item label="认证方式">
            <el-select v-model="queryParams.auth_type" placeholder="全部" clearable style="width: 120px" @change="handleSearch">
              <el-option label="密码" value="PASSWORD" />
              <el-option label="短信" value="SMS" />
              <el-option label="Token" value="TOKEN" />
              <el-option label="SSO" value="SSO" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
             <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleSearch"
                style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- Table Section -->
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="mobile" label="账号" min-width="120">
             <template #default="scope">
                {{ scope.row.mobile || 'Unknown' }}
             </template>
        </el-table-column>
        <el-table-column prop="ip_address" label="IP 地址" width="130" />
        <el-table-column prop="location" label="归属地" width="120" show-overflow-tooltip />
        <el-table-column prop="login_method" label="登录方式" width="120">
          <template #default="scope">
            <el-tag effect="plain">{{ getLoginMethodLabel(scope.row.login_method) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auth_type" label="认证方式" width="100">
          <template #default="scope">
             <el-tag effect="plain" type="info">{{ getAuthTypeLabel(scope.row.auth_type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_success" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_success === 1 ? 'success' : 'danger'">
              {{ scope.row.is_success === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="failure_reason" label="失败原因" min-width="150" show-overflow-tooltip>
             <template #default="scope">
                <span v-if="scope.row.is_success === 0" class="text-danger">{{ scope.row.failure_reason }}</span>
                <span v-else>-</span>
             </template>
        </el-table-column>
        <el-table-column prop="created_at" label="登录时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="详情" width="80" align="center">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="showDetails(scope.row)">查看</el-button>
            </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    </el-card>

    <!-- Details Dialog -->
    <el-dialog v-model="detailsVisible" title="日志详情" width="500px">
        <el-descriptions :column="1" border>
            <el-descriptions-item label="日志 ID">{{ currentLog?.id }}</el-descriptions-item>
            <el-descriptions-item label="用户账号">{{ currentLog?.mobile }}</el-descriptions-item>
            <el-descriptions-item label="用户 ID">{{ currentLog?.user_id || '-' }}</el-descriptions-item>
            <el-descriptions-item label="登录状态">
                <el-tag :type="currentLog?.is_success === 1 ? 'success' : 'danger'">
                  {{ currentLog?.is_success === 1 ? '成功' : '失败' }}
                </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="失败原因" v-if="currentLog?.is_success === 0">
                {{ currentLog?.failure_reason }}
            </el-descriptions-item>
            <el-descriptions-item label="登录方式">{{ getLoginMethodLabel(currentLog?.login_method) }}</el-descriptions-item>
            <el-descriptions-item label="认证方式">{{ getAuthTypeLabel(currentLog?.auth_type) }}</el-descriptions-item>
            <el-descriptions-item label="IP 地址">{{ currentLog?.ip_address }}</el-descriptions-item>
            <el-descriptions-item label="归属地">{{ currentLog?.location || '-' }}</el-descriptions-item>
            <el-descriptions-item label="时间">{{ formatDate(currentLog?.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="User Agent">
                <div style="word-break: break-all; max-height: 100px; overflow-y: auto;">
                    {{ currentLog?.user_agent }}
                </div>
            </el-descriptions-item>
        </el-descriptions>
        <template #footer>
            <el-button @click="detailsVisible = false">关闭</el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getLoginLogs, LoginLog } from '../../../api/login_logs'

// --- State ---
const loading = ref(false)
const tableData = ref<LoginLog[]>([])
const dateRange = ref<[string, string] | null>(null)

const queryParams = reactive({
  mobile: '',
  ip_address: '',
  status: undefined as number | undefined,
  login_method: undefined as string | undefined,
  auth_type: undefined as string | undefined,
})

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// Details
const detailsVisible = ref(false)
const currentLog = ref<LoginLog | null>(null)

// --- Methods ---

const fetchData = async () => {
  loading.value = true
  try {
    const params: any = {
      skip: (pagination.current - 1) * pagination.size,
      limit: pagination.size,
      mobile: queryParams.mobile || undefined,
      ip_address: queryParams.ip_address || undefined,
      status: queryParams.status,
      login_method: queryParams.login_method || undefined,
      auth_type: queryParams.auth_type || undefined,
    }

    if (dateRange.value) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1] + ' 23:59:59'
    }

    const res = await getLoginLogs(params)
    tableData.value = res.data.items
    pagination.total = res.data.total
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetQuery = () => {
  queryParams.mobile = ''
  queryParams.ip_address = ''
  queryParams.status = undefined
  queryParams.login_method = undefined
  queryParams.auth_type = undefined
  dateRange.value = null
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.size = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchData()
}

const showDetails = (row: LoginLog) => {
    currentLog.value = row
    detailsVisible.value = true
}

// Helpers
const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleString()
}

const getLoginMethodLabel = (val?: string) => {
    const map: Record<string, string> = {
        'UNIFIED_PAGE': '统一认证页面',
        'CUSTOM_PAGE': '自定义页面',
        'DIRECT_JUMP': '直接跳转',
        'INTER_PLATFORM': '平台间跳转',
        'UNKNOWN': '未知'
    }
    return val ? (map[val] || val) : '-'
}

const getAuthTypeLabel = (val?: string) => {
    const map: Record<string, string> = {
        'PASSWORD': '密码',
        'SMS': '短信',
        'TICKET': '票据',
        'TOKEN': 'Token',
        'SSO': 'SSO',
        'OTHER': '其他'
    }
    return val ? (map[val] || val) : '-'
}

// --- Lifecycle ---
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.text-danger {
    color: #F56C6C;
}
</style>

