<template>
  <AdminLayout 
    title="系统管理" 
    subtitle="管理用户、角色、权限、部门等系统信息"
  >
    <div class="user-manage">
      <div class="header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>

      <el-table 
        :data="userList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        row-key="userID"
      >
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="realName" label="真实姓名" min-width="100" />
        <el-table-column prop="nickname" label="昵称" min-width="100" />
        <el-table-column prop="deptName" label="部门" min-width="120" />
        <el-table-column prop="roleName" label="角色" min-width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
              link
            >
              编辑
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleBindDeptRole(row)"
              link
            >
              绑定部门角色
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 新增/编辑用户对话框 -->
      <el-dialog
        v-model="userDialogVisible"
        :title="isEdit ? '编辑用户' : '新增用户'"
        width="600px"
        @close="resetForm"
      >
        <el-form
          ref="userFormRef"
          :model="currentUser"
          :rules="userFormRules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="currentUser.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!isEdit">
            <el-input 
              v-model="currentUser.password" 
              type="password" 
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="currentUser.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="currentUser.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="currentUser.realName" placeholder="请输入真实姓名" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="currentUser.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="currentUser.status">
              <el-radio :value="0">正常</el-radio>
              <el-radio :value="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="submitting">
            确定
          </el-button>
        </template>
      </el-dialog>

      <!-- 绑定部门角色对话框 -->
      <el-dialog
        v-model="bindDialogVisible"
        title="绑定部门角色"
        width="600px"
        @close="resetBindForm"
      >
        <el-form
          ref="bindFormRef"
          :model="bindForm"
          label-width="100px"
        >
          <el-form-item label="选择部门">
            <el-tree-select
              v-model="bindForm.deptId"
              :data="deptTree"
              check-strictly
              :render-after-expand="false"
              placeholder="请选择部门"
            />
          </el-form-item>
          <el-form-item label="选择角色">
            <el-select v-model="bindForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
              <el-option
                v-for="role in roles"
                :key="role.roleID"
                :label="role.name"
                :value="role.roleID"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="bindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBindForm" :loading="binding">
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { userApi, deptApi, roleApi } from '@/apis/system';
import type { SysUser, SysRole, PageParam, UserVO, UserDeptRoleVO } from '@/types';
import { AdminLayout } from '@/views/admin';

defineOptions({
  name: 'UserManageView'
});

const loading = ref(false);
const submitting = ref(false);
const binding = ref(false);

const userList = ref<UserVO[]>([]);
const deptTree = ref<any[]>([]);
const roles = ref<SysRole[]>([]);

// 分页参数
const pageParam = ref<PageParam>({
  pageNumber: 1,
  pageSize: 10
});
const total = ref(0);

const userDialogVisible = ref(false);
const bindDialogVisible = ref(false);
const isEdit = ref(false);

const userFormRef = ref<FormInstance>();
const bindFormRef = ref<FormInstance>();

const currentUser = ref<UserVO & { password?: string }>({
  status: 0
});

const bindForm = ref<{
  userId?: string;
  deptId?: string;
  roleIds: string[];
}>({
  roleIds: []
});

const userFormRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

onMounted(() => {
  loadUsers();
  loadDepts();
  loadRoles();
});

async function loadUsers() {
  try {
    loading.value = true;
    const result = await userApi.getUserPage(pageParam.value);
    if (result.success) {
      userList.value = result.dataList || [];
      total.value = result.pageParam?.totalElements || 0;
    }
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error('加载用户列表失败');
  } finally {
    loading.value = false;
  }
}

async function loadDepts() {
  try {
    const result = await deptApi.getAllDepts();
    if (result.success) {
      deptTree.value = result.dataList || [];
    }
  } catch (error) {
    console.error('加载部门列表失败:', error);
  }
}

async function loadRoles() {
  try {
    const result = await roleApi.getRoleList({});
    if (result.success) {
      roles.value = result.dataList || [];
    }
  } catch (error) {
    console.error('加载角色列表失败:', error);
  }
}

function handleAdd() {
  isEdit.value = false;
  currentUser.value = { status: 0 };
  userDialogVisible.value = true;
}

function handleEdit(row: UserVO) {
  isEdit.value = true;
  currentUser.value = { ...row };
  userDialogVisible.value = true;
}

async function handleDelete(row: UserVO) {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.username}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const result = await userApi.deleteUser({ id: row.id } as SysUser);
    if (result.success) {
      ElMessage.success('删除成功');
      loadUsers();
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

function handleBindDeptRole(row: UserVO) {
  bindForm.value = {
    userId: row.id,
    deptId: undefined,
    roleIds: []
  };
  bindDialogVisible.value = true;
}

async function submitUserForm() {
  if (!userFormRef.value) return;

  try {
    await userFormRef.value.validate();
    submitting.value = true;

    let result;
    if (isEdit.value) {
      result = await userApi.updateUser(currentUser.value as SysUser);
    } else {
      result = await userApi.createUser(currentUser.value as SysUser);
    }

    if (result.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
      userDialogVisible.value = false;
      loadUsers();
    } else {
      ElMessage.error(result.message || (isEdit.value ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
  } finally {
    submitting.value = false;
  }
}

async function submitBindForm() {
  try {
    binding.value = true;
    
    // 构建 UserDeptRoleVO 对象
    const userDeptRoleVO: UserDeptRoleVO = {
      user: { id: bindForm.value.userId } as SysUser,
      depts: bindForm.value.deptId ? [{ id: bindForm.value.deptId }] : [],
      roles: bindForm.value.roleIds.map(roleId => ({ id: roleId }))
    };
    
    const result = await userApi.bindUserDeptRole(userDeptRoleVO);

    if (result.success) {
      ElMessage.success('绑定成功');
      bindDialogVisible.value = false;
      loadUsers();
    } else {
      ElMessage.error(result.message || '绑定失败');
    }
  } catch (error) {
    console.error('绑定失败:', error);
    ElMessage.error('绑定失败');
  } finally {
    binding.value = false;
  }
}

function resetForm() {
  userFormRef.value?.resetFields();
}

function resetBindForm() {
  bindFormRef.value?.resetFields();
}

function handlePageChange(page: number) {
  pageParam.value.pageNumber = page;
  loadUsers();
}

function handleSizeChange(size: number) {
  pageParam.value.pageSize = size;
  pageParam.value.pageNumber = 1; // 改变每页数量时，重置到第一页
  loadUsers();
}
</script>

<style lang="scss" scoped>
.user-manage {
  background: #FFFFFF;
  padding: 24px;
  border-radius: 14px;
}

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

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #101828;
  }
}

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