<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>管理员管理</span>
          <el-button type="primary" v-permission="'user:create'" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增管理员
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="用户名/姓名/手机号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="部门">
          <el-tree-select
            v-model="queryParams.departmentId"
            :data="departmentTree"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            :render-after-expand="false"
            placeholder="全部"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.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">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="userList" v-loading="loading">
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column prop="departmentName" label="部门" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" size="small" style="margin-right: 4px">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="row.username === 'admin'"
              @change="handleStatusChange(row)"
              v-permission="'user:update'"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="170" />
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" v-permission="'user:update'" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" v-permission="'user:assign_role'" @click="handleAssignRole(row)">分配角色</el-button>
            <el-button link type="primary" v-permission="'user:assign_department'" @click="handleAssignDepartment(row)">分配部门</el-button>
            <el-button link type="primary" v-permission="'user:assign_menu'" @click="handleAssignMenu(row)">专属菜单</el-button>
            <el-button link type="warning" v-permission="'user:reset_password'" @click="handleResetPassword(row)">重置密码</el-button>
            <el-button link type="danger" v-permission="'user:delete'" @click="handleDelete(row)" :disabled="row.username === 'admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="用户名" prop="username" v-if="!isEdit">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <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="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="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="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="400px">
      <el-checkbox-group v-model="checkedRoleIds">
        <el-checkbox v-for="role in allRoles" :key="role.id" :value="role.id" :disabled="role.code === 'super_admin'">
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRoles" :loading="roleSubmitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配部门对话框 -->
    <el-dialog v-model="departmentDialogVisible" title="分配部门" width="400px">
      <el-tree-select
        v-model="selectedDepartmentId"
        :data="departmentTree"
        :props="{ label: 'name', value: 'id', children: 'children' }"
        check-strictly
        :render-after-expand="false"
        placeholder="请选择部门"
        clearable
        style="width: 100%"
      />
      <template #footer>
        <el-button @click="departmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitDepartment" :loading="departmentSubmitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配专属菜单对话框 -->
    <el-dialog v-model="menuDialogVisible" title="分配专属菜单" width="500px">
      <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedMenuIds"
        :check-strictly="true"
      />
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMenus" :loading="menuSubmitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="重置密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPassword" :loading="passwordSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { ElTree } from 'element-plus'
import {
  getAdminUserList,
  createAdminUser,
  updateAdminUser,
  deleteAdminUser,
  setAdminUserStatus,
  resetPassword,
  assignRoles,
  getUserRoles,
  assignDepartment,
  getUserMenus,
  assignUserMenus,
  type AdminUser,
  type AdminUserQuery
} from '@/api/adminUser'
import { getAllRoles, type Role } from '@/api/role'
import { getDepartmentTree, type DepartmentTree } from '@/api/department'
import { getMenuTree, type MenuTree } from '@/api/menu'

const loading = ref(false)
const userList = ref<AdminUser[]>([])
const total = ref(0)

const queryParams = reactive<AdminUserQuery>({
  keyword: '',
  departmentId: undefined,
  status: undefined,
  page: 1,
  pageSize: 10
})

// 基础数据
const allRoles = ref<Role[]>([])
const departmentTree = ref<DepartmentTree[]>([])
const menuTree = ref<MenuTree[]>([])

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑管理员' : '新增管理员')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const formData = reactive({
  id: 0,
  username: '',
  password: '',
  realName: '',
  email: '',
  phone: '',
  status: 1
})

const formRules: 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' }
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
}

// 角色分配相关
const roleDialogVisible = ref(false)
const checkedRoleIds = ref<number[]>([])
const currentUserId = ref(0)
const roleSubmitLoading = ref(false)

// 部门分配相关
const departmentDialogVisible = ref(false)
const selectedDepartmentId = ref<number | null>(null)
const departmentSubmitLoading = ref(false)

