package com.ycwl.basic.service.pc.impl;

import com.ycwl.basic.mapper.MenuMapper;
import com.ycwl.basic.model.pc.menu.MenuNode;
import com.ycwl.basic.model.pc.menu.entity.MenuEntity;
import com.ycwl.basic.service.pc.MenuService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Author：longbinbin
 * @Date：2024/12/3 10:16
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ApiResponse<List<MenuNode>> list(Integer type) {
//        if(type==null){
//            type=1;
//        }
        List<MenuNode> listByType = menuMapper.getListByType(type);
        List<MenuNode> MenuList = new ArrayList<>();
        for (MenuNode item :listByType) {
            if ("-1".equals(item.getParentId())) {
                MenuList.add(item);
            }
            for (MenuNode item2 : listByType) {
                if (item2.getParentId().equals(item.getId())) {
                    if (item.getChildrenList() == null) {
                        item.setChildrenList(new ArrayList<>());
                    }
                    item.getChildrenList().add(item2);
                }
            }
        }
        return ApiResponse.success(MenuList);
    }

    @Override
    public ApiResponse<Integer> add(MenuEntity menu) {
        menu.setId(SnowFlakeUtil.getId());
        int add = menuMapper.add(menu);
        if(add>0){
            return ApiResponse.success(add);
        }else {
            return ApiResponse.fail("添加失败");
        }
    }

    @Override
    public ApiResponse<Integer> update(MenuEntity menu) {
        int update = menuMapper.update(menu);
        if(update>0){
            return ApiResponse.success(update);
        }else {
            return ApiResponse.fail("更新失败");
        }
    }

    @Override
    public ApiResponse<Integer> deleteById(Long id) {
        int deleteById = menuMapper.deleteById(id);
        if(deleteById>0){
            return ApiResponse.success(deleteById);
        }else {
            return ApiResponse.fail("删除失败");
        }
    }
}
