package com.ssj.dao.sys.menu.dao;

import com.ssj.bean.sys.menu.domain.Menu;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface MenuDao extends JpaRepository<Menu, String>{

	public List<Menu> findByParentId(String parentId);
	
	@Query(nativeQuery = true, value = "select m.* from sys_menu m, sys_role_menu rm where rm.role_id = ?1 and rm.menu_id = m.id")
	public List<Menu> findAllMenuByRoleId(String roleId);
	
	@Query(nativeQuery = true, value = "SELECT\n" +
			"	m.*\n" +
			"FROM\n" +
			"  sys_admin_role r,\n" +
			"	sys_menu m,\n" +
			"	sys_role_menu rm\n" +
			"WHERE\n" +
			"	rm.role_id = r.role_id\n" +
			"AND rm.menu_id = m.id\n" +
			"AND m.parent_id =?2\n" +
			"and r.admin_id =?1\n" +
			" GROUP BY m.id \n" +
			"ORDER BY\n" +
			"	m.menu_order")
	public List<Menu> findMenuByRoleIdAndParentId(String adminId, String parentId);
	
	@Query(nativeQuery = true, value = "SELECT\n" +
			"	m.menu_url\n" +
			"FROM\n" +
			"	sys_admin_role r  \n" +
			"  join  sys_role_menu rm  on rm.role_id  = r.role_id\n" +
			"join  sys_menu  m on   rm.menu_id = m.id \n" +
			"WHERE\n" +
			"	r.admin_id = ?1 and m.parent_id >1\n" +
			"order by m.menu_order")
	public List<String> findRoleByAdminId(String adminId);
	
	
	
	@Query(nativeQuery = true, value = 	"SELECT  s.id,s.menu_name,s.menu_url,s.parent_id\n" +
			",s.menu_order,s.menu_icon,s.insert_date,s.update_date ,\n" +
			"count(m.parent_id) as sub_count  FROM  sys_menu s LEFT JOIN  sys_menu  m \n" +
			"on  s.id  = m.parent_id\n" +
			" where s.parent_id=?1\n" +
			"GROUP BY  s.id \n" +
			"ORDER BY s.menu_order asc ")
	
	 List<Menu>  getSubNodesByParentid(String parentId);
	
	 public Page<Menu> findAll(Specification<Menu> specification, Pageable page);
	 
	  @Query(nativeQuery = true, value = "update sys_menu set menu_order = ?2 where id =?1 ")
		 @Modifying
		 Integer updateMenuOrder(String id, int menu_order);
}
