<template>
  <div class="admin-manage">
    <div class="header">
      <h2>管理员账号管理</h2>
      <button @click="showCreateDialog = true" class="btn-primary">
        <span>➕</span> 添加管理员
      </button>
    </div>

    <div class="admin-cards">
      <div v-for="admin in admins" :key="admin.id" class="admin-card">
        <div class="card-header">
          <div class="admin-info">
            <div class="admin-avatar">
              {{ admin.username.charAt(0).toUpperCase() }}
            </div>
            <div class="admin-details">
              <div class="admin-name">{{ admin.name }}</div>
              <div class="admin-username">@{{ admin.username }}</div>
            </div>
          </div>
          <span :class="['role-badge', admin.role]">
            {{ admin.role === 'super' ? '超级管理员' : '管理员' }}
          </span>
        </div>
        
        <div class="card-meta">
          <span class="meta-item">
            <span class="meta-icon">📅</span>
            创建于 {{ formatDate(admin.createdAt) }}
          </span>
        </div>
        
        <div class="card-actions">
          <button @click="editAdmin(admin)" class="btn-action btn-edit">
            <span>✏️</span> 编辑
          </button>
          <button @click="changePassword(admin)" class="btn-action btn-password">
            <span>🔑</span> 改密码
          </button>
          <button 
            v-if="admin.role !== 'super'" 
            @click="deleteAdmin(admin)" 
            class="btn-action btn-delete"
          >
            <span>🗑️</span> 删除
          </button>
        </div>
      </div>
      
      <div v-if="!admins.length" class="empty-state">
        <div class="empty-icon">👥</div>
        <div class="empty-text">暂无管理员</div>
      </div>
    </div>

    <!-- 创建管理员对话框 -->
    <div v-if="showCreateDialog" class="dialog-overlay" @click.self="showCreateDialog = false">
      <div class="dialog">
        <h3>添加管理员</h3>
        <form @submit.prevent="createAdmin">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="newAdmin.username" required placeholder="请输入用户名" />
          </div>
          <div class="form-group">
            <label>姓名</label>
            <input v-model="newAdmin.name" required placeholder="请输入姓名" />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input v-model="newAdmin.password" type="password" required placeholder="请输入密码" />
          </div>
          <div class="form-group">
            <label>角色</label>
            <select v-model="newAdmin.role">
              <option value="admin">管理员</option>
              <option value="super">超级管理员</option>
            </select>
          </div>
          <div class="dialog-actions">
            <button type="button" @click="showCreateDialog = false" class="btn-cancel">取消</button>
            <button type="submit" class="btn-primary">创建</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑管理员对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click.self="showEditDialog = false">
      <div class="dialog">
        <h3>编辑管理员</h3>
        <form @submit.prevent="updateAdmin">
          <div class="form-group">
            <label>用户名</label>
            <input :value="editingAdmin.username" disabled />
          </div>
          <div class="form-group">
            <label>姓名</label>
            <input v-model="editingAdmin.name" required placeholder="请输入姓名" />
          </div>
          <div class="form-group">
            <label>角色</label>
            <select v-model="editingAdmin.role">
              <option value="admin">管理员</option>
              <option value="super">超级管理员</option>
            </select>
          </div>
          <div class="dialog-actions">
            <button type="button" @click="showEditDialog = false" class="btn-cancel">取消</button>
            <button type="submit" class="btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <div v-if="showPasswordDialog" class="dialog-overlay" @click.self="showPasswordDialog = false">
      <div class="dialog">
        <h3>修改密码</h3>
        <form @submit.prevent="updatePassword">
          <div class="form-group">
            <label>用户名</label>
            <input :value="passwordAdmin.username" disabled />
          </div>
          <div class="form-group">
            <label>新密码</label>
            <input v-model="newPassword" type="password" required placeholder="请输入新密码" />
          </div>
          <div class="dialog-actions">
            <button type="button" @click="showPasswordDialog = false" class="btn-cancel">取消</button>
            <button type="submit" class="btn-primary">确认</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '../../api';
import { showToast } from 'vant';

const admins = ref([]);
const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const showPasswordDialog = ref(false);

const newAdmin = ref({
  username: '',
  name: '',
  password: '',
  role: 'admin'
});

const editingAdmin = ref({});
const passwordAdmin = ref({});
const newPassword = ref('');

