package com.rf.psychological.menu.service.impl;

import com.rf.psychological.menu.dao.model.MenuEntry;
import com.rf.psychological.menu.dao.model.RoleMenuEntry;
import com.rf.psychological.menu.dao.repository.MenuRepository;
import com.rf.psychological.menu.service.MenuService;
import com.rf.psychological.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:zzf
 * @Date:2022/7/6:18:01
 * @Description:
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuRepository menuRepository;



    /**
     * 查询一级菜单
     *
     * @param roleMenuEntryList
     * @param menuNo
     * @return
     */
    @Override
    public List findAll(List<RoleMenuEntry> roleMenuEntryList, String menuNo) {
        Specification<MenuEntry> specification = (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            //状态为可用
            predicateList.add(cb.equal(root.get("menuStatus"), Constant.MAGIC_NUM_1));
            //菜单码在集合
            List<String> menuNos = new ArrayList<>();
            roleMenuEntryList.forEach(roleMenuEntry -> menuNos.add(roleMenuEntry.getMenuNo()));
            predicateList.add((root.get("menuNo").in(menuNos)));
            if(menuNo == null){
                //顶层菜单
                predicateList.add(cb.equal(root.get("parentMenu"),Constant.MAGIC_NUM_0));
            }else{
                predicateList.add(cb.equal(root.get("menuNo"),menuNo));
            }

            query.where(cb.and(predicateList.toArray(new Predicate[predicateList.size()])));
            query.orderBy(cb.asc(root.get("orders")));
            return query.getRestriction();
        };
        return this.menuRepository.findAll(specification);
    }

    /**
     * menuNo---menuEntry
     *
     * @param menuNo
     * @return
     */
    @Override
    public MenuEntry findByMenuNo(String menuNo) {
        return menuRepository.findByMenuNo( menuNo);
    }

}
