package com.hotent.portal.persistence.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.exception.BaseException;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.util.BeanUtils;
import com.hotent.portal.model.MenuBookmark;
import com.hotent.portal.persistence.dao.MenuBookmarkDao;
import com.hotent.portal.persistence.manager.MenuBookmarkManager;
import com.hotent.sys.persistence.manager.SysMenuManager;
import com.hotent.sys.persistence.model.SysMenu;
import com.hotent.uc.api.impl.util.ContextUtil;
import org.springframework.stereotype.Service;

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

/**
 * 菜单收藏 服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author zengst
 * @since 2021-06-21
 */
@Service
public class MenuBookmarkManagerImpl extends BaseManagerImpl<MenuBookmarkDao, MenuBookmark> implements MenuBookmarkManager {

    @Resource
    SysMenuManager sysMenuManager;

    @Override
    public String handleBookmarkChange(String menuId, String currentUserId) {
        String message = null;
        List<MenuBookmark> bmk = this.getByMenuIdAndUserId(menuId, currentUserId);
        if (BeanUtils.isNotEmpty(bmk)) {
            //取消收藏
            QueryWrapper<MenuBookmark> qw = new QueryWrapper<>();
            qw.eq("USER_ID_", currentUserId);
            qw.eq("MENU_ID_", menuId);
            this.remove(qw);
            message = "取消收藏成功";
        }else{
            //收藏
            SysMenu menu = sysMenuManager.getByIdAndTenant(menuId, "-1");
            if (BeanUtils.isEmpty(menu)) {
                throw new BaseException("菜单不存在");
            }
            MenuBookmark mb = new MenuBookmark();
            mb.setAlias(menu.getAlias());
            mb.setMenuId(menuId);
            mb.setParentMenuId(menu.getParentId());
            mb.setHref(menu.getHref());
            mb.setUserId(currentUserId);
            mb.setName(menu.getName());
            this.create(mb);
            message = "收藏成功";
        }
        return message;
    }

    @Override
    public void removeBookmarkByMenuIds(List<String> menuIds) {
        QueryWrapper<MenuBookmark> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_ID_", ContextUtil.getCurrentUserId()).in("MENU_ID_", menuIds);
        this.remove(queryWrapper);
    }

    private List<MenuBookmark> getByMenuIdAndUserId(String menuId, String userId) {
        QueryWrapper<MenuBookmark> qw = new QueryWrapper<>();
        qw.eq("MENU_ID_", menuId).eq("USER_ID_", userId);
        return this.list(qw);
    }
}