const loadAdmins = async () => {
  try {
    const { data } = await api.getAdmins();
    console.log('管理员数据:', data);
    admins.value = data;
  } catch (error) {
    console.error('加载管理员列表失败:', error);
    console.error('错误详情:', error.response?.data);
    if (error.response?.status === 403) {
      showToast('需要超级管理员权限');
    } else if (error.response?.status === 401) {
      showToast('登录已过期，请重新登录');
    } else {
      showToast(error.response?.data?.error || '加载失败');
    }
  }
};

const createAdmin = async () => {
  try {
    await api.createAdmin(newAdmin.value);
    showToast('创建成功');
    showCreateDialog.value = false;
    newAdmin.value = { username: '', name: '', password: '', role: 'admin' };
    loadAdmins();
  } catch (error) {
    showToast(error.response?.data?.error || '创建失败');
  }
};

const editAdmin = (admin) => {
  editingAdmin.value = { ...admin };
  showEditDialog.value = true;
};

const updateAdmin = async () => {
  try {
    await api.updateAdmin(editingAdmin.value.id, {
      name: editingAdmin.value.name,
      role: editingAdmin.value.role
    });
    showToast('更新成功');
    showEditDialog.value = false;
    loadAdmins();
  } catch (error) {
    showToast('更新失败');
  }
};

const changePassword = (admin) => {
  passwordAdmin.value = admin;
  newPassword.value = '';
  showPasswordDialog.value = true;
};

const updatePassword = async () => {
  try {
    await api.updateAdminPassword(passwordAdmin.value.id, {
      newPassword: newPassword.value
    });
    showToast('密码修改成功');
    showPasswordDialog.value = false;
  } catch (error) {
    showToast('修改失败');
  }
};

const deleteAdmin = async (admin) => {
  if (!confirm(`确定删除管理员 ${admin.username} 吗？`)) return;
  
  try {
    await api.deleteAdmin(admin.id);
    showToast('删除成功');
    loadAdmins();
  } catch (error) {
    showToast(error.response?.data?.error || '删除失败');
  }
};

const formatDate = (date) => {
  if (!date) return '-';
  try {
    return new Date(date).toLocaleDateString('zh-CN');
  } catch (error) {
    return '-';
  }
};

onMounted(loadAdmins);
</script>

<style scoped>
.admin-manage {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
}

.btn-primary {
  padding: 12px 24px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(77, 171, 247, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(77, 171, 247, 0.4);
}

.btn-primary:active {
  transform: translateY(0);
}

.btn-primary span {
  font-size: 18px;
}

.admin-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.admin-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
}

.admin-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 12px;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.admin-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 700;
  flex-shrink: 0;
}

.admin-details {
  flex: 1;
  min-width: 0;
}

.admin-name {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.admin-username {
  font-size: 13px;
  color: #999;
}

.role-badge {
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
  flex-shrink: 0;
}

.role-badge.super {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.role-badge.admin {
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(77, 171, 247, 0.3);
}

.card-meta {
  padding: 12px 0;
  border-top: 1px solid #f5f5f5;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.meta-icon {
  font-size: 16px;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-action {
  flex: 1;
  min-width: 80px;
  padding: 10px 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.2s;
}

.btn-action:hover {
  transform: translateY(-2px);
}

.btn-action:active {
  transform: translateY(0);
}

.btn-edit {
  background: #e3f2fd;
  color: #1976d2;
}

.btn-edit:hover {
  background: #bbdefb;
}

.btn-password {
  background: #fff3e0;
  color: #f57c00;
}

.btn-password:hover {
  background: #ffe0b2;
}

.btn-delete {
  background: #ffebee;
  color: #d32f2f;
}

.btn-delete:hover {
  background: #ffcdd2;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #999;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
  backdrop-filter: blur(4px);
}

.dialog {
  background: white;
  padding: 28px;
  border-radius: 16px;
  width: 100%;
  max-width: 440px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.dialog h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e8e8e8;
  border-radius: 10px;
  font-size: 14px;
  transition: all 0.2s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #4dabf7;
  box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.1);
}

.form-group input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
  color: #999;
}

.form-group input::placeholder {
  color: #bbb;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 28px;
}

.dialog-actions button {
  padding: 12px 24px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.2s;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-cancel:hover {
  background: #e8e8e8;
}

@media (max-width: 768px) {
  .admin-manage {
    padding: 16px;
  }
  
  .header h2 {
    font-size: 20px;
  }
  
  .admin-cards {
    grid-template-columns: 1fr;
  }
  
  .btn-action {
    min-width: 70px;
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .dialog {
    padding: 24px;
  }
}
</style>
