<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button 
        type="primary" 
        @click="showAddDialog = true"
        v-if="hasPermission('user:create')"
      >
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option 
              v-for="role in roleOptions" 
              :key="role.value" 
              :label="role.label" 
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <div class="table-container">
      <el-table 
        :data="userList" 
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ getRoleLabel(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="160" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="handleView(row)"
              v-if="hasPermission('user:view')"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(row)"
              v-if="hasPermission('user:edit')"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              :type="row.status === 'active' ? 'warning' : 'success'" 
              @click="handleToggleStatus(row)"
              v-if="hasPermission('user:edit')"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              v-if="hasPermission('user:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加/编辑用户对话框 -->
    <el-dialog 
      v-model="showAddDialog" 
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="600px"
    >
      <el-form 
        :model="userForm" 
        :rules="userFormRules" 
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="!!editingUser" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option 
              v-for="role in roleOptions" 
              :key="role.value" 
              :label="role.label" 
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!editingUser">
          <el-input v-model="userForm.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser" :loading="saving">
          {{ editingUser ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="showViewDialog" title="用户详情" width="500px">
      <div class="user-detail" v-if="viewingUser">
        <div class="detail-item">
          <label>用户名：</label>
          <span>{{ viewingUser.username }}</span>
        </div>
        <div class="detail-item">
          <label>姓名：</label>
          <span>{{ viewingUser.name }}</span>
        </div>
        <div class="detail-item">
          <label>邮箱：</label>
          <span>{{ viewingUser.email }}</span>
        </div>
        <div class="detail-item">
          <label>手机号：</label>
          <span>{{ viewingUser.phone }}</span>
        </div>
        <div class="detail-item">
          <label>角色：</label>
          <el-tag :type="getRoleTagType(viewingUser.role)">
            {{ getRoleLabel(viewingUser.role) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>状态：</label>
          <el-tag :type="viewingUser.status === 'active' ? 'success' : 'danger'">
            {{ viewingUser.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>最后登录：</label>
          <span>{{ viewingUser.lastLogin || '从未登录' }}</span>
        </div>
        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ viewingUser.createdAt }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/stores/permission'
import { userAPI } from '@/services/api'

const permissionStore = usePermissionStore()

// 权限检查
const hasPermission = (permission) => {
  return permissionStore.hasPermission.value(permission)
}

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const userList = ref([])
const showAddDialog = ref(false)
const showViewDialog = ref(false)
const editingUser = ref(null)
const viewingUser = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  role: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  username: '',
  name: '',
  email: '',
  phone: '',
  role: '',
  password: '',
  confirmPassword: '',
  status: 'active'
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 角色选项
const roleOptions = [
  { label: '超级管理员', value: 'super_admin' },
  { label: '管理员', value: 'admin' },
  { label: '经理', value: 'manager' },
  { label: '操作员', value: 'operator' },
  { label: '查看者', value: 'viewer' }
]

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    'super_admin': 'danger',
    'admin': 'warning',
    'manager': 'primary',
    'operator': 'success',
    'viewer': 'info'
  }
  return typeMap[role] || 'info'
}

// 获取角色标签
const getRoleLabel = (role) => {
  const labelMap = {
    'super_admin': '超级管理员',
    'admin': '管理员',
    'manager': '经理',
    'operator': '操作员',
    'viewer': '查看者'
  }
  return labelMap[role] || role
}

// 方法
const loadUserList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 模拟API调用
    const response = await mockUserAPI.getUsers(params)
    userList.value = response.data.list
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    role: '',
    status: ''
  })
  pagination.page = 1
  loadUserList()
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadUserList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadUserList()
}

const handleView = (user) => {
  viewingUser.value = user
  showViewDialog.value = true
}

const handleEdit = (user) => {
  editingUser.value = user
  Object.assign(userForm, {
    username: user.username,
    name: user.name,
    email: user.email,
    phone: user.phone,
    role: user.role,
    status: user.status,
    password: '',
    confirmPassword: ''
  })
  showAddDialog.value = true
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    await mockUserAPI.deleteUser(user.id)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleStatus = async (user) => {
  try {
    const newStatus = user.status === 'active' ? 'inactive' : 'active'
    await mockUserAPI.updateUserStatus(user.id, newStatus)
    ElMessage.success(`${newStatus === 'active' ? '启用' : '禁用'}成功`)
    loadUserList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleSaveUser = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate()
    
    saving.value = true
    
    if (editingUser.value) {
      // 更新用户
      await mockUserAPI.updateUser(editingUser.value.id, userForm)
      ElMessage.success('更新成功')
    } else {
      // 添加用户
      await mockUserAPI.createUser(userForm)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetUserForm()
    loadUserList()
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const resetUserForm = () => {
  Object.assign(userForm, {
    username: '',
    name: '',
    email: '',
    phone: '',
    role: '',
    password: '',
    confirmPassword: '',
    status: 'active'
  })
  editingUser.value = null
}

// 模拟API
const mockUserAPI = {
  async getUsers(params) {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        username: 'admin',
        name: '系统管理员',
        email: 'admin@example.com',
        phone: '13800138000',
        role: 'super_admin',
        status: 'active',
        lastLogin: '2025-01-21 10:30:00',
        createdAt: '2025-01-01 00:00:00'
      },
      {
        id: 2,
        username: 'manager',
        name: '张经理',
        email: 'manager@example.com',
        phone: '13800138001',
        role: 'manager',
        status: 'active',
        lastLogin: '2025-01-21 09:15:00',
        createdAt: '2025-01-02 00:00:00'
      },
      {
        id: 3,
        username: 'operator',
        name: '李操作员',
        email: 'operator@example.com',
        phone: '13800138002',
        role: 'operator',
        status: 'active',
        lastLogin: '2025-01-20 16:45:00',
        createdAt: '2025-01-03 00:00:00'
      }
    ]
    
    return {
      success: true,
      data: {
        list: mockData,
        total: mockData.length
      }
    }
  },
  
  async createUser(userData) {
    return { success: true }
  },
  
  async updateUser(id, userData) {
    return { success: true }
  },
  
  async deleteUser(id) {
    return { success: true }
  },
  
  async updateUserStatus(id, status) {
    return { success: true }
  }
}

const userFormRef = ref()

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

<style scoped>
.user-management {
  padding: 20px;
}

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

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-bar {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.user-detail {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #666;
}

.detail-item span {
  color: #333;
}
</style>