<template>
  <div class="dept-manage">
    <div class="header">
      <h2>部门管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </div>

    <el-table 
      :data="deptList" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
      row-key="deptID"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="部门名称" min-width="200" />
      <el-table-column prop="deptID" label="部门ID" min-width="150" />
      <el-table-column prop="description" label="部门描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="creatorName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleAddChild(row)"
            link
          >
            新增子部门
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEdit(row)"
            link
          >
            编辑
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleBindRole(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="dialogVisible" 
      :title="isEdit ? '编辑部门' : '新增部门'"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="父部门" prop="parentID">
          <el-cascader
            v-model="formData.parentID"
            :options="parentDeptOptions"
            :props="cascaderProps"
            placeholder="请选择父部门"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input 
            v-model="formData.name" 
            placeholder="请输入部门名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="submitting"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定角色对话框 -->
    <el-dialog v-model="bindRoleDialogVisible" title="绑定角色" width="800px" @close="resetBindList">
      <div class="role-binding-container">
        <!-- 部门信息显示 -->
        <div class="dept-info" v-if="currentDept">
          <h4>部门信息：{{ currentDept.name }}</h4>
          <p>部门ID：{{ currentDept.deptID }}</p>
        </div>
        
        <!-- 角色绑定状态表格 -->
        <el-table :data="roleList" style="width: 100%" border stripe>
          <el-table-column width="80" label="绑定状态">
            <template #default="{ row }">
              <el-tag 
                :type="isRoleSelected(row.roleID) ? 'success' : 'info'"
                size="small"
              >
                {{ isRoleSelected(row.roleID) ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="角色名称" min-width="150" />
          <el-table-column prop="roleID" label="角色ID" min-width="120" />
          <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button 
                :type="isRoleSelected(row.roleID) ? 'danger' : 'primary'"
                size="small"
                @click="toggleRoleSelection(row)"
              >
                {{ isRoleSelected(row.roleID) ? '解绑' : '绑定' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 统计信息 -->
        <div class="binding-stats">
          <el-alert 
            :title="`已绑定 ${selectedRoles.length} 个角色，未绑定 ${roleList.length - selectedRoles.length} 个角色`"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="bindRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRoleBinding" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { deptApi } from '@/apis/system/dept';
import { roleApi } from '@/apis/system/role';
import { SysDept, SysRole } from '@/types';
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 数据状态
const deptList = ref<SysDept[]>([]);
const loading = ref(false);
const submitting = ref(false);

// 角色绑定相关数据
const roleList = ref<SysRole[]>([]);
const selectedRoles = ref<string[]>([]);
const currentDept = ref<SysDept | null>(null);
const bindList = ref<{ roles: SysRole[] }>({
  roles: []
});

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

// 表单数据
const formData = reactive<SysDept>({
  name: '',
  description: '',
  parentID: undefined
});

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '部门描述不能超过 200 个字符', trigger: 'blur' }
  ]
};

// 级联选择器配置
const cascaderProps = {
  value: 'deptID',
  label: 'name',
  children: 'children',
  checkStrictly: true
};

// 父部门选项
const parentDeptOptions = computed(() => {
  return buildParentDeptOptions(deptList.value);
});

// 构建父部门选项
function buildParentDeptOptions(depts: SysDept[]): any[] {
  return depts.map(dept => ({
    deptID: dept.deptID,
    name: dept.name,
    children: dept.children ? buildParentDeptOptions(dept.children) : undefined
  }));
}

// 加载部门列表
async function loadDeptList() {
  try {
    loading.value = true;
    deptList.value = await deptApi.getAllDepts();
  } catch (error) {
    console.error('加载部门列表失败:', error);
    ElMessage.error('加载部门列表失败');
  } finally {
    loading.value = false;
  }
}

// 新增部门
function handleAdd() {
  isEdit.value = false;
  formData.parentID = undefined;
  dialogVisible.value = true;
}

// 新增子部门
function handleAddChild(row: SysDept) {
  isEdit.value = false;
  formData.parentID = row.deptID;
  dialogVisible.value = true;
}

// 编辑部门
function handleEdit(row: SysDept) {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
}

// 删除部门
async function handleDelete(row: SysDept) {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await deptApi.deleteDept(row);
    ElMessage.success('删除成功');
    await loadDeptList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除部门失败:', error);
      ElMessage.error('删除部门失败');
    }
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    if (isEdit.value) {
      await deptApi.updateDept(formData);
      ElMessage.success('更新成功');
    } else {
      await deptApi.createDept(formData);
      ElMessage.success('新增成功');
    }
    
    dialogVisible.value = false;
    await loadDeptList();
  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      console.error('提交失败:', error);
      ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    }
  } finally {
    submitting.value = false;
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    name: '',
    description: '',
    parentID: undefined
  });
}

