<template>
  <Page
    description="管理系统管理员账户信息"
    title="管理员管理"
  >
    <div class="flex flex-col gap-4">
      <!-- 搜索表单 -->
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <Icon icon="ep:search" class="mr-1" />
              搜索
            </el-button>
            <el-button @click="handleReset">
              <Icon icon="ep:refresh" class="mr-1" />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作按钮和数据表格 -->
      <el-card>
        <div class="mb-4">
          <el-button type="primary" @click="handleAdd">
            <Icon icon="ep:plus" class="mr-1" />
            新增管理员
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            <Icon icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
        </div>

        <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="uid" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" min-width="120" />
      <el-table-column prop="realName" label="真实姓名" min-width="120" />
      <el-table-column prop="mobile" label="手机号" min-width="120" />
      <el-table-column prop="email" label="邮箱" min-width="150" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isAdmin" label="超级管理员" width="120">
        <template #default="{ row }">
          <el-tag :type="row.isAdmin === 1 ? 'warning' : 'info'">
            {{ row.isAdmin === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="warning" size="small" @click="handleSetRoles(row)">
            角色
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <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="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            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="mobile">
          <el-input v-model="formData.mobile" 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="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">未知</el-radio>
          </el-radio-group>
        </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-item label="超级管理员" prop="isAdmin">
          <el-radio-group v-model="formData.isAdmin">
            <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="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog v-model="roleDialogVisible" title="分配角色" width="500px">
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox
          v-for="role in roleList"
          :key="role.roleId"
          :label="role.roleId"
        >
          {{ role.roleName }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoles" :loading="roleLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
      </el-card>
    </div>
  </Page>
</template>

<script lang="ts" setup>
// 1. Vue 相关导入
import { ref, reactive, onMounted } from 'vue';

// 2. Element Plus 组件导入
import {
  ElButton,
  ElCard,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElRow,
  ElSelect,
  ElSpace,
  ElSwitch,
  ElTable,
  ElTableColumn,
  ElTag,
  type FormInstance,
} from 'element-plus';

// 3. 图标组件导入
import { Icon } from '@iconify/vue';

// 4. Vben 组件导入
import { Page } from '@vben/common-ui';

// 5. 项目内部导入
import {
  getAdminListApi,
  createAdminApi,
  updateAdminApi,
  deleteAdminApi,
  batchDeleteAdminApi,
  setAdminRolesApi,
  getAdminRolesApi,
  getAllRolesApi,
  type AdminUser,
  type CreateAdminParams,
  type UpdateAdminParams,
  type Role,
} from '#/api/common/auth';

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const roleLoading = ref(false);
const tableData = ref<AdminUser[]>([]);
const selectedRows = ref<AdminUser[]>([]);
const roleList = ref<Role[]>([]);
const selectedRoleIds = ref<number[]>([]);
const currentUserId = ref<number>(0);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined,
});

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const roleDialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive<CreateAdminParams & { uid?: number }>({
  username: '',
  password: '',
  realName: '',
  mobile: '',
  email: '',
  sex: 0,
  status: 1,
  isAdmin: 0,
});

// 表单验证规则
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' },
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? '编辑管理员' : '新增管理员'));

// 方法
const formatTime = (timestamp: number) => {
  if (!timestamp) return '-';
  return new Date(timestamp * 1000).toLocaleString();
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status,
    };
    const result = await getAdminListApi(params);
    tableData.value = result.list;
    pagination.total = result.total;
  } catch (error) {
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

const loadRoles = async () => {
  try {
    roleList.value = await getAllRolesApi();
  } catch (error) {
    ElMessage.error('加载角色列表失败');
  }
};

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

const handleReset = () => {
  searchForm.keyword = '';
  searchForm.status = undefined;
  handleSearch();
};

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

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

const handleSelectionChange = (selection: AdminUser[]) => {
  selectedRows.value = selection;
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: AdminUser) => {
  isEdit.value = true;
  Object.assign(formData, {
    uid: row.uid,
    username: row.username,
    password: '',
    realName: row.realName,
    mobile: row.mobile,
    email: row.email,
    sex: row.sex,
    status: row.status,
    isAdmin: row.isAdmin,
  });
  dialogVisible.value = true;
};

const handleDelete = async (row: AdminUser) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员 "${row.username}" 吗？`,
      '确认删除',
      {
        type: 'warning',
      }
    );
    await deleteAdminApi(row.uid);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个管理员吗？`,
      '确认删除',
      {
        type: 'warning',
      }
    );
    const uids = selectedRows.value.map(row => row.uid);
    await batchDeleteAdminApi(uids);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const handleSetRoles = async (row: AdminUser) => {
  currentUserId.value = row.uid;
  try {
    const roles = await getAdminRolesApi(row.uid);
    selectedRoleIds.value = roles.map(role => role.roleId);
    roleDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('加载用户角色失败');
  }
};

const handleSaveRoles = async () => {
  roleLoading.value = true;
  try {
    await setAdminRolesApi(currentUserId.value, selectedRoleIds.value);
    ElMessage.success('角色分配成功');
    roleDialogVisible.value = false;
    loadData();
  } catch (error) {
    ElMessage.error('角色分配失败');
  } finally {
    roleLoading.value = false;
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (isEdit.value) {
      const updateData: UpdateAdminParams = {
        uid: formData.uid!,
        username: formData.username,
        realName: formData.realName,
        mobile: formData.mobile,
        email: formData.email,
        sex: formData.sex,
        status: formData.status,
        isAdmin: formData.isAdmin,
      };
      if (formData.password) {
        updateData.password = formData.password;
      }
      await updateAdminApi(updateData);
      ElMessage.success('更新成功');
    } else {
      await createAdminApi(formData);
      ElMessage.success('创建成功');
    }
    
    dialogVisible.value = false;
    loadData();
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败');
  } finally {
    submitLoading.value = false;
  }
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
  resetForm();
};

const resetForm = () => {
  Object.assign(formData, {
    uid: undefined,
    username: '',
    password: '',
    realName: '',
    mobile: '',
    email: '',
    sex: 0,
    status: 1,
    isAdmin: 0,
  });
};

// 生命周期
onMounted(() => {
  loadData();
  loadRoles();
});
</script>

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

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

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