<template>
  <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="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="creatorName" label="创建人" width="120" />
      <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>

    <!-- 新增/编辑用户对话框 -->
    <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-select v-model="currentUser.status" placeholder="请选择状态">
            <el-option label="正常" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定部门角色对话框 -->
    <el-dialog
      v-model="bindDeptRoleDialogVisible"
      title="绑定部门角色"
      width="800px"
      @close="resetBindForm"
    >
      <div class="bind-info">
        <el-alert 
          :title="`用户：${currentUser.username} (${currentUser.realName})`" 
          type="info" 
          :closable="false"
          style="margin-bottom: 20px"
        />
      </div>

      <el-table :data="bindList" style="width: 100%" border stripe>
        <el-table-column width="80" label="绑定状态">
          <template #default="{ row }">
            <el-tag 
              :type="isSelected(row) ? 'success' : 'info'"
              size="small"
            >
              {{ isSelected(row) ? '已绑定' : '未绑定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" min-width="150" />
        <el-table-column prop="roleName" label="角色" min-width="150" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button 
              :type="isSelected(row) ? 'danger' : 'primary'"
              size="small" 
              @click="toggleSelection(row)"
            >
              {{ isSelected(row) ? '解绑' : '绑定' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="bind-stats" style="margin-top: 20px">
        <el-alert 
          :title="`已绑定 ${selectedBindings.length} 个部门角色，未绑定 ${bindList.length - selectedBindings.length} 个部门角色`" 
          type="info" 
          :closable="false"
          show-icon
        />
      </div>

      <template #footer>
        <el-button @click="bindDeptRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBindings" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { userApi } from '@/apis/system/user';
import { deptApi } from '@/apis/system/dept';
import { roleApi } from '@/apis/system/role';
import type { SysUser, UserDeptRoleVO, UserVO, SysDeptRole} from '@/types';

// 扩展部门角色类型，包含绑定状态和显示信息
interface DeptRoleBindItem extends SysDeptRole {
  deptName?: string;
  roleName?: string;
  isBound?: boolean;
}

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const userList = ref<UserVO[]>([]);

// 对话框控制
const userDialogVisible = ref(false);
const bindDeptRoleDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的用户
const currentUser = ref<SysUser & { realName?: string; nickname?: string }>({});

// 绑定相关数据
const bindList = ref<DeptRoleBindItem[]>([]);
const selectedBindings = ref<string[]>([]); // 存储选中的绑定项的唯一标识

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

// 生成唯一标识
function getBindingKey(item: DeptRoleBindItem): string {
  return `${item.deptID}_${item.roleID}`;
}

// 检查是否已选中
function isSelected(item: DeptRoleBindItem): boolean {
  return selectedBindings.value.includes(getBindingKey(item));
}

// 切换选择状态
function toggleSelection(item: DeptRoleBindItem) {
  const key = getBindingKey(item);
  const index = selectedBindings.value.indexOf(key);
  
  if (index > -1) {
    selectedBindings.value.splice(index, 1);
  } else {
    selectedBindings.value.push(key);
  }
}

// 加载用户列表
async function loadUserList() {
  try {
    loading.value = true;
    const result = await userApi.getUserList({id: ""});
    userList.value = result.dataList || [];
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error('加载用户列表失败');
  } finally {
    loading.value = false;
  }
}

// 加载部门和角色数据用于名称映射
async function loadDeptAndRoleData() {
  try {
    const [deptResult, roleResult] = await Promise.all([
      deptApi.getAllDepts(),
      roleApi.getAllRoles()
    ]);
    
    const depts = deptResult.dataList || [];
    const roles = roleResult.dataList || [];
    
    const deptMap = new Map(depts.map(d => [d.deptID, d.name || '未知部门']));
    const roleMap = new Map(roles.map(r => [r.roleID, r.name || '未知角色']));
    
    return { deptMap, roleMap };
  } catch (error) {
    console.error('加载部门角色数据失败:', error);
    return { deptMap: new Map(), roleMap: new Map() };
  }
}

// 加载部门角色绑定列表
async function loadDeptRoleList(): Promise<DeptRoleBindItem[]> {
  try {
    const [deptRoleResult, { deptMap, roleMap }] = await Promise.all([
      deptApi.getDeptRoleList({id: ""}),
      loadDeptAndRoleData()
    ]);
    
    const deptRoles = deptRoleResult.dataList || [];
    
    return deptRoles.map(item => ({
      ...item,
      deptName: deptMap.get(item.deptID || '') || `部门${item.deptID}`,
      roleName: roleMap.get(item.roleID || '') || `角色${item.roleID}`,
      isBound: false // 初始状态为未绑定，需要根据实际绑定情况设置
    }));
  } catch (error) {
    console.error('加载部门角色列表失败:', error);
    return [];
  }
}


// 新增用户
function handleAdd() {
  isEdit.value = false;
  currentUser.value = {};
  userDialogVisible.value = true;
}

// 编辑用户
function handleEdit(row: UserVO) {
  isEdit.value = true;
  // 将UserVO转换为SysUser
  currentUser.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    phone: row.phone,
    wechatID: row.wechatID,
    status: row.status,
    createTime: row.createTime,
    updateTime: row.updateTime,
    deleteTime: row.deleteTime,
    deleted: row.deleted,
    realName: row.realName,
    nickname: row.nickname
  };
  userDialogVisible.value = true;
}

// 删除用户
async function handleDelete(row: UserVO) {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await userApi.deleteUser(row);
    ElMessage.success('删除成功');
    await loadUserList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败');
    }
  }
}

// 保存用户
async function saveUser() {
  try {
    submitting.value = true;
    
    if (isEdit.value) {
      await userApi.updateUser(currentUser.value);
      ElMessage.success('更新成功');
    } else {
      await userApi.createUser(currentUser.value);
      ElMessage.success('创建成功');
    }
    
    userDialogVisible.value = false;
    await loadUserList();
  } catch (error) {
    console.error('保存用户失败:', error);
    ElMessage.error('保存用户失败');
  } finally {
    submitting.value = false;
  }
}

// 绑定部门角色
async function handleBindDeptRole(row: UserVO) {
  // 将UserVO转换为SysUser
  currentUser.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    phone: row.phone,
    wechatID: row.wechatID,
    status: row.status,
    createTime: row.createTime,
    updateTime: row.updateTime,
    deleteTime: row.deleteTime,
    deleted: row.deleted
  };
  
  try {
    // 加载全部部门和角色数据
    bindList.value = await loadDeptRoleList();
    
    // 加载已绑定部门角色
    const deptRoleResult = await userApi.getUserDeptRole({userID: currentUser.value.id});
    const deptRoles = deptRoleResult.dataList || [];
    
    // 初始化选中状态为已绑定的项
    selectedBindings.value = bindList.value
      .filter(item => deptRoles.some(deptRole => 
        deptRole.deptID === item.deptID && deptRole.roleID === item.roleID
      ))
      .map(item => getBindingKey(item));
    
    bindDeptRoleDialogVisible.value = true;
  } catch (error) {
    console.error('加载绑定数据失败:', error);
    ElMessage.error('加载绑定数据失败');
  }
}

