package com.tofly.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.dto.ShorcutMenuDto;
import com.tofly.base.entity.UserShortMenu;
import com.tofly.base.mapper.ShortcutMenuMapper;
import com.tofly.base.service.ShortcutMenuService;
import com.tofly.common.oauth.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class ShortcutMenuServiceImpl extends ServiceImpl<ShortcutMenuMapper, UserShortMenu>
        implements ShortcutMenuService {

    @Override
    public List<UserShortMenu> menuList(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return new ArrayList<>();
        }

        LambdaQueryWrapper<UserShortMenu> wrapper = Wrappers.<UserShortMenu>lambdaQuery()
                .eq(UserShortMenu::getUserId, userId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void saveMenu(ShorcutMenuDto shorcutMenuDto) {
        UserShortMenu userShortMenu = BeanUtil.copyProperties(shorcutMenuDto, UserShortMenu.class);
        Long userId = SecurityUtils.getUserId();
        userShortMenu.setUserId(userId);

        Integer sort = shorcutMenuDto.getSort();
        if (ObjectUtil.isNull(sort)) {
            userShortMenu.setSort(0);
        }

        Date now = new Date();
        userShortMenu.setCreatedTime(now);
        userShortMenu.setUpdatedTime(now);

        userShortMenu.setId(baseMapper.selectNextId());
        save(userShortMenu);
    }

}
