package com.sunyard.ssp.modules.user.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunyard.chsm.constant.ParamConfKeyConstant;
import com.sunyard.chsm.mapper.ParamConfMapper;
import com.sunyard.chsm.model.entity.ParamConf;
import com.sunyard.ssp.modules.user.entity.ScPermission;
import com.sunyard.ssp.modules.user.mapper.ScPermissionMapper;
import com.sunyard.ssp.modules.user.service.IScPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.sunyard.chsm.constant.ParamConfKeyConstant.SYS_DEBUG_SWITCH;
import static com.sunyard.ssp.common.constant.CommonConstant.DEFAULT_USER_ROOT_ID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tsz
 * @since 2020-03-11
 */
@Slf4j
@Service
@Transactional
public class ScPermissionServiceImpl extends ServiceImpl<ScPermissionMapper, ScPermission> implements IScPermissionService {

    @Autowired
    ParamConfMapper paramConfMapper;


    @Override
    public List<ScPermission> findByTypeAndStatusOrderBySortOrder(Integer type, Integer status) {

        return baseMapper.selectList(new QueryWrapper<ScPermission>().lambda()
                .eq(ScPermission::getPType,type)
                .eq(ScPermission::getPStatus,status)
                .orderByAsc(ScPermission::getSortOrder));
    }

    @Override
    public List<ScPermission> findByUserId(Long userId) {

        List<ScPermission> permissions;

        //默认用户获取全部权限
        if(DEFAULT_USER_ROOT_ID.equals(userId)){
            permissions = baseMapper.selectList(new QueryWrapper<ScPermission>().eq("P_STATUS",0).lambda().orderByAsc(ScPermission::getSortOrder));
        }else {
            permissions = baseMapper.findByUserId(userId);
        }

        permissionFileter(permissions);

        return permissions;
    }

    public void permissionFileter(List<ScPermission> permissions){
        ParamConf sysDebugSwitchConf = paramConfMapper.selectByKey(SYS_DEBUG_SWITCH);

        if(ParamConfKeyConstant.SYS_DEBUG_SWITCH_VALUE.PRODUCT.getValue().equals(sysDebugSwitchConf.getValue())){
            Set<String> removePermissions = new HashSet<String>(){{
                    add("menu-manage");
                    add("dict-manage");
            }};

            permissions.removeIf(p -> removePermissions.contains(p.getName()));
        }

    }

    @Override
    public List<ScPermission> findByLevelOrderBySortOrder(Integer level) {


        return baseMapper.findByLevelOrderBySortOrder(level);
    }

    @Override
    public List<ScPermission> findByParentIdOrderBySortOrder(Long parentId) {


        return baseMapper.findByParentIdOrderBySortOrder(parentId);
    }
}
