package org.xyzh.system.service.permission.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xyzh.api.system.permission.ResourcePermissionService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.dto.dept.TbSysDeptRole;
import org.xyzh.common.dto.permission.TbResourcePermission;
import org.xyzh.common.vo.UserDeptRoleVO;
import org.xyzh.system.mapper.DeptRoleMapper;
import org.xyzh.system.mapper.ResourcePermissionMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description 资源权限控制服务实现类
 * @filename SysResourcePermissionServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-29
 */
@Service
public class SysResourcePermissionServiceImpl implements ResourcePermissionService {

    private static final Logger logger = LoggerFactory.getLogger(SysResourcePermissionServiceImpl.class);

    @Autowired
    private ResourcePermissionMapper resourcePermissionMapper;

    @Autowired
    private DeptRoleMapper deptRoleMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultDomain<TbResourcePermission> createResourcePermission(Integer resource_type, String resource_id,
        UserDeptRoleVO userDeptRole) {
      ResultDomain<TbResourcePermission> resultDomain = new ResultDomain<>();
      
      Set<TbResourcePermission> resourcePermissions = new HashSet<>();
      Date now = new Date();
      
      // 判断是否为root_department的superadmin
      if (isRootSuperAdmin(userDeptRole)) {
        // root_department的superadmin创建资源：创建全局读权限
        logger.info("用户为root_department的superadmin，创建全局读权限，所有用户（包括未来新增的部门/角色）都能访问");
        
        // 1. 创建全局读权限（所有人可读，包括未来新增的部门/角色）
        TbResourcePermission globalReadPermission = createGlobalReadPermission(resource_type, resource_id, userDeptRole.getUserID());
        globalReadPermission.setCreateTime(now);
        resourcePermissions.add(globalReadPermission);
        
        // 2. 为superadmin创建全权限（读写执行）
        TbResourcePermission superAdminPermission = createSuperAdminPermission(resource_type, resource_id, userDeptRole.getUserID());
        superAdminPermission.setCreateTime(now);
        resourcePermissions.add(superAdminPermission);
        
      } else {
        // 普通用户创建资源：为父部门管理员+当前部门创建权限
        logger.info("普通用户创建资源，为父部门管理员和当前部门创建权限（子部门通过递归查询自动继承）");
        
        // 1. 为父部门的管理员角色创建精确权限（dept + admin role）
        List<TbSysDeptRole> parentDeptRoles = deptRoleMapper.selectParentDeptAdmin(userDeptRole);
        for (TbSysDeptRole deptRole : parentDeptRoles) {
          TbResourcePermission temp = createResourcePermission(resource_type, resource_id, deptRole.getDeptID(), deptRole.getRoleID());
          temp.setCreateTime(now);
          resourcePermissions.add(temp);
        }
        
        // 2. 为当前用户所在部门创建部门级权限（dept + NULL）
        //    所有角色都能访问（包括未来新增的角色）
        //    所有子部门都能访问（包括未来新增的子部门，通过查询时递归实现）
        TbResourcePermission deptPermission = createDeptLevelPermission(resource_type, resource_id, userDeptRole.getDeptID());
        deptPermission.setCreateTime(now);
        resourcePermissions.add(deptPermission);
        
        // 3. 为superadmin创建全权限（确保超级管理员始终可以管理所有资源）
        TbResourcePermission superAdminPermission = createSuperAdminPermission(resource_type, resource_id, userDeptRole.getUserID());
        superAdminPermission.setCreateTime(now);
        resourcePermissions.add(superAdminPermission);
      }

      List<TbResourcePermission> resourcePermissionsList = new ArrayList<>(resourcePermissions);
      int result = resourcePermissionMapper.batchInsertResourcePermission(resourcePermissionsList);
      if (result > 0) {
        resultDomain.success("创建资源权限成功", resourcePermissionsList);
        return resultDomain;
      } else {
        resultDomain.fail("创建资源权限失败");
        return resultDomain;
      }
      
    }
    
    /**
     * 判断是否为root_department的superadmin
     */
    private boolean isRootSuperAdmin(UserDeptRoleVO userDeptRole) {
        return "root_department".equals(userDeptRole.getDeptID()) 
            && "superadmin".equals(userDeptRole.getRoleID());
    }

    /**
     * 创建全局读权限（所有人可读，包括未来新增的部门/角色）
     */
    private TbResourcePermission createGlobalReadPermission(Integer resource_type, String resource_id, String creatorID) {
        TbResourcePermission resourcePermission = new TbResourcePermission();
        resourcePermission.setResourceType(resource_type);
        resourcePermission.setResourceID(resource_id);
        resourcePermission.setCreator(creatorID);
        resourcePermission.setDeptID(null);  // NULL表示不限制部门
        resourcePermission.setRoleID(null);  // NULL表示不限制角色
        resourcePermission.setCanRead(true);
        resourcePermission.setCanWrite(false);
        resourcePermission.setCanExecute(false);
        return resourcePermission;
    }

    /**
     * 创建精确部门角色权限（dept + role，读权限）
     */
    private TbResourcePermission createResourcePermission(Integer resource_type, String resource_id, String deptID, String roleID) {
        TbResourcePermission resourcePermission = new TbResourcePermission();
        resourcePermission.setResourceType(resource_type);
        resourcePermission.setResourceID(resource_id);
        resourcePermission.setDeptID(deptID);
        resourcePermission.setRoleID(roleID);
        resourcePermission.setCanRead(true);
        resourcePermission.setCanWrite(false);
        resourcePermission.setCanExecute(false);
        return resourcePermission;
    }
    
    /**
     * 创建部门级权限（dept + NULL，该部门所有角色可读，包括未来新增的角色）
     */
    private TbResourcePermission createDeptLevelPermission(Integer resource_type, String resource_id, String deptID) {
        TbResourcePermission resourcePermission = new TbResourcePermission();
        resourcePermission.setResourceType(resource_type);
        resourcePermission.setResourceID(resource_id);
        resourcePermission.setDeptID(deptID);
        resourcePermission.setRoleID(null);  // NULL表示该部门所有角色都能访问
        resourcePermission.setCanRead(true);
        resourcePermission.setCanWrite(false);
        resourcePermission.setCanExecute(false);
        return resourcePermission;
    }

    /**
     * 创建超级管理员全权限（读写执行）
     */
    private TbResourcePermission createSuperAdminPermission(Integer resource_type, String resource_id, String creatorID) {
        TbResourcePermission resourcePermission = new TbResourcePermission();
        resourcePermission.setResourceType(resource_type);
        resourcePermission.setResourceID(resource_id);
        resourcePermission.setCreator(creatorID);
        resourcePermission.setDeptID("root_department");
        resourcePermission.setRoleID("superadmin");
        resourcePermission.setCanRead(true);
        resourcePermission.setCanWrite(true);
        resourcePermission.setCanExecute(true);
        return resourcePermission;
    }

    
}

