<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>人员管理</span>
      </div>
    </template>
    <div class="table-header">
      <el-input v-model="searchName" placeholder="按姓名搜索" clearable @clear="fetchUsers" @keyup.enter="fetchUsers" style="width: 200px;"></el-input>
      <el-select v-model="searchRole" placeholder="按角色筛选" clearable @change="fetchUsers" style="width: 150px;">
         <el-option label="管理员" value="ADMIN"></el-option>
         <el-option label="决策者" value="DECISION_MAKER"></el-option>
         <el-option label="主管" value="SUPERVISOR"></el-option>
         <el-option label="网格员" value="GRID_WORKER"></el-option>
         <el-option label="公众监督员" value="PUBLIC_SUPERVISOR"></el-option>
      </el-select>
      <el-button type="primary" @click="fetchUsers" :icon="Search">搜索</el-button>
    </div>

    <el-table :data="users" v-loading="loading" style="width: 100%" border stripe table-layout="auto" class="user-table compact-table">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" align="center"></el-table-column>
      <el-table-column prop="gender" label="性别" width="70" align="center">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="150" align="center">
         <template #default="scope">
           <el-tag :type="roleTagType(scope.row.role)" size="small">{{ formatRole(scope.row.role) }}</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
           <el-tag :type="statusTagType(scope.row.status)" size="small" disable-transitions>{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定要删除这位用户吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      v-model:page-size="pagination.size"
      v-model:current-page="pagination.page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end;"
    ></el-pagination>

  <!-- Edit User Dialog -->
  <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="700px" :show-close="false" class="edit-dialog ultimate-dialog">
     <template #header="{ close, titleId, titleClass }">
      <div class="ultimate-dialog-header">
        <h4 :id="titleId" :class="titleClass">
           <el-icon class="header-icon"><EditPen /></el-icon>
           编辑用户信息
        </h4>
        <el-button circle :icon="Close" type="danger" class="header-close-btn" @click="close"></el-button>
      </div>
    </template>
    <el-form :model="editForm" ref="editFormRef" label-width="90px" label-position="top">
      
      <div class="form-section">
        <h3 class="section-title">身份凭证</h3>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item>
              <template #label>
                <div class="form-label-icon">
                  <el-icon><User /></el-icon>
                  <span>用户ID</span>
                </div>
              </template>
              <el-input v-model="editForm.id" disabled class="readonly-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template #label>
                <div class="form-label-icon">
                  <el-icon><Avatar /></el-icon>
                  <span>姓名</span>
                </div>
              </template>
              <el-input v-model="editForm.name" disabled class="readonly-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <h3 class="section-title">详细信息</h3>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="phone">
               <template #label>
                <div class="form-label-icon">
                  <el-icon><Phone /></el-icon>
                  <span>手机号</span>
                </div>
              </template>
              <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="gender">
               <template #label>
                <div class="form-label-icon">
                  <el-icon><Male /></el-icon>
                  <span>性别</span>
                </div>
              </template>
              <el-radio-group v-model="editForm.gender">
                <el-radio label="MALE">男</el-radio>
                <el-radio label="FEMALE">女</el-radio>
                <el-radio label="OTHER">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="role">
               <template #label>
                <div class="form-label-icon">
                  <el-icon><Key /></el-icon>
                  <span>角色</span>
                </div>
              </template>
              <el-select v-model="editForm.role" placeholder="选择角色" style="width:100%;">
                  <el-option label="管理员" value="ADMIN"></el-option>
                  <el-option label="决策者" value="DECISION_MAKER"></el-option>
                  <el-option label="主管" value="SUPERVISOR"></el-option>
                  <el-option label="网格员" value="GRID_WORKER"></el-option>
                  <el-option label="公众监督员" value="PUBLIC_SUPERVISOR"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
               <template #label>
                <div class="form-label-icon">
                  <el-icon><Switch /></el-icon>
                  <span>状态</span>
                </div>
              </template>
              <el-select v-model="editForm.status" placeholder="选择状态" style="width:100%;">
                  <el-option label="ACTIVE" value="ACTIVE"></el-option>
                  <el-option label="INACTIVE" value="INACTIVE"></el-option>
                  <el-option label="SUSPENDED" value="SUSPENDED"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
  </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false" plain>取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="isSaving" :icon="Check">确 认 保 存</el-button>
      </span>
    </template>
  </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, User, Avatar, Phone, Male, Key, Switch, Close, Check, EditPen } from '@element-plus/icons-vue';
