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

    <el-table 
      :data="roleList" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
    >
      <el-table-column prop="name" label="角色名称" min-width="200" />
      <el-table-column prop="roleID" 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="handleEdit(row)"
            link
          >
            编辑
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleBindPermission(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="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="bindPermissionDialogVisible" title="绑定权限" width="800px" @close="resetBindList">
      <div class="permission-binding-container">
        <!-- 角色信息显示 -->
        <div class="role-info" v-if="currentRole">
          <h4>角色信息：{{ currentRole.name }}</h4>
          <p>角色ID：{{ currentRole.roleID }}</p>
        </div>
        
        <!-- 权限绑定状态表格 -->
        <el-table :data="permissionList" style="width: 100%" border stripe>
          <el-table-column width="80" label="绑定状态">
            <template #default="{ row }">
              <el-tag 
                :type="isPermissionSelected(row.permissionID) ? 'success' : 'info'"
                size="small"
              >
                {{ isPermissionSelected(row.permissionID) ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="权限名称" min-width="150" />
          <el-table-column prop="permissionID" label="权限ID" min-width="120" />
          <el-table-column prop="code" label="权限编码" min-width="150" />
          <el-table-column prop="description" label="权限描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button 
                :type="isPermissionSelected(row.permissionID) ? 'danger' : 'primary'"
                size="small"
                @click="togglePermissionSelection(row)"
              >
                {{ isPermissionSelected(row.permissionID) ? '解绑' : '绑定' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 统计信息 -->
        <div class="binding-stats">
          <el-alert 
            :title="`已绑定 ${selectedPermissions.length} 个权限，未绑定 ${permissionList.length - selectedPermissions.length} 个权限`"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="bindPermissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissionBinding" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

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

// 权限绑定相关数据
const permissionList = ref<SysPermission[]>([]);
const selectedPermissions = ref<string[]>([]);
const currentRole = ref<SysRole | null>(null);
const bindList = ref<{ permissions: SysPermission[] }>({
  permissions: []
});

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

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

// 表单验证规则
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' }
  ]
};

// 加载角色列表
async function loadRoleList() {
  try {
    loading.value = true;
    const result = await roleApi.getAllRoles();
    roleList.value = result.dataList || [];
  } catch (error) {
    console.error('加载角色列表失败:', error);
    ElMessage.error('加载角色列表失败');
  } finally {
    loading.value = false;
  }
}

// 新增角色
function handleAdd() {
  isEdit.value = false;
  dialogVisible.value = true;
}

// 编辑角色
function handleEdit(row: SysRole) {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
}

// 删除角色
async function handleDelete(row: SysRole) {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await roleApi.deleteRole(row);
    ElMessage.success('删除成功');
    await loadRoleList();
  } 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 roleApi.updateRole(formData);
      ElMessage.success('更新成功');
    } else {
      await roleApi.createRole(formData);
      ElMessage.success('新增成功');
    }
    
    dialogVisible.value = false;
    await loadRoleList();
  } 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: ''
  });
}

// 查看绑定权限
async function handleBindPermission(row: SysRole) {
  currentRole.value = row;
  
  try {
    // 获取所有权限
    let permission: SysPermission = {
      permissionID: undefined,
      name: undefined,
      code: undefined,
      description: undefined,
    };
    const permissionResult = await permissionApi.getPermissionList(permission);
    permissionList.value = permissionResult.dataList || [];
    
    // 获取已绑定的权限
    const bindingResult = await roleApi.getRolePermission({
      roleID: row.roleID
    });
    console.log('已绑定的权限:', bindingResult);
    bindList.value.permissions = bindingResult.dataList || [];
    
    // 设置已选中的权限
    selectedPermissions.value = bindList.value.permissions.map(permission => permission.permissionID).filter((id): id is string => !!id);
    
    console.log('已绑定的权限:', bindList.value.permissions);
    console.log('所有权限:', permissionList.value);
    bindPermissionDialogVisible.value = true;
  } catch (error) {
    console.error('获取权限绑定信息失败:', error);
    ElMessage.error('获取权限绑定信息失败');
  }
}

// 重置绑定列表
function resetBindList() {
  bindList.value = {
    permissions: []
  };
  selectedPermissions.value = [];
  currentRole.value = null;
}

// 检查权限是否已选中
function isPermissionSelected(permissionID: string | undefined): boolean {
  return permissionID ? selectedPermissions.value.includes(permissionID) : false;
}

// 切换权限选择状态
function togglePermissionSelection(permission: SysPermission) {
  if (!permission.permissionID) return;
  
  const index = selectedPermissions.value.indexOf(permission.permissionID);
  if (index > -1) {
    selectedPermissions.value.splice(index, 1);
  } else {
    selectedPermissions.value.push(permission.permissionID);
  }
}

// 保存权限绑定
async function savePermissionBinding() {
  if (!currentRole.value || !currentRole.value.roleID) {
    ElMessage.error('角色信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的权限ID
    const currentBoundPermissions = (bindList.value.permissions || []).map(permission => permission.permissionID).filter((id): id is string => !!id);
    
    // 找出需要绑定的权限（新增的）
    const permissionsToBind = selectedPermissions.value.filter(permissionID => !currentBoundPermissions.includes(permissionID));
    
    // 找出需要解绑的权限（移除的）
    const permissionsToUnbind = currentBoundPermissions.filter(permissionID => !selectedPermissions.value.includes(permissionID));
    
    // 构建需要绑定的权限对象数组
    if (permissionsToBind.length > 0) {
      const permissionsToBindObjects = permissionsToBind.map(permissionID => {
        const permission = permissionList.value.find(p => p.permissionID === permissionID);
        return permission || { permissionID: permissionID };
      });
      
      const bindRole = {
        ...currentRole.value,
        permissions: permissionsToBindObjects,
        roles: [{ roleID: currentRole.value.roleID }]
      };
      await permissionApi.bindRole(bindRole);
    }
    
    // 构建需要解绑的权限对象数组
    if (permissionsToUnbind.length > 0) {
      const permissionsToUnbindObjects = permissionsToUnbind.map(permissionID => {
        const permission = permissionList.value.find(p => p.permissionID === permissionID);
        return permission || { permissionID: permissionID };
      });
      
      const unbindRole = {
        ...currentRole.value,
        permissions: permissionsToUnbindObjects,
        roles: [{ roleID: currentRole.value.roleID }]
      };
      await permissionApi.unbindRole(unbindRole);
    }
    
    ElMessage.success('权限绑定保存成功');
    bindPermissionDialogVisible.value = false;
    
    // 刷新角色列表
    await loadRoleList();
  } catch (error) {
    console.error('保存权限绑定失败:', error);
    ElMessage.error('保存权限绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 页面加载时获取角色列表
onMounted(() => {
  loadRoleList();
});
</script>

<style scoped lang="scss">
.role-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;
    }
  }
}

// 权限绑定容器样式
.permission-binding-container {
  .role-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>