package com.njcn.rdms.module.system.service.permission;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.annotations.VisibleForTesting;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.service.impl.DiffParseFunction;
import com.mzt.logapi.starter.annotation.LogRecord;
import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.framework.common.util.collection.CollectionUtils;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.module.system.controller.admin.permission.vo.role.RolePageReqVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.role.RoleSaveReqVO;
import com.njcn.rdms.module.system.dal.dataobject.permission.RoleDO;
import com.njcn.rdms.module.system.dal.dataobject.permission.UserRoleDO;
import com.njcn.rdms.module.system.dal.mysql.permission.RoleMapper;
import com.njcn.rdms.module.system.dal.mysql.permission.UserRoleMapper;
import com.njcn.rdms.module.system.dal.redis.RedisKeyConstants;
import com.njcn.rdms.module.system.enums.permission.PermissionScopeTypeEnum;
import com.njcn.rdms.module.system.enums.permission.RoleCodeEnum;
import com.njcn.rdms.module.system.enums.permission.RoleTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.njcn.rdms.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.njcn.rdms.framework.common.util.collection.CollectionUtils.convertMap;
import static com.njcn.rdms.module.system.enums.ErrorCodeConstants.*;
import static com.njcn.rdms.module.system.enums.LogRecordConstants.*;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    private static final String GLOBAL_SCOPE_TYPE = PermissionScopeTypeEnum.GLOBAL.getScopeType();
    private static final String OBJECT_SCOPE_TYPE = PermissionScopeTypeEnum.OBJECT.getScopeType();
    private static final String GLOBAL_OBJECT_TYPE = PermissionScopeTypeEnum.GLOBAL_OBJECT_TYPE;

    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_CREATE_SUB_TYPE, bizNo = "{{#role.id}}",
            success = SYSTEM_ROLE_CREATE_SUCCESS)
    public Long createRole(RoleSaveReqVO createReqVO, Integer type) {
        String scopeType = StrUtil.blankToDefault(StrUtil.trim(createReqVO.getScopeType()), GLOBAL_SCOPE_TYPE);
        String objectType = OBJECT_SCOPE_TYPE.equals(scopeType) ? StrUtil.trim(createReqVO.getObjectType()) : GLOBAL_OBJECT_TYPE;
        validateRoleDuplicate(createReqVO.getName(), createReqVO.getCode(), null,
                scopeType, objectType);

        RoleDO role = BeanUtils.toBean(createReqVO, RoleDO.class)
                .setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType()))
                .setStatus(ObjUtil.defaultIfNull(createReqVO.getStatus(), CommonStatusEnum.ENABLE.getStatus()))
                .setScopeType(scopeType)
                .setObjectType(objectType);
        roleMapper.insert(role);

        LogRecordContext.putVariable("role", role);
        return role.getId();
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.ROLE, key = "#updateReqVO.id")
    @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}",
            success = SYSTEM_ROLE_UPDATE_SUCCESS)
    public void updateRole(RoleSaveReqVO updateReqVO) {
        RoleDO role = validateRoleExists(updateReqVO.getId());
        String effectiveCode = shouldPreserveBuiltInCode(role) ? role.getCode() : updateReqVO.getCode();
        validateRoleDuplicate(updateReqVO.getName(), effectiveCode, updateReqVO.getId(),
                role.getScopeType(), role.getObjectType());

        //如果前端想要禁用，则去校验能否被禁用
        if (updateReqVO.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
            VerifyDoDisable(updateReqVO.getId());
        }

        RoleDO updateObj = BeanUtils.toBean(updateReqVO, RoleDO.class);
        if (shouldPreserveBuiltInCode(role)) {
            updateObj.setCode(role.getCode());
        }
        updateObj.setScopeType(role.getScopeType());
        updateObj.setObjectType(role.getObjectType());
        roleMapper.updateById(updateObj);

        LogRecordContext.putVariable(DiffParseFunction.OLD_OBJECT, BeanUtils.toBean(role, RoleSaveReqVO.class));
        LogRecordContext.putVariable("role", role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = RedisKeyConstants.ROLE, key = "#id")
    @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_DELETE_SUB_TYPE, bizNo = "{{#id}}",
            success = SYSTEM_ROLE_DELETE_SUCCESS)
    public void deleteRole(Long id) {
        RoleDO role = validateRoleForDelete(id);

        roleMapper.deleteById(id);
        permissionService.processRoleDeleted(id);

        LogRecordContext.putVariable("role", role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = RedisKeyConstants.ROLE, allEntries = true)
    public void deleteRoleList(List<Long> ids) {
        ids.forEach(this::validateRoleForDelete);

        roleMapper.deleteByIds(ids);
        ids.forEach(permissionService::processRoleDeleted);
    }

    private void VerifyDoDisable(Long id) {
        /*
            通过角色id去检查是否有用户在使用该角色（检查system_user_role表）
            1.只查deleted = 0的，即没被删除的记录
            2.无论用户是被禁用还是正常的（status = 0 | 1），只要有用户使用该角色则不能被禁用
         */
        QueryWrapper<UserRoleDO> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false)
                .eq("role_id", id);
        Long res = userRoleMapper.selectCount(wrapper);
        if (res > 0) {
            throw exception(ROLE_DISABLE_NOT_ALLOWED);
        }
    }

    @VisibleForTesting
    void validateRoleDuplicate(String name, String code, Long id) {
        validateRoleDuplicate(name, code, id, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @VisibleForTesting
    void validateRoleDuplicate(String name, String code, Long id, String scopeType, String objectType) {
        if (RoleCodeEnum.isBuiltIn(code)) {
            if (id == null) {
                throw exception(ROLE_ADMIN_CODE_ERROR, code);
            }
            RoleDO currentRole = roleMapper.selectById(id);
            if (currentRole == null || !ObjUtil.equal(currentRole.getCode(), code)) {
                throw exception(ROLE_ADMIN_CODE_ERROR, code);
            }
        }

        RoleDO role = roleMapper.selectByName(name, scopeType, objectType);
        if (role != null && !role.getId().equals(id)) {
            throw exception(ROLE_NAME_DUPLICATE, name);
        }

        if (!StringUtils.hasText(code)) {
            return;
        }
        role = roleMapper.selectByCode(code, scopeType, objectType);
        if (role != null && !role.getId().equals(id)) {
            throw exception(ROLE_CODE_DUPLICATE, code);
        }
    }

    @VisibleForTesting
    RoleDO validateRoleExists(Long id) {
        RoleDO role = roleMapper.selectById(id);
        if (role == null) {
            throw exception(ROLE_NOT_EXISTS);
        }
        return role;
    }

    @VisibleForTesting
    RoleDO validateRoleForDelete(Long id) {
        RoleDO role = validateRoleExists(id);
        if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) {
            throw exception(ROLE_CAN_NOT_DELETE_SYSTEM_TYPE_ROLE);
        }
        return role;
    }

    private boolean shouldPreserveBuiltInCode(RoleDO role) {
        return role != null
                && RoleTypeEnum.SYSTEM.getType().equals(role.getType())
                && RoleCodeEnum.isBuiltIn(role.getCode());
    }

    @Override
    public RoleDO getRole(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    public RoleDO getRole(Long roleId, String scopeType, String objectType) {
        RoleDO role = roleMapper.selectById(roleId);
        return matchesScope(role, scopeType, objectType) ? role : null;
    }

    @Override
    public RoleDO getRoleByCode(String code, String scopeType, String objectType) {
        return roleMapper.selectByCode(code, scopeType, objectType);
    }

    @Override
    @Cacheable(value = RedisKeyConstants.ROLE, key = "#id", unless = "#result == null")
    public RoleDO getRoleFromCache(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    public List<RoleDO> getRoleListByStatus(Collection<Integer> statuses) {
        return getRoleListByStatus(statuses, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public List<RoleDO> getRoleListByStatus(Collection<Integer> statuses, String scopeType, String objectType) {
        return roleMapper.selectListByStatus(statuses, scopeType, objectType);
    }

    @Override
    public List<RoleDO> getRoleList() {
        return getRoleListByStatus(null, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public List<RoleDO> getRoleList(Collection<Long> ids) {
        return getRoleList(ids, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public List<RoleDO> getRoleList(Collection<Long> ids, String scopeType, String objectType) {
        if (CollectionUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<RoleDO> roles = roleMapper.selectByIds(ids);
        roles.removeIf(role -> !matchesScope(role, scopeType, objectType));
        return roles;
    }

    @Override
    public List<RoleDO> getRoleListFromCache(Collection<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        RoleServiceImpl self = getSelf();
        return CollectionUtils.convertList(ids, self::getRoleFromCache);
    }

    @Override
    public PageResult<RoleDO> getRolePage(RolePageReqVO reqVO) {
        return getRolePage(reqVO, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public PageResult<RoleDO> getRolePage(RolePageReqVO reqVO, String scopeType, String objectType) {
        return roleMapper.selectPageByScope(reqVO, scopeType, objectType);
    }

    @Override
    public boolean hasAnySuperAdmin(Collection<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return false;
        }
        RoleServiceImpl self = getSelf();
        return ids.stream().anyMatch(id -> {
            RoleDO role = self.getRoleFromCache(id);
            return role != null && RoleCodeEnum.isSuperAdmin(role.getCode());
        });
    }

    @Override
    public void validateRoleList(Collection<Long> ids) {
        validateRoleList(ids, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public void validateRoleList(Collection<Long> ids, String scopeType, String objectType) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        List<RoleDO> roles = roleMapper.selectByIds(ids);
        Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId);
        ids.forEach(id -> {
            RoleDO role = roleMap.get(id);
            if (role == null) {
                throw exception(ROLE_NOT_EXISTS);
            }
            if (!matchesScope(role, scopeType, objectType)) {
                throw exception(ROLE_SCOPE_NOT_MATCH, role.getName());
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())) {
                throw exception(ROLE_IS_DISABLE, role.getName());
            }
        });
    }

    private boolean matchesScope(RoleDO role, String scopeType, String objectType) {
        return role != null
                && (scopeType == null || Objects.equals(scopeType, role.getScopeType()))
                && (objectType == null || Objects.equals(objectType, role.getObjectType()));
    }

    private RoleServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }

}
