<template>
  <div class="users-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>用户管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon> 新建用户
          </el-button>
        </div>
      </template>

      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width: 140px">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="锁定" value="locked" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="filters.role" placeholder="全部" clearable style="width: 160px">
            <el-option label="超级管理员" value="super_admin" />
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
            <el-option label="访客" value="viewer" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUsers">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="users" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="real_name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag :type="roleTagType(scope.row.role)" effect="plain" size="small">
              {{ roleLabel(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)" effect="plain" size="small">
              {{ statusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登录" width="170">
          <template #default="scope">
            {{ scope.row.last_login_at ? formatDateTime(scope.row.last_login_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
              :disabled="scope.row.id === currentUserId"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              v-if="scope.row.status === 'locked'"
              size="small"
              type="primary"
              @click="unlockUser(scope.row)"
            >
              解锁
            </el-button>
            <el-button size="small" @click="showResetPasswordDialog(scope.row)">
              重置密码
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.row)"
              :disabled="scope.row.id === currentUserId"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- 新建用户对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建用户" width="500px" @close="resetCreateForm">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="createForm.username" placeholder="登录用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createForm.password" type="password" placeholder="≥6 位" show-password />
        </el-form-item>
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="createForm.real_name" placeholder="真实姓名（可选）" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="createForm.email" placeholder="可选" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="createForm.phone" placeholder="可选" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="createForm.role" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
            <el-option label="访客" value="viewer" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitCreate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetDialogVisible" title="重置密码" width="420px">
      <el-form :model="resetForm" label-width="100px">
        <el-form-item label="目标用户">
          <el-text>{{ resetTarget?.username }} ({{ resetTarget?.real_name || '-' }})</el-text>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="resetForm.new_password" type="password" placeholder="≥6 位" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitReset">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { userApi } from '@/api/auth'
import { formatDateTime, formatDate, formatRelative } from '@/utils/datetime'
import { authStore } from '@/utils/auth'

const loading = ref(false)
const submitting = ref(false)
const users = ref([])

const filters = reactive({ status: '', role: '' })
const pagination = reactive({ page: 1, limit: 20, total: 0 })

const currentUserId = computed(() => authStore.getUserInfo()?.id)

const createDialogVisible = ref(false)
const createFormRef = ref(null)
const createForm = reactive({
  username: '', password: '', real_name: '', email: '', phone: '', role: 'viewer',
})
const createRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, min: 6, message: '密码至少 6 位', trigger: 'blur' }],
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

const resetDialogVisible = ref(false)
const resetForm = reactive({ new_password: '' })
const resetTarget = ref(null)

const ROLE_MAP = {
  super_admin: { label: '超级管理员', tagType: 'danger' },
  admin:       { label: '管理员',     tagType: 'warning' },
  operator:    { label: '操作员',     tagType: 'success' },
  viewer:      { label: '访客',       tagType: 'info' },
}
const STATUS_MAP = {
  active:   { label: '正常', tagType: 'success' },
  inactive: { label: '禁用', tagType: 'info' },
  locked:   { label: '锁定', tagType: 'danger' },
}

function roleLabel(r) { return ROLE_MAP[r]?.label || r || '-' }
function roleTagType(r) { return ROLE_MAP[r]?.tagType || '' }
function statusLabel(s) { return STATUS_MAP[s]?.label || s || '-' }
function statusTagType(s) { return STATUS_MAP[s]?.tagType || '' }

// 旧 formatDate 已由 @/utils/datetime 统一替代

async function loadUsers() {
  loading.value = true
  try {
    const result = await userApi.getList({
      skip: (pagination.page - 1) * pagination.limit,
      limit: pagination.limit,
      status: filters.status || undefined,
      role: filters.role || undefined,
    })
    users.value = result.items || []
    pagination.total = result.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  filters.status = ''
  filters.role = ''
  pagination.page = 1
  loadUsers()
}

function showCreateDialog() {
  createDialogVisible.value = true
}

function resetCreateForm() {
  Object.assign(createForm, {
    username: '', password: '', real_name: '', email: '', phone: '', role: 'viewer',
  })
  createFormRef.value?.resetFields()
}

async function submitCreate() {
  if (!createFormRef.value) return
  try {
    await createFormRef.value.validate()
  } catch (_) { return }

  submitting.value = true
  try {
    await userApi.create({ ...createForm })
    ElMessage.success('用户创建成功')
    createDialogVisible.value = false
    pagination.page = 1
    loadUsers()
  } catch (error) {
    console.error('创建用户失败:', error)
  } finally {
    submitting.value = false
  }
}

async function toggleStatus(row) {
  const next = row.status === 'active' ? 'inactive' : 'active'
  const action = next === 'active' ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 ${row.username} 吗？`,
      '提示', { type: 'warning', confirmButtonText: action, cancelButtonText: '取消' }
    )
  } catch (_) { return }

  try {
    await userApi.updateStatus(row.id, next)
    ElMessage.success(`已${action}`)
    loadUsers()
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

async function unlockUser(row) {
  try {
    await userApi.unlock(row.id)
    ElMessage.success('用户已解锁')
    loadUsers()
  } catch (error) {
    console.error('解锁失败:', error)
  }
}

function showResetPasswordDialog(row) {
  resetTarget.value = row
  resetForm.new_password = ''
  resetDialogVisible.value = true
}

async function submitReset() {
  if (!resetForm.new_password || resetForm.new_password.length < 6) {
    ElMessage.warning('新密码至少 6 位')
    return
  }
  submitting.value = true
  try {
    await userApi.resetPassword(resetTarget.value.id, resetForm.new_password)
    ElMessage.success('密码已重置，用户所有会话已失效')
    resetDialogVisible.value = false
  } catch (error) {
    console.error('重置密码失败:', error)
  } finally {
    submitting.value = false
  }
}

async function deleteUser(row) {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？（软删除，标记为禁用）`,
      '提示', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
    )
  } catch (_) { return }

  try {
    await userApi.delete(row.id)
    ElMessage.success('用户已删除')
    loadUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-form {
  margin-bottom: 16px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>