package com.hs.api.service.Impl;

import com.hs.api.mapper.SysMenuMapper;
import com.hs.api.model.SysMenu;
import com.hs.api.model.respmodel.SysMenuList;
import com.hs.api.service.SysMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenuList> getMenu(Long userId) throws Exception {
        SysMenuList sysMenuList = new SysMenuList();
        SysMenu sysMenu = new SysMenu();
        List<SysMenuList> list = sysMenuMapper.selectMenuByUser(userId);
        List<SysMenuList> resultList  = getLevelData(list, Long.valueOf(MENU_TOP_PARENT_ID));
        resultList=resultList.stream().sorted(Comparator.comparing(SysMenu::getSort)).collect(Collectors.toList());
        return resultList;
    }

    private List<SysMenuList> getLevelData(List<SysMenuList> list, Long parentcode) {
        List<SysMenuList> resultList = new ArrayList<>();
        for (SysMenuList data : list) {
           if (data.getParentId() == parentcode){
               List<SysMenuList> childList = getLevelData(list,data.getId());
               childList=childList.stream().sorted(Comparator.comparing(SysMenu::getSort)).collect(Collectors.toList());
               data.setSysMenuList(childList);
               resultList.add(data);
           }
        }
        return resultList;
    }

    @Override
    public int add(SysMenu sysMenu) {
        return sysMenuMapper.insert(sysMenu);
    }

    @Override
    public List<SysMenu> findAll() {
        return sysMenuMapper.selectAll();
    }

    @Override
    public SysMenu find(Long id) {
        return sysMenuMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(Long id) {
        return sysMenuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int logicDelete(Long id) {
        return 0;
    }

    @Override
    public int update(SysMenu sysMenu) {
        return sysMenuMapper.updateByPrimaryKey(sysMenu);
    }
}
