package com.cool.bang.modules.system.service.impl;

import com.cool.bang.common.base.BaseServiceImpl;
import com.cool.bang.modules.system.domain.po.Menu;
import com.cool.bang.modules.system.domain.po.User;
import com.cool.bang.modules.system.mapper.UserAndRoleMapper;
import com.cool.bang.modules.system.mapper.UserMapper;
import com.cool.bang.modules.system.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * system user service implementation class
 *
 * @author GuoPeiZhi
 * 2021-2-20 10:33
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserAndRoleMapper userAndRoleMapper;

    @Override
    public boolean save(User user) {
        user.insertConfigure();
        int count = baseMapper.insert(user);
        if (!CollectionUtils.isEmpty(user.getRoleList())) {
            userAndRoleMapper.insertUserIdAndRoles(user.getId(), user.getRoleList());
        }
        return count > 0;
    }

    @Override
    public boolean update(User user) {
        user.updateConfigure();
        int count = baseMapper.update(user);
        if (!CollectionUtils.isEmpty(user.getRoleList())) {
            userAndRoleMapper.deleteByUserId(user.getId());
            userAndRoleMapper.insertUserIdAndRoles(user.getId(), user.getRoleList());
        }
        return count > 0;
    }

    @Override
    public boolean removeById(Serializable id) {
        User user = new User();
        user.setId((Long) id);
        user.setEnable(true);
        user.setDelFlag(false);
        int count = baseMapper.update(user);
        userAndRoleMapper.deleteByUserId((Long) id);
        return count > 0;
    }

    @Override
    public List<Menu> toUserMenu(List<Menu> sysMenus, Long parentId) {
        List<Menu> list = new ArrayList<>();
        for (Menu menu : sysMenus) {
            if (parentId.equals(menu.getParentId())) {
                menu.setChildren(toUserMenu(sysMenus, menu.getId()));
                list.add(menu);
            }
        }
        return list;
    }

    @Override
    public User queryByOpenid(String openid) {
        return baseMapper.selectByOpenid(openid);
    }

    @Override
    public User queryByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }

    @Override
    public boolean usernameUniqueCheck(String username, Long id) {
        return baseMapper.usernameUniqueCheck(username, id) > 0;
    }

    @Override
    public boolean updateEnable(Long id, boolean enable) {
        return baseMapper.updateEnable(id, enable) > 0;
    }


}
