/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.entity.UserRole;
import com.tofly.base.mapper.UserRoleMapper;
import com.tofly.base.service.UserRoleService;
import com.tofly.common.core.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户角色表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserRole(Long userid, String roles) {
        //首先删除用户角色。
        remove(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId,userid));
        //然后再新增用户角色
        if(!StringUtil.isEmpty(roles)){
            List<UserRole> list=new ArrayList<>();
            String[] role=roles.split(",");
            UserRole userRole;
            for(String s:role){
                userRole=new UserRole();
                userRole.setUserId(userid);
                userRole.setRoleId(Long.valueOf(s));
                save(userRole);
                //list.add(userRole);
            }
           // saveBatch(list);
        }
        return true;
    }

    @Override
    public List<UserRole> getTreeMenuByUser(Long id) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_ID",id);
        List<UserRole> userRoles = baseMapper.selectList(wrapper);
        return userRoles;
    }


}
