package cn.com.capcloud.core.system.role;

import cn.com.capcloud.core.system.user.User;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class RoleService {

  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RoleService.class);

  @Autowired
  private JdbcTemplate jdbcTemplate;
  @Autowired
  private RoleRepository roleRepository;
  @Autowired
  private RolePageSortRepository rolePageSortRepository;

  @Cacheable(value = "getMenuByLoginUserName",key = "#loginUserName", unless="#result == null")
  public List<Map<String,Object>> getMenuByLoginUserName(String loginUserName) {
    String menuAllSql=" SELECT menu_url,menu_id FROM tbl_system_menu WHERE menu_status='0' AND menu_url !='' AND menu_id IN "
            +" (SELECT menu_id FROM tbl_system_menurole WHERE role_id IN "
            +" (SELECT role_id FROM tbl_system_roleuser WHERE user_id="
            +" (SELECT user_id FROM tbl_system_user WHERE user_login_name='"+loginUserName+"' and status=0)));";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(menuAllSql);
    return list;
  }
  @Cacheable(value = "getRolesIdByLoginUserName",key = "#loginUserName", unless="#result == null")
  public List<Map<String,Object>> getRolesIdByLoginUserName(String loginUserName) {
    String rolesSql=" SELECT role_id FROM tbl_system_roleuser WHERE user_id="
            +" (SELECT user_id FROM tbl_system_user WHERE user_login_name='"+loginUserName+"' and status=0);";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(rolesSql);
    return list;
  }
  @Cacheable(value = "getRolesIdByMenuId",key = "#menuId", unless="#result == null")
  public List<Map<String,Object>> getRolesIdByMenuId(String menuId) {
    String menuAllSql=" SELECT role_id FROM tbl_system_menurole WHERE menu_id= "+menuId;
    List<Map<String,Object>> list=jdbcTemplate.queryForList(menuAllSql);
    return list;
  }
  //暂时不使用缓存，后续如果使用缓存则需要补充删除方法，来配合更新
  //@Cacheable(value = "getNoLoginURL",key = "", unless="#result == null")
  public List<Map<String,Object>> getNoLoginURL() {// 不需登录就能访问的url，如：登录和验证码等等
    String getNoLoginURLSql=" SELECT url_path FROM  tbl_data_nosession_url where url_status='Y';";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(getNoLoginURLSql);
    return list;
  }
  //@Cacheable(value = "getNotRoleURL",key = "", unless="#result == null")
  public List<Map<String,Object>> getNotRoleURL() {// 不需要角色权限的url，登录后就能访问
    String getNotRoleURLSql=" SELECT url_path FROM tbl_data_norole_url where url_status='Y';";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(getNotRoleURLSql);
    return list;
  }
  /**
   * 返回单条信息
   */
  public Role findOne(long id){
    return roleRepository.findById(id).orElse(null);
  }
  /**
   * 保存
   */
  public void save(Role role){
    if(role.getRoleId()>0){
      Role oldRole=this.roleRepository.findById(role.getRoleId()).orElse(null);
      role.setUsers(oldRole.getUsers());

      role.setCreateTime(oldRole.getCreateTime());
      role.setRoleCreateUser(oldRole.getRoleCreateUser());
    }
    roleRepository.save(role);
  }
  /**
   * 重新定义role中的user,role的菜单保持不边
   */
  public void updateUserForRole(Role role){
    if(role.getRoleId()>0){
      Role oldRole=this.roleRepository.findById(role.getRoleId()).orElse(null);

    }
    roleRepository.save(role);
  }

  public List<Role> getRoleNoUserByUserID(long userID){
    String sql="select * from tbl_system_role " +
            "where role_id in (select role_id from tbl_system_roleuser where user_id="+userID+")";

    List<Role> list=jdbcTemplate.query(sql,  new BeanPropertyRowMapper<Role>(Role.class) );

    return list;
  }

  public void updatePermissionsesForRole(Role role){
    if(role.getRoleId()>0){
      Role oldRole=this.roleRepository.findById(role.getRoleId()).orElse(null);
      role.setUsers(oldRole.getUsers());
    }

    roleRepository.save(role);
  }
  /**
   * 删除
   */
  public void delete(long id){
    roleRepository.deleteById(id);
  }
  /**
   * 返回全部角色信息
   */
  //@Cacheable(value = "findAllRole",key = "#username", unless="#result == null")//keyGenerator = "myKeyGenerator"
  public Iterable<Role> findALL(String username){

    return roleRepository.findAll();
  }

  /**
   * 分页返回全部角色信息
   */
  public Page<Role> findALL(Pageable pageable){
    return rolePageSortRepository.findAll(pageable);
  }
  /**
   * 根据角色名称查询，并分页返回全部信息
   */
  public Page<Role> findALLByName(String roleName,Pageable pageable){
    if(roleName==null||roleName.equals("null")){
      roleName="";
    }
    logger.info("%"+roleName+"%");
    return rolePageSortRepository.findByroleName("%"+roleName+"%", pageable);
  }
  /**
   * 根据角色名称返回全部角色（一般其他服务类调用）
   */
  public Role findRoleByName(String roleName){
    List<Role> list=roleRepository.findByroleName(roleName);
    if(list.size()>0){
      return list.get(0);
    }else{
      return null;
    }
  }
  public List<User> getUserByRoleName(String roleName){
    String sql="select * from tbl_system_user where user_id in (select a.user_id from tbl_system_roleuser a,tbl_system_role b where a.role_id=b.role_id and b.role_name='"+roleName+"')";
    return jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class));

  }
}

