package org.springblade.resource;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.modules.system.entity.Menu;
import org.springblade.modules.system.service.IMenuService;
import org.springblade.system.client.MenuClient;
import org.springblade.system.client.model.BladeMenuModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.LinkedList;
import java.util.List;

@ApiIgnore
@RestController
public class MenuResource implements MenuClient {

    @Autowired
    private IMenuService menuService;

    @Override
    public List<BladeMenuModel> getByTenantId(String tenantId) {
        List<Menu> list = menuService.list(Wrappers.<Menu>lambdaQuery()
                .eq(Menu::getTenantId, tenantId));
        List<BladeMenuModel> menuModels = new LinkedList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Menu menu : list) {
                BladeMenuModel menuModel = new BladeMenuModel();
                BeanUtil.copyProperties(menu,menuModel);
                menuModels.add(menuModel);
            }
        }
        return menuModels;
    }

    @Override
    public void saveList(List<BladeMenuModel> menuModels) {
        if (CollectionUtil.isNotEmpty(menuModels)) {
            List<Menu> menus = new LinkedList<>();
            for (BladeMenuModel menuModel : menuModels) {
                Menu menu = new Menu();
                BeanUtil.copyProperties(menuModel,menu);
                menus.add(menu);
            }
            menuService.saveBatch(menus);
        }
    }

    @Override
    public Long save(BladeMenuModel menuModel) {
        Menu menu = new Menu();
        BeanUtil.copyProperties(menuModel,menu);
        boolean save = menuService.save(menu);
        return menu.getId();
    }
}
