package cn.hnthyy.thmz.service.impl.thmz;

import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.thmz.RoleMenuRelation;
import cn.hnthyy.thmz.entity.thmz.UserRoleRelation;
import cn.hnthyy.thmz.mapper.thmz.UserRoleRelationMapper;
import cn.hnthyy.thmz.service.thmz.UserRoleRelationService;
import cn.hnthyy.thmz.vo.UserRoleRelationVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class UserRoleRelationServiceImpl implements UserRoleRelationService {
    @SuppressWarnings("all")
    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    public List<UserRoleRelation> queryByUserId(Long userId) {
        return userRoleRelationMapper.selectByUserId(userId);
    }

    @Override
    public List<UserRoleRelation> queryByRoleId(Long roleId) {
        return userRoleRelationMapper.selectByRoleId(roleId);
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public int saveUserRoleRelation(UserRoleRelationVo userRoleRelationVo,Long createId) throws MzException {
        if (null == userRoleRelationVo.getUser().getId()) {
            throw new MzException("保存角色与用户关系失败,用户ID参数为空");
        }
        List<String> roleIds = null;
        if (userRoleRelationVo.getRoleIds() != null) {
            roleIds = Arrays.asList(userRoleRelationVo.getRoleIds().split(","));
        }
        Date now = new Date();
        userRoleRelationMapper.deleteByUserId(userRoleRelationVo.getUser().getId());
        for (String roleId : roleIds) {
            if (StringUtils.isBlank(roleId)) {
                continue;
            }
            Long roleIdL = Long.valueOf(roleId);
            UserRoleRelation newUserRoleRelation = new UserRoleRelation();
            newUserRoleRelation.setUserId(userRoleRelationVo.getUser().getId());
            newUserRoleRelation.setRoleId(roleIdL);
            newUserRoleRelation.setCreateId(createId);
            newUserRoleRelation.setCreateTime(now);
            userRoleRelationMapper.insertUserRoleRelation(newUserRoleRelation);
        }
        return 1;
    }

    @Override
    public int removeByRoleId(Long roleId) {
        return userRoleRelationMapper.deleteByRoleId(roleId);
    }

    @Override
    public int removeByUserId(Long userId) {
        return userRoleRelationMapper.deleteByUserId(userId);
    }
}
