package io.renren.modules.sys.service.impl.alg;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.datasource.annotation.DataSource;
import io.renren.modules.sys.dao.alg.SysUserAlgDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.alg.SysRoleAlgService;
import io.renren.modules.sys.service.alg.SysUserAlgService;
import io.renren.modules.sys.service.alg.SysUserRoleAlgService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("sysUserAlgService")
@DataSource("alg")
public class SysUserAlgServiceImpl extends ServiceImpl<SysUserAlgDao, SysUserEntity> implements SysUserAlgService {
    @Autowired
    private SysUserRoleAlgService sysUserRoleAlgService;
    @Autowired
    private SysRoleAlgService sysRoleAlgService;

    @Override
    @Transactional
    public void saveUser(SysUserEntity user,String salt, String password) {
        user.setCreateTime(new Date());
        //sha256加密
        //String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(password);
        user.setSalt(salt);
        this.save(user);

        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleAlgService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }


    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user){
        if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if(user.getCreateUserId() == Constant.SUPER_ADMIN){
            return ;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleAlgService.queryRoleByIdList(user.getCreateUserId());

        //判断是否越权
        if(!roleIdList.containsAll(user.getRoleIdList())){
            throw new RRException("新增用户所选角色，不是本人创建");
        }
    }



}
