package com.yida.data.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.system.SystemUserMenu;
import com.yida.data.system.dto.MenuForUserDTO;
import com.yida.data.system.mapper.SystemUserMenuMapper;
import com.yida.data.system.service.IMenuService;
import com.yida.data.system.service.SystemUserMenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author ccl
 */
@Slf4j
@Service("systemUserMenuService")
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class SystemUserMenuServiceImpl extends ServiceImpl<SystemUserMenuMapper, SystemUserMenu> implements SystemUserMenuService {

    @Resource
    private IMenuService menuService;

    @Override
    public void saveUserMenu(MenuForUserDTO dto) {
        List<SystemUserMenu> menus = new ArrayList<>();
        for (Long menuId : dto.getMenuId()) {
            SystemUserMenu systemUserMenu = new SystemUserMenu();
            systemUserMenu.setMenuId(menuId);
            systemUserMenu.setUserId(dto.getUserId());
            menus.add(systemUserMenu);
        }
        saveBatch(menus);
    }

    @Override
    public void updateUserMenu(MenuForUserDTO dto) {
        remove(Wrappers.lambdaQuery(new SystemUserMenu())
                .eq(SystemUserMenu::getUserId, dto.getUserId()));
        saveUserMenu(dto);
    }

    @Override
    public List<Long> findUserMenu(Long userId) {
        List<SystemUserMenu> userMenuList = list(Wrappers.lambdaQuery(new SystemUserMenu())
                .eq(SystemUserMenu::getUserId, userId));
        List<Long> menuIds = new ArrayList<>();
        for (SystemUserMenu systemUserMenu : userMenuList) {
            menuIds.add(systemUserMenu.getMenuId());
        }
        return menuIds;
    }
}
