<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api/admin'
import type { AdminUserDetail, Device } from '@/types'
import { UserStatus, AdminRole, DeviceStatus } from '@/types'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const user = ref<AdminUserDetail | null>(null)

const userId = route.params.id as string

onMounted(async () => {
  try {
    const response = await adminApi.getUserDetail(userId)
    if (response.success && response.data) {
      user.value = response.data
    }
  } finally {
    loading.value = false
  }
})

async function handleResetPassword() {
  try {
    await ElMessageBox.confirm(
      '确定要重置该用户的密码吗？新密码将显示一次，请妥善保存。',
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await adminApi.resetUserPassword(userId)
    if (response.success && response.data) {
      ElMessageBox.alert(
        `新密码: ${response.data}`,
        '密码已重置',
        { confirmButtonText: '我已记录' }
      )
    }
  } catch {
    // 取消
  }
}

async function handleForceLogout(device: Device) {
  try {
    await ElMessageBox.confirm(
      `确定要强制设备 "${device.deviceName}" 下线吗？`,
      '强制下线',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await adminApi.forceDeviceLogout(device.id)
    if (response.success) {
      ElMessage.success('已强制下线')
    }
  } catch {
    // 取消
  }
}

async function handleToggleDeviceStatus(device: Device) {
  const disabled = device.status === DeviceStatus.Normal
  const action = disabled ? '禁用' : '启用'

  try {
    await ElMessageBox.confirm(
      `确定要${action}设备 "${device.deviceName}" 吗？`,
      `${action}设备`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await adminApi.setDeviceStatus(device.id, disabled)
    if (response.success) {
      ElMessage.success(`${action}成功`)
      device.status = disabled ? DeviceStatus.Disabled : DeviceStatus.Normal
    }
  } catch {
    // 取消
  }
}

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

function getRoleText(role: AdminRole) {
  const map = {
    [AdminRole.User]: '普通用户',
    [AdminRole.Admin]: '管理员',
    [AdminRole.SuperAdmin]: '超级管理员'
  }
  return map[role] || '未知'
}
</script>

<template>
  <div v-loading="loading" class="user-detail">
    <div class="page-header">
      <el-button @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>用户详情</h2>
    </div>

    <template v-if="user">
      <!-- 用户信息 -->
      <div class="info-card">
        <div class="card-header">
          <h3>基本信息</h3>
          <el-button type="primary" @click="handleResetPassword">重置密码</el-button>
        </div>
        <div class="info-grid">
          <div class="info-item">
            <label>用户名</label>
            <span>{{ user.userName }}</span>
          </div>
          <div class="info-item">
            <label>邮箱</label>
            <span>{{ user.email }}</span>
          </div>
          <div class="info-item">
            <label>角色</label>
            <span>{{ getRoleText(user.role) }}</span>
          </div>
          <div class="info-item">
            <label>状态</label>
            <el-tag :type="user.status === UserStatus.Normal ? 'success' : 'danger'" size="small">
              {{ user.status === UserStatus.Normal ? '正常' : '禁用' }}
            </el-tag>
          </div>
          <div class="info-item">
            <label>注册时间</label>
            <span>{{ formatDate(user.createdAt) }}</span>
          </div>
          <div class="info-item">
            <label>最后登录</label>
            <span>{{ formatDate(user.lastLoginAt) }}</span>
          </div>
          <div class="info-item">
            <label>书签数量</label>
            <span>{{ user.bookmarkCount }}</span>
          </div>
        </div>
      </div>

      <!-- 设备列表 -->
      <div class="info-card">
        <div class="card-header">
          <h3>设备列表 ({{ user.devices.length }})</h3>
        </div>
        <el-table :data="user.devices" class="device-table">
          <el-table-column label="设备名称" prop="deviceName" min-width="150" />
          <el-table-column label="设备类型" prop="deviceType" min-width="150" />
          <el-table-column label="管理员设备" width="100" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.isAdmin" type="warning" size="small">是</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === DeviceStatus.Normal ? 'success' : 'danger'" size="small">
                {{ row.status === DeviceStatus.Normal ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后活跃" width="180">
            <template #default="{ row }">
              {{ formatDate(row.lastActiveAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button size="small" @click="handleForceLogout(row)">
                强制下线
              </el-button>
              <el-button
                size="small"
                :type="row.status === DeviceStatus.Normal ? 'danger' : 'success'"
                @click="handleToggleDeviceStatus(row)"
              >
                {{ row.status === DeviceStatus.Normal ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.user-detail {
  .page-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;

    h2 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .info-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;

    .info-item {
      display: flex;
      flex-direction: column;
      gap: 4px;

      label {
        font-size: 12px;
        color: #999;
      }

      span {
        font-size: 14px;
        color: #333;
      }
    }
  }

  .device-table {
    border-radius: 8px;
  }
}
</style>