// 查看绑定角色
async function handleBindRole(row: SysDept) {
  currentDept.value = row;
  
  try {
    // 获取所有角色
    roleList.value = await roleApi.getAllRoles();
    
    // 获取已绑定的角色
    const bindingResult = await deptApi.getDeptByRole(row);
    bindList.value.roles = bindingResult || [];
    
    // 设置已选中的角色
    selectedRoles.value = bindList.value.roles.map(role => role.roleID).filter((id): id is string => !!id);
    
    console.log('已绑定的角色:', bindList.value.roles);
    console.log('所有角色:', roleList.value);
    bindRoleDialogVisible.value = true;
  } catch (error) {
    console.error('获取角色绑定信息失败:', error);
    ElMessage.error('获取角色绑定信息失败');
  }
}

// 重置绑定列表
function resetBindList() {
  bindList.value = {
    roles: []
  };
  selectedRoles.value = [];
  currentDept.value = null;
}

// 检查角色是否已选中
function isRoleSelected(roleID: string | undefined): boolean {
  return roleID ? selectedRoles.value.includes(roleID) : false;
}

// 切换角色选择状态
function toggleRoleSelection(role: SysRole) {
  if (!role.roleID) return;
  
  const index = selectedRoles.value.indexOf(role.roleID);
  if (index > -1) {
    selectedRoles.value.splice(index, 1);
  } else {
    selectedRoles.value.push(role.roleID);
  }
}

// 保存角色绑定
async function saveRoleBinding() {
  if (!currentDept.value || !currentDept.value.deptID) {
    ElMessage.error('部门信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的角色ID
    const currentBoundRoles = (bindList.value.roles || []).map(role => role.roleID).filter((id): id is string => !!id);
    
    // 找出需要绑定的角色（新增的）
    const rolesToBind = selectedRoles.value.filter(roleID => !currentBoundRoles.includes(roleID));
    
    // 找出需要解绑的角色（移除的）
    const rolesToUnbind = currentBoundRoles.filter(roleID => !selectedRoles.value.includes(roleID));
    
    // 构建需要绑定的角色对象数组
    if (rolesToBind.length > 0) {
      const rolesToBindObjects = rolesToBind.map(roleID => {
        const role = roleList.value.find(r => r.roleID === roleID);
        return role || { roleID: roleID };
      });
      
      const bindDept = {
        dept: currentDept.value,
        depts: [{deptID: currentDept.value.deptID}],
        roles: rolesToBindObjects,
      };
      await deptApi.bindDeptRole(bindDept);
    }
    
    // 构建需要解绑的角色对象数组
    if (rolesToUnbind.length > 0) {
      const rolesToUnbindObjects = rolesToUnbind.map(roleID => {
        const role = roleList.value.find(r => r.roleID === roleID);
        return role || { roleID: roleID };
      });
      
      const unbindDept = {
        dept: currentDept.value,
        roles: rolesToUnbindObjects,
        depts: [{deptID: currentDept.value.deptID}]
      };
      await deptApi.unbindDeptRole(unbindDept);
    }
    
    ElMessage.success('角色绑定保存成功');
    bindRoleDialogVisible.value = false;
    
    // 刷新部门列表
    await loadDeptList();
  } catch (error) {
    console.error('保存角色绑定失败:', error);
    ElMessage.error('保存角色绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 页面加载时获取部门列表
onMounted(() => {
  loadDeptList();
});
</script>

<style scoped lang="scss">
.dept-manage {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }
  }
  
  .el-table {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #ebeef5;
  }
}

// 表单样式优化
:deep(.el-form) {
  .el-form-item__label {
    font-weight: 500;
    color: #606266;
  }
  
  .el-input__wrapper {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
  
  .el-textarea__inner {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &:focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
}

// 按钮样式优化
:deep(.el-button) {
  &.is-link {
    padding: 0;
    margin-right: 12px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

// 角色绑定容器样式
.role-binding-container {
  .dept-info {
    background: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 16px;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .binding-stats {
    margin-top: 20px;
  }
}
</style>