<template>
  <div class="admin-user-list-container">
    <h2 class="page-title">管理员管理</h2>
    
    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleCreate">
              注册管理员
            </el-button>
            <el-button icon="Refresh" @click="loadAdminUserList">刷新</el-button>
          </el-space>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户名、姓名、手机号"
            clearable
            @clear="loadAdminUserList"
            @keyup.enter="loadAdminUserList"
          >
            <template #append>
              <el-button icon="Search" @click="loadAdminUserList" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 管理员列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="adminUserList"
        stripe
        style="width: 100%"
      >
        <template #empty>
          <div class="custom-empty-state">
            <el-icon class="empty-icon"><UserFilled /></el-icon>
            <div class="empty-text">暂无管理员数据</div>
            <div class="empty-hint">点击"注册管理员"按钮开始创建</div>
          </div>
        </template>
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="username" label="用户名" width="150" />
        
        <el-table-column prop="realName" label="真实姓名" width="120" />
        
        <el-table-column prop="phone" label="手机号" width="130" />
        
        <el-table-column prop="email" label="邮箱" width="200" />
        
        <el-table-column label="角色" width="150">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              :type="role.roleCode === 'SUPER_ADMIN' ? 'danger' : 'primary'"
              style="margin-right: 5px"
            >
              {{ role.roleName }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="{ row }">
            {{ row.lastLoginTime ? formatDateTime(row.lastLoginTime) : '从未登录' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              :disabled="!canOperate(row)"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === 1"
              type="warning"
              link
              size="small"
              :disabled="!canOperate(row) || isCurrentUser(row)"
              @click="handleDisable(row)"
            >
              禁用
            </el-button>
            <el-button
              v-else
              type="success"
              link
              size="small"
              :disabled="!canOperate(row)"
              @click="handleEnable(row)"
            >
              启用
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              :disabled="!canOperate(row) || isCurrentUser(row)"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadAdminUserList"
          @current-change="loadAdminUserList"
        />
      </div>
    </el-card>
    
    <!-- 注册/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="密码" :prop="isEdit ? '' : 'password'">
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="isEdit ? '留空则不修改密码' : '请输入密码（至少6位）'"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in filteredRoleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, UserFilled } from '@element-plus/icons-vue'
import { API_BASE_URL, API_ENDPOINTS } from '@/config/api'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 数据
const loading = ref(false)
const adminUserList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const roleList = ref([])

// 筛选角色列表，只显示普通管理员和超级管理员
const filteredRoleList = computed(() => {
  const base = roleList.value.filter(role => 
    role.roleCode === 'ADMIN' || role.roleCode === 'SUPER_ADMIN'
  )
  if (userStore.isSuperAdmin) return base
  return base.filter(role => role.roleCode !== 'SUPER_ADMIN')
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('注册管理员')
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const formData = ref({
  id: null,
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  roleId: null,
  status: 1
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 加载管理员列表
const loadAdminUserList = async () => {
  loading.value = true
  try {
    const response = await fetch(
      `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_LIST}?page=${currentPage.value}&pageSize=${pageSize.value}&keyword=${encodeURIComponent(searchQuery.value || '')}`,
      {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    const result = await response.json()
    if (result.code === 200) {
      adminUserList.value = result.data.list || []
      total.value = result.data.total || 0
    } else {
      ElMessage.error(result.message || '加载失败')
    }
  } catch (error) {
    console.error('加载管理员列表失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    const response = await fetch(
      `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_ROLES}`,
      {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    const result = await response.json()
    if (result.code === 200) {
      roleList.value = result.data || []
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
  }
}

// 创建
const handleCreate = () => {
  isEdit.value = false
  dialogTitle.value = '注册管理员'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑管理员'
  formData.value = {
    id: row.id,
    username: row.username,
    password: '',
    realName: row.realName || '',
    phone: row.phone || '',
    email: row.email || '',
    roleId: row.roles && row.roles.length > 0 ? row.roles[0].id : null,
    status: row.status
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员"${row.username}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await fetch(
      `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_DELETE}/${row.id}`,
      {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('删除成功')
      loadAdminUserList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      const url = isEdit.value
        ? `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_UPDATE}/${formData.value.id}`
        : `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_REGISTER}`
      
      const method = isEdit.value ? 'PUT' : 'POST'
      
      const body = { ...formData.value }
      // 将单个roleId转换为roleIds数组
      if (body.roleId) {
        body.roleIds = [body.roleId]
      }
      delete body.roleId
      if (isEdit.value && !body.password) {
        delete body.password
      }
      
      const response = await fetch(url, {
        method,
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      })
      
      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '注册成功')
        dialogVisible.value = false
        loadAdminUserList()
      } else {
        ElMessage.error(result.message || '操作失败')
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: null,
    username: '',
    password: '',
    realName: '',
    phone: '',
    email: '',
    roleId: null,
    status: 1
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 判断是否是超级管理员
const isSuperAdmin = (row) => {
  return row.roles && row.roles.some(r => r.roleCode === 'SUPER_ADMIN')
}

// 判断是否是当前用户
const isCurrentUser = (row) => {
  return row.id === userStore.userInfo?.id
}

// 是否允许对该行用户进行操作
const canOperate = (row) => {
  if (!row) return false
  if (isCurrentUser(row)) return true

  const targetIsSuperAdmin = isSuperAdmin(row)
  if (targetIsSuperAdmin) {
    return false
  }

  if (userStore.isSuperAdmin) {
    return true
  }

  return false
}

// 禁用管理员
const handleDisable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用管理员"${row.username}"吗？禁用后将无法登录系统。`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await fetch(
      `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_DISABLE}/${row.id}`,
      {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('禁用成功')
      loadAdminUserList()
    } else {
      ElMessage.error(result.message || '禁用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('禁用失败:', error)
      ElMessage.error('禁用失败')
    }
  }
}

// 启用管理员
const handleEnable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要启用管理员"${row.username}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const response = await fetch(
      `${API_BASE_URL}${API_ENDPOINTS.ADMIN_USER_ENABLE}/${row.id}`,
      {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('启用成功')
      loadAdminUserList()
    } else {
      ElMessage.error(result.message || '启用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启用失败:', error)
      ElMessage.error('启用失败')
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadAdminUserList()
  loadRoleList()
})
</script>

<style scoped>
.admin-user-list-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.custom-empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 12px;
  color: #c0c4cc;
}

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