import { getUsers, updateUser, deleteUser } from '@/api/personnel';
import type { UserAccount, UserUpdateRequest } from '@/api/types';

const users = ref<UserAccount[]>([]);
const loading = ref(true);
const total = ref(0);
const searchName = ref('');
const searchRole = ref('');

const pagination = reactive({
  page: 1,
  size: 10,
});

const editDialogVisible = ref(false);
const isSaving = ref(false);
const editFormRef = ref();
const editForm = reactive<Partial<UserAccount>>({});

const roleMap: Record<string, string> = {
  ADMIN: '管理员',
  DECISION_MAKER: '决策者',
  SUPERVISOR: '主管',
  GRID_WORKER: '网格员',
  PUBLIC_SUPERVISOR: '公众监督员'
};

const formatRole = (role: string) => roleMap[role] || role;
const formatGender = (gender: 'MALE' | 'FEMALE' | 'OTHER') => {
  if (gender === 'MALE') return '男';
  if (gender === 'FEMALE') return '女';
  return '未知';
}

const roleTagType = (role: string) => {
  switch (role) {
    case 'ADMIN': return 'danger';
    case 'DECISION_MAKER': return 'warning';
    case 'SUPERVISOR': return 'primary';
    default: return 'info';
  }
};

const statusTagType = (status: string) => {
  if (status === 'ACTIVE') return 'success';
  if (status === 'INACTIVE') return 'info';
  if (status === 'SUSPENDED') return 'warning';
  return '';
};

const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      name: searchName.value || undefined,
      role: searchRole.value || undefined,
    };
    const response = await getUsers(params);
    users.value = response.content;
    total.value = response.totalElements;
  } catch (error) {
    console.error("获取用户列表时出错:", error);
    ElMessage.error('获取用户列表失败，请检查网络或联系管理员。');
  } finally {
    loading.value = false;
  }
};

const handleEdit = (user: UserAccount) => {
  Object.assign(editForm, user);
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  if (!editForm.id) return;
  isSaving.value = true;
  
  const updateData: UserUpdateRequest = {
      phone: editForm.phone,
      gender: editForm.gender as 'MALE' | 'FEMALE' | 'OTHER',
      role: editForm.role,
      status: editForm.status,
  };

  try {
    await updateUser(editForm.id, updateData);
    ElMessage.success('用户信息更新成功');
    editDialogVisible.value = false;
    await fetchUsers();
  } catch (error) {
    console.error(`更新用户 #${editForm.id} 失败:`, error);
    ElMessage.error('更新失败，请重试。');
  } finally {
    isSaving.value = false;
  }
};

const handleDelete = async (userId: number) => {
  try {
    await deleteUser(userId);
    ElMessage.success('删除成功');
    await fetchUsers();
  } catch (error) {
    console.error(`删除用户 #${userId} 失败:`, error);
    ElMessage.error('删除失败，请重试。');
  }
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  fetchUsers();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchUsers();
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.table-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.user-table {
  font-size: 14px;
}

.compact-table :deep(.el-table__cell) {
  padding: 6px 0;
}

.user-table .el-button {
  margin: 0 4px;
}

.el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
}

:deep(.el-table__row .el-button) {
    visibility: hidden;
}

:deep(.el-table__row:hover .el-button) {
    visibility: visible;
}

/* Ultimate Dialog Styles */
.ultimate-dialog .el-dialog__header {
  display: none; /* Hide original header */
}

.ultimate-dialog {
  --el-dialog-padding-primary: 0;
  background: linear-gradient(to top right, #e0f2f1, #ffffff);
}

.ultimate-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.ultimate-dialog-header h4 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 1.3rem;
}

.header-close-btn {
  --el-button-bg-color: transparent;
  --el-button-border-color: transparent;
  --el-button-hover-bg-color: var(--el-color-danger-light-8);
  --el-button-hover-border-color: var(--el-color-danger-light-8);
}

.ultimate-dialog .el-dialog__body {
  padding: 24px 30px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 100%);
}

.form-section {
  background-color: rgba(255, 255, 255, 0.7);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 25px;
  border: 1px solid rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #495057;
  margin-top: 0;
  margin-bottom: 24px;
  border-left: 4px solid var(--el-color-primary);
  padding-left: 12px;
}

.form-label-icon {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #343a40;
}

.readonly-input {
  --el-input-disabled-bg-color: #eef1f6;
  --el-input-disabled-text-color: #303133;
  --el-input-disabled-border-color: #dcdfe6;
}

.dialog-footer {
  text-align: right;
  padding: 10px 30px 20px;
}
</style> 