package com.sky.ioc.service.system.impl;

import com.sky.ioc.entity.domain.system.Menus;
import com.sky.ioc.entity.domain.system.Users;
import com.sky.ioc.mapper.system.MenuMapper;
import com.sky.ioc.mapper.system.UserMapper;
import com.sky.ioc.service.system.MenuService;
import com.sky.ioc.tool.ReturnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    UserMapper userMapper;


    @Override
    public ReturnMsg getMenusInfoList(long parentId) {
        List<Menus> lists = menuMapper.getList();
        return  ReturnMsg.ok(listWithTree(lists,parentId));
    }

    @Override
    public List<Menus> listWithTree(List<Menus> list,long parentId) {
        List<Menus> result = new ArrayList<>();
        for (Menus Menus : list) {
            if (Menus.getParentId()==parentId) {
                result.add(Menus);
            }
            for (Menus child : list) {
                if (child.getParentId().equals(Menus.getId())) {
                    List<Menus> children = Menus.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        Menus.setChildren(children);
                    }
                    children.add(child);
                }
            }
        }
        return result;
     }

    @Override
    public ReturnMsg listByUserId(Integer userId) {
        Users users = userMapper.getUsersById(userId);
        if(users!=null){
            List<Integer> ids = new ArrayList<>();
            if(users.getCommonMenus()!=null&&!users.getCommonMenus().isEmpty()){
               List<String> lists = Arrays.stream(users.getCommonMenus().split(",")).collect(Collectors.toList());
               for(String id:lists){
                   ids.add(Integer.parseInt(id));
               }
                List<Menus> menus =  menuMapper.getListByIds(ids);
                return ReturnMsg.ok(menus);
            }else{
                return ReturnMsg.ok();
            }

        }else{
            return ReturnMsg.fail("用户不存在");
        }
    }
}





