package com.sy.coinage.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.coinage.core.util.TreeUtil;
import com.sy.coinage.core.util.TreeUtil.TreeNode;
import com.sy.coinage.sys.vo.MenuPermissionVO;
import com.sy.coinage.sys.vo.UserMenusVO;
import java.util.Collection;
import java.util.List;

import org.springframework.stereotype.Service;

import com.sy.coinage.sys.dao.MenuDao;
import com.sy.coinage.sys.model.*;
import com.sy.coinage.sys.service.IMenuService;
import com.sy.coinage.sys.vo.MenuListVO;
import com.sy.coinage.core.constants.Constants;
import com.sy.coinage.core.vo.OptVO;

/**
 * 菜单ServiceImpl
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements IMenuService {

    @Override
    public List<MenuListVO> treeList() {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(Menu::getStatus, Constants.STATUS_USABLE);
        queryWrapper.orderByAsc(Menu::getSorted);
        List<MenuListVO> list = this.baseMapper.queryList(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPermissionList(JSON.parseArray(list.get(i).getPermission(), MenuPermissionVO.class));
        }
        Collection<? extends TreeNode<Integer>> resp = TreeUtil.buildTree(list, 0);
        return (List<MenuListVO>) resp;
    }

    @Override
    public List<OptVO> treeOpt() {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getStatus, Constants.STATUS_USABLE);
        queryWrapper.orderByAsc(Menu::getSorted);
        List<OptVO> list = this.baseMapper.queryOptList(queryWrapper);
        Collection<? extends TreeNode<Integer>> resp = TreeUtil.buildTree(list, 0);
        return (List<OptVO>) resp;
    }

    @Override
    public List<UserMenusVO> queryUserMenusList(Integer userId) {
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sys_menu.status", Constants.STATUS_USABLE).eq("sys_role.status", Constants.STATUS_USABLE)
                        .eq("sys_user_role.user_id", userId);
        queryWrapper.select("distinct ").orderByAsc("sys_menu.sorted");
        return this.baseMapper.queryUserMenusList(queryWrapper);
    }

}