// 菜单分配相关
const menuDialogVisible = ref(false)
const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const checkedMenuIds = ref<number[]>([])
const menuSubmitLoading = ref(false)

// 重置密码相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordSubmitLoading = ref(false)
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

const passwordRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getAdminUserList(queryParams)
    userList.value = res.data.list
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

const loadBaseData = async () => {
  const [rolesRes, deptRes, menuRes] = await Promise.all([
    getAllRoles(),
    getDepartmentTree(),
    getMenuTree()
  ])
  allRoles.value = rolesRes.data
  departmentTree.value = deptRes.data
  menuTree.value = menuRes.data
}

const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

const handleReset = () => {
  queryParams.keyword = ''
  queryParams.departmentId = undefined
  queryParams.status = undefined
  queryParams.page = 1
  fetchData()
}

const resetForm = () => {
  formData.id = 0
  formData.username = ''
  formData.password = ''
  formData.realName = ''
  formData.email = ''
  formData.phone = ''
  formData.status = 1
  formRef.value?.resetFields()
}

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

const handleEdit = (row: AdminUser) => {
  isEdit.value = true
  formData.id = row.id
  formData.realName = row.realName || ''
  formData.email = row.email || ''
  formData.phone = row.phone || ''
  formData.status = row.status
  dialogVisible.value = true
}

const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updateAdminUser(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createAdminUser(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row: AdminUser) => {
  try {
    await ElMessageBox.confirm(`确定要删除管理员 "${row.username}" 吗？`, '提示', { type: 'warning' })
    await deleteAdminUser(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

const handleStatusChange = async (row: AdminUser) => {
  try {
    await setAdminUserStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch {
    row.status = row.status === 1 ? 0 : 1
  }
}

const handleAssignRole = async (row: AdminUser) => {
  currentUserId.value = row.id
  const res = await getUserRoles(row.id)
  checkedRoleIds.value = res.data
  roleDialogVisible.value = true
}

const handleSubmitRoles = async () => {
  roleSubmitLoading.value = true
  try {
    await assignRoles({ userId: currentUserId.value, roleIds: checkedRoleIds.value })
    ElMessage.success('分配成功')
    roleDialogVisible.value = false
    fetchData()
  } finally {
    roleSubmitLoading.value = false
  }
}

const handleAssignDepartment = (row: AdminUser) => {
  currentUserId.value = row.id
  selectedDepartmentId.value = row.departmentId
  departmentDialogVisible.value = true
}

const handleSubmitDepartment = async () => {
  departmentSubmitLoading.value = true
  try {
    await assignDepartment({ userId: currentUserId.value, departmentId: selectedDepartmentId.value })
    ElMessage.success('分配成功')
    departmentDialogVisible.value = false
    fetchData()
  } finally {
    departmentSubmitLoading.value = false
  }
}

const handleAssignMenu = async (row: AdminUser) => {
  currentUserId.value = row.id
  const res = await getUserMenus(row.id)
  checkedMenuIds.value = res.data
  menuDialogVisible.value = true
}

const handleSubmitMenus = async () => {
  menuSubmitLoading.value = true
  try {
    const menuIds = menuTreeRef.value?.getCheckedKeys(false) as number[]
    await assignUserMenus({ userId: currentUserId.value, menuIds })
    ElMessage.success('分配成功')
    menuDialogVisible.value = false
  } finally {
    menuSubmitLoading.value = false
  }
}

const handleResetPassword = (row: AdminUser) => {
  currentUserId.value = row.id
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

const handleSubmitPassword = async () => {
  const valid = await passwordFormRef.value?.validate()
  if (!valid) return

  passwordSubmitLoading.value = true
  try {
    await resetPassword({ userId: currentUserId.value, newPassword: passwordForm.newPassword })
    ElMessage.success('密码重置成功')
    passwordDialogVisible.value = false
  } finally {
    passwordSubmitLoading.value = false
  }
}

onMounted(() => {
  loadBaseData()
  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

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