// 保存绑定设置
async function saveBindings() {
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.error('用户信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的部门角色
    const currentBoundResult = await userApi.getUserDeptRole({userID: currentUser.value.id});
    const currentBoundItems = currentBoundResult.dataList || [];
    const currentBoundKeys = currentBoundItems.map(item => `${item.deptID}_${item.roleID}`);
    
    // 找出需要绑定的项（新增的）
    const itemsToBind = bindList.value.filter(item => {
      const key = getBindingKey(item);
      return selectedBindings.value.includes(key) && !currentBoundKeys.includes(key);
    });
    
    // 找出需要解绑的项（移除的）
    const itemsToUnbind = bindList.value.filter(item => {
      const key = getBindingKey(item);
      return !selectedBindings.value.includes(key) && currentBoundKeys.includes(key);
    });
    
    // 执行绑定操作 - 一次性发送所有绑定项
    if (itemsToBind.length > 0) {
      const userDeptRoleVO: UserDeptRoleVO = {
        user: currentUser.value,
        users: [currentUser.value],
        userDeptRoles: itemsToBind.map(item => ({
          deptID: item.deptID,
          roleID: item.roleID
        }))
      };
      await userApi.bindUserDeptRole(userDeptRoleVO);
    }
    
    // 执行解绑操作 - 一次性发送所有解绑项
    if (itemsToUnbind.length > 0) {
      const userDeptRoleVO: UserDeptRoleVO = {
        user: currentUser.value,
        users: [currentUser.value],
        userDeptRoles: itemsToUnbind.map(item => ({
          deptID: item.deptID,
          roleID: item.roleID
        }))
      };
      await userApi.unbindUserDeptRole(userDeptRoleVO);
    }
    
    ElMessage.success('部门角色绑定保存成功');
    bindDeptRoleDialogVisible.value = false;
    
    // 刷新用户列表
    await loadUserList();
  } catch (error) {
    console.error('保存部门角色绑定失败:', error);
    ElMessage.error('保存部门角色绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 重置表单
function resetForm() {
  currentUser.value = {};
}

// 重置绑定表单
function resetBindForm() {
  bindList.value = [];
  selectedBindings.value = [];
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserList();
});
</script>

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

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

.header h2 {
  margin: 0;
}

.bind-info {
  margin-bottom: 20px;
}

.bind-stats {
  margin-top: 20px;
}
</style>
