package cn.sh.stc.sict.cloud.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.sh.stc.sict.cloud.upms.model.HpRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;

import cn.sh.stc.sict.cloud.upms.dao.HpUserRoleMapper;
import cn.sh.stc.sict.cloud.upms.model.HpUserRole;
import cn.sh.stc.sict.cloud.upms.service.HpUserRoleService;
import org.springframework.transaction.annotation.Transactional;

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


@Service("hpUserRoleService")
@AllArgsConstructor
public class HpUserRoleServiceImpl extends ServiceImpl<HpUserRoleMapper, HpUserRole> implements HpUserRoleService {

    private final HpUserRoleMapper hpUserRoleMapper;

    @Override
    public boolean exist(Long roleId) {
        LambdaQueryWrapper<HpUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HpUserRole::getRoleId, roleId);
        return this.count(wrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(Long userId, List<HpRole> roleList) {
        this.removeByUserId(userId);
        if (CollUtil.isNotEmpty(roleList)) {
            List<HpUserRole> list = new ArrayList<>();
            roleList.forEach(r -> {
                HpUserRole ur = new HpUserRole();
                ur.setUserId(userId);
                ur.setRoleId(r.getId());
                list.add(ur);
            });
            this.saveBatch(list);
        }
        return true;
    }

    @Override
    public boolean removeByUserId(Long userId) {
        LambdaQueryWrapper<HpUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HpUserRole::getUserId, userId);
        return this.remove(wrapper);
    }
}
