package com.sifang.modules.setting.dao;

import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class MemberRoleDao {

    //根据角色的ID获取所有菜单
    public List<Record> getMenusByUserRole(String roleId){
        StringBuilder sb = new StringBuilder("");
        sb.append("select b.* from sys_role_menu a , sys_menu_pro b where b.id = a.menu_id and b.status = '0' and a.role_id = ? ORDER BY b.sort DESC ");
        return Db.find(sb.toString(), roleId);
    }

    public List<Record> getMemberRoleMenus(String userId){
        StringBuilder sb = new StringBuilder("");
        sb.append(" select a.role_ids from crm_platform_employee_role_rel a, crm_platform_employee c ");
        sb.append(" where a.employee_id = c.id and c.user_id = ? and c.status = '0' ");
        String roleIds = Db.findFirst(sb.toString(), userId).getStr("role_ids");

        String[] roleIdArr = roleIds.split(",");
        StringBuilder insb = new StringBuilder("'-1'");
        for(String roleId : roleIdArr){
            insb.append(",").append("'").append(roleId).append("'");
        }

        return Db.find(" select * from crm_platform_employee_role a where a.id in ("+insb.toString()+") ");
    }

    /**
     *服务商人员获取保存设置的登陆权限 ***
     */
   public Record getSitMemberRoleMenus(String siteId,Integer role){
        String sql="SELECT * FROM `crm_site_employee_role` WHERE site_id=? AND role=?";
            return Db.findFirst(sql,siteId,role);
   }


    public List<Record> getMenusByMemberRoleId(String roleId){
        return Db.find(" select * from crm_platform_employee_role a where a.id = ? ", roleId);
    }

    //配合 @Method:getMemberRoleMenus使用
    public Map<String, String> getMemberRoleMap(List<Record> roleRds){
        Map<String, String> map = Maps.newHashMap();
        for(Record rd : roleRds){
            String permission = rd.getStr("permission");
            if(StrKit.notBlank(permission)){
                String[] perArr = permission.split(",");
                for(String per : perArr){
                    if(!map.containsKey(per)){
                        map.put(per, "1");
                    }
                }
            }
        }
        return map;
    }
}
