package org.moxianchengbao.controller;

import org.moxianchengbao.mapper.MenuMapper;
import org.moxianchengbao.pojo.entity.Menu;
import org.moxianchengbao.resultR.R;
import org.moxianchengbao.service.impl.MenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author moxianchengbao
 * @Date 2023/8/4 15:31
 */

@RestController
@RequestMapping("/menu")
public class menuController {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuServiceImpl menuService;



    @GetMapping("/menuAll")
    public R menuAll(){
        List<Menu> list = menuService.list();
        List<Menu> parNode = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());
        for( Menu it : parNode){
            it.setChildren(list.stream().filter(m->it.getId().equals(m.getPid())).collect(Collectors.toList()));
        }

        return R.SUCCESS(parNode);
    }


    @PostMapping("/save")
    public R menuSave(@RequestBody Menu item){

        if(menuService.saveOrUpdate(item)){
            return R.SUCCESS();
        }else {
            return R.FAIL();
        }
    }


    @DeleteMapping("/del/{id}")
    public R menuDelete(@PathVariable Integer id){
        if(menuMapper.deleteById(id)==1){
            return R.SUCCESS();
        }else{
            return R.FAIL();
        }
    }


    @PostMapping("/batch/del")
    public R menuBatchDelete(@RequestBody List<Integer> ids){
        int len = ids.size();
        if(menuMapper.deleteBatchIds(ids)==len){
            return R.SUCCESS();
        }else {
            return R.FAIL();
        }
    }

}