<template>
  <el-dialog
    v-model="visible"
    title="IP登录历史"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.id }}</div>
      </div>
      <div class="login-stats">
        <el-statistic title="登录记录数" :value="total" />
      </div>
    </div>

    <!-- IP登录历史列表 -->
    <el-table :data="ipLogList" v-loading="loading" border stripe max-height="400">
      <el-table-column prop="id" label="ID" width="80" />

      <el-table-column prop="loginDate" label="登录日期" width="120" />

      <el-table-column label="登录时间" width="170">
        <template #default="{ row }">
          {{ row.loginTime || row.lastLoginTime || '-' }}
        </template>
      </el-table-column>

      <el-table-column prop="ip" label="IP地址" min-width="150">
        <template #default="{ row }">
          <div class="ip-info">
            <span class="ip-address">{{ row.ip || '-' }}</span>
            <el-button
              v-if="row.ip"
              type="primary"
              link
              size="small"
              @click="handleCopyIp(row.ip)"
            >
              复制
            </el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="location" label="归属地" min-width="150">
        <template #default="{ row }">
          {{ row.location || '-' }}
        </template>
      </el-table-column>

      <el-table-column prop="device" label="设备信息" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.device || '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      class="pagination"
    />

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUserIpLogs, type UserListItem, type IpLogItem } from '@/api/business/user'

interface Props {
  modelValue: boolean
  user: UserListItem | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const ipLogList = ref<IpLogItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const currentPageSize = ref(20)

// 获取数据
const fetchData = async () => {
  if (!props.user) return

  loading.value = true
  try {
    const res = await getUserIpLogs(props.user.id, currentPage.value, currentPageSize.value)
    ipLogList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    console.error('获取IP登录历史失败', error)
    ipLogList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  currentPageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 复制IP地址
const handleCopyIp = async (ip: string) => {
  try {
    await navigator.clipboard.writeText(ip)
    ElMessage.success('IP地址已复制')
  } catch {
    // 降级方案
    const textarea = document.createElement('textarea')
    textarea.value = ip
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage.success('IP地址已复制')
  }
}

// 对话框打开时
const handleOpen = () => {
  currentPage.value = 1
  currentPageSize.value = 20
  fetchData()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

.uid {
  font-size: 12px;
  color: #909399;
}

.login-stats {
  padding: 0 20px;
}

.ip-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ip-address {
  font-family: monospace;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
