package com.sifang.modules.sys.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.extention.permission.AbstractPermissionFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class AuthUtils {

	public static String checkPagePermission(HttpServletRequest request, String authFlag) {
		User user = UserUtils.getUser();
		AbstractPermissionFilter apf = user.getApf();
		/*if(true){
			return "0";
		}*/
		if(apf != null){
			if(apf.getVo().getData().containsKey(apf.parseAuthTagToMenuId(authFlag))){
				return "0";
			}else{
				return "1";
			}
		}
		return "0";
	}

	public static List<Record> getLeftMainMenusCommon(List<Record> menus1,List<Record> menus2,List<Record> tabMenus){
		User user = UserUtils.getUser();

		AbstractPermissionFilter apf = user.getApf();
		boolean doFilter = false;
		Map<String, String> permissionMap = Maps.newHashMap();

		if(apf != null && "4".equals(user.getUserType())){
			doFilter = true;
			permissionMap = apf.getVo().getData();
		}
		if(apf != null && "7".equals(user.getUserType())){
			doFilter = true;
			permissionMap = apf.getVo().getData();
		}

		List<Record> retMenus = Lists.newArrayList();

		boolean inL1 = false;

		for(Record rd1 : menus1){

			Record menuItem = new Record();
			String menuId1 = rd1.getStr("id");
			if(doFilter && !permissionMap.containsKey(menuId1)){
				continue;
			}
			String name = rd1.getStr("name");

			menuItem.set("id", menuId1);
			menuItem.set("name", name);
			menuItem.set("icon",rd1.getStr("icon"));

			List<Record> subMenus = Lists.newArrayList();
			menuItem.set("subMenus", subMenus);

			for(Record rd2 : menus2){

				String pid2 = rd2.getStr("parent_id");
				String menuId2 = rd2.getStr("id");
				if(doFilter && !permissionMap.containsKey(menuId2)){
					continue;
				}
				String name2 = rd2.getStr("name");

				//二级菜单有href
				String href = "/BLANK";

				if(pid2.equals(menuId1)){
					for(Record tabRd : tabMenus){
						String tabPid = tabRd.getStr("parent_id");
						String tabMenuId = tabRd.getStr("id");

						if(tabPid.equals(menuId2)){//当前用户有同一个一级菜单下的二级菜单的对应的TAB页面的权限
							if(doFilter){//平台人员角色,需要进行权限判断
								if(permissionMap.containsKey(tabMenuId)){
									href = tabRd.getStr("href");
									break;
								}
							}else{//非平台人员，不需要进行角色权限判断
								href = tabRd.getStr("href");
								break;
							}
						}else{
							continue;
						}
					}
					Record subMenu = new Record();
					subMenu.set("id", menuId2);
					subMenu.set("name", name2);
					subMenu.set("href", href);
					subMenus.add(subMenu);
				}else{
					continue;
				}
			}
			retMenus.add(menuItem);
		}

		return retMenus;
	}
	public static List<Record> getLeftMainMenus(String roleId){
		//第一级菜单
		List<Record> menus1 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id` WHERE a.status = '0' AND a.target = '0' AND a.parent_id = '1' AND b.`role_id`=? ORDER BY sort DESC", roleId);
		//第二级菜单
		List<Record> menus2 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '0' AND a.parent_id != '1' AND a.parent_id != '0' AND b.`role_id`=? ORDER BY a.parent_id ASC, sort DESC", roleId);
		//TAB页面菜单
		List<Record> tabMenus = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '1' AND b.`role_id`=? ORDER BY a.sort DESC", roleId);
		return  getLeftMainMenusCommon(menus1,menus2,tabMenus);
	}

	public static List<Record> getLeftMainMenus(String roleId,String topTraderId){
		SqlBuilder builder = new SqlBuilder();
		builder.line(" select  partner_id from crm_trader_partner where trader_id=?  ",topTraderId);
		List<Record> records = Db.find(builder.build(), builder.params());
		List<String> managementList = records.stream().map(r -> r.getStr("partner_id")).collect(Collectors.toList());
		//第一级菜单
		SqlBuilder sql = new SqlBuilder();
		sql.line("  SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id` ")
				.line(" where  a.status = '0' AND a.target = '0' AND a.parent_id = '1'  AND b.`role_id`=?   ",roleId);
		if (managementList.size() > 0){
			sql.inst(" and  (a.permission IS NULL OR a.permission = '') or a.permission in", managementList);
		}else {
			sql.line(" and  (a.permission IS NULL OR a.permission = '')  ");
		}
		sql.line("   GROUP BY a.id  ORDER BY sort DESC ");
		List<Record> menus1 = Db.find(sql.build(),sql.params());
//		List<Record> menus1 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id` WHERE a.status = '0' AND a.target = '0' AND a.parent_id = '1' AND b.`role_id`=? ORDER BY sort DESC", roleId);
		//第二级菜单
		List<Record> menus2 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '0' AND a.parent_id != '1' AND a.parent_id != '0' AND b.`role_id`=? ORDER BY a.parent_id ASC, sort DESC", roleId);
		//TAB页面菜单
		List<Record> tabMenus = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '1' AND b.`role_id`=? ORDER BY a.sort DESC", roleId);
		return  getLeftMainMenusCommon(menus1,menus2,tabMenus);
	}

	//平台获取登录进去后左边的一二级菜单
	public static List<Record> getLeftMainMenus(){
		User user = UserUtils.getUser();
		if(User.USER_TYPE_GYS.equals(user.getUserType())){
			return getLeftMainMenus(User.USER_TYPE_GYS);
		}
		if (User.USER_TYPE_PARTNER.equals(user.getUserType()) || User.USER_TYPE_HZS.equals(user.getUserType())) {
			return getLeftMainMenus(user.getUserType());
		}
		return getLeftMainMenus("1");
	}

	//代理商获取菜单
	public static List<Record> getLeftMainMenusForTrader() {
		User user = UserUtils.getUser();
		String topTraderId = user.getTopTraderId();
		if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
			if (Objects.equals("1", user.getTraderType())) {
				return getLeftMainMenus("4",topTraderId);
			} else {
				return getLeftMainMenus("10",topTraderId);
			}
		} else if (User.USER_TYPE_GYS.equals(user.getUserType())) {
			return getLeftMainMenus(User.USER_TYPE_GYS);
		}
		if (Objects.equals("1", user.getTraderType())) {
			return getLeftMainMenus("4",topTraderId);
		} else {
			return getLeftMainMenus("10",topTraderId);
		}
	}

// 获取服务商端登录进去后左边的一二级菜单
	public static List<Record> getSiteLeftMainMenus(){
		//第一级菜单
		List<Record> menus1 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id` WHERE a.status = '0' AND a.target = '0' AND a.parent_id = '1' AND b.`role_id`='3' ORDER BY sort DESC");
		//第二级菜单
		List<Record> menus2 = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '0' AND a.parent_id != '1' AND a.parent_id != '0' AND b.`role_id`='3' ORDER BY  sort DESC");
		//TAB页面菜单
		List<Record> tabMenus = Db.find("SELECT a.* FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '1' AND b.`role_id`='3' ORDER BY a.sort ASC");
		User user = UserUtils.getUser();

		AbstractPermissionFilter apf = user.getApf();
		boolean doFilter = false;
		Map<String, String> permissionMap = Maps.newHashMap();

		if(apf != null && "5".equals(user.getUserType())){
			doFilter = true;
			permissionMap = apf.getVo().getData();
		}

		List<Record> retMenus = Lists.newArrayList();

		boolean inL1 = false;

		for(Record rd1 : menus1){

			Record menuItem = new Record();
			String menuId1 = rd1.getStr("id");
			if(doFilter && !permissionMap.containsKey(menuId1)){
				continue;
			}
			String name = rd1.getStr("name");

			menuItem.set("id", menuId1);
			menuItem.set("name", name);
			menuItem.set("icon",rd1.getStr("icon"));
			List<Record> subMenus = Lists.newArrayList();
			menuItem.set("subMenus", subMenus);

			for(Record rd2 : menus2){

				String pid2 = rd2.getStr("parent_id");
				String menuId2 = rd2.getStr("id");
				if(doFilter && !permissionMap.containsKey(menuId2)){
					continue;
				}
				String name2 = rd2.getStr("name");

				//二级菜单有href
				String href = "/BLANK";

				if(pid2.equals(menuId1)){
					for(Record tabRd : tabMenus){
						String tabPid = tabRd.getStr("parent_id");
						String tabMenuId = tabRd.getStr("id");
						if(tabPid.equals(menuId2)){//当前用户有同一个一级菜单下的二级菜单的对应的TAB页面的权限
							if(doFilter){//服务商人员角色,需要进行权限判断
								if(permissionMap.containsKey(tabMenuId)){
									href = tabRd.getStr("href");
									break;
								}
							}else{//非平台人员，不需要进行角色权限判断
								href = tabRd.getStr("href");
								break;
							}
						}else{
							continue;
						}
					}
					Record subMenu = new Record();
					subMenu.set("id", menuId2);
					subMenu.set("name", name2);
					subMenu.set("href", href);
					subMenus.add(subMenu);
				}else{
					continue;
				}
			}
			retMenus.add(menuItem);
		}

		return retMenus;
	}

	//判断是否有新建流程的权限  0 有权限  1 无权限
	public static String flowableAddPermission(String formId){
		User user = UserUtils.getUser();
		String roleIds=user.getRoleIds();    //用户角色
		Record submitRecord= FormUtils.submitRoleId(formId);   //提交节点的用户角色
		if(submitRecord!=null){
			String submitType=submitRecord.getStr("submit_type");// 提交人类型 1平台角色 2 平台员工 3 代理商
			if("3".equals(submitType)){
				if("6".equals(user.getUserType()) ||"7".equals(user.getUserType())){
					return "0";
				}
			}else if("1".equals(submitType)){
				if(roleIds.contains(submitRecord.getStr("role_id"))){
					return "0";
				}
			}else if("2".equals(submitType)){
				if(submitRecord.getStr("emp_user_id").contains(user.getId()) && "4".equals(user.getUserType())){
					return "0";
				}
			}
		}
		return "1";
	}

	//判断是否有审批权限
    public static String flowableAuditPermission(String formId,String taskName,String createDepartId){
		User user = UserUtils.getUser();
		String roleIds=user.getRoleIds();    //用户角色
		String departmentId=user.getDepartmentId();  //用户的部门
		Record record=FormUtils.getAuditRole(formId,taskName);  //获取节点审批设置
		if(record == null){
			return "0";
		}
		String auditRoleId= record.get("role_id"); // 获取审批角色
		String transDepartment=record.getStr("trans_department");
		if(roleIds.contains(auditRoleId)){
			if("0".equals(transDepartment)){  //不跨部门
				return "1";
			}else{   //跨部门
                //获取提交人的所有上级部门
				String topDepts=FormUtils.getTopDepart(departmentId);
				if(topDepts.contains(departmentId) || departmentId==createDepartId){
					return "1";
				}
			}
		}
		return "0";
	}

	/**
	 * 获取平台员工的小程序登录及操作权限 或者 可以判断某平台员工是否有某个操作权限
	 * 返回：返回NULL表示无登录权限，返回0表示有登录权限无操作权限，返回其他值表示有登录权限且存在操作权限 其操作权限值用,隔开
	 */
	public static String getPlatEmpMenusForSmallProgram(String empId, String permission) {
		/*String menuId = getMiniViewPremissForEmp(empId);
		if (StringUtil.isBlank(menuId)) {
			return "NULL";
		}*/
		// 获取平台员工的小程序操作权限
		SqlBuilder getMenusSQL = new SqlBuilder();
		getMenusSQL.line(" SELECT DISTINCT(p.permission) as permission ");
		getMenusSQL.line(" FROM crm_platform_employee_role er, crm_platform_employee_role_rel r, sys_menu_pro p ");
		getMenusSQL.line(" WHERE r.`employee_id` = ? AND FIND_IN_SET(er.id, r.role_ids)  ", empId);
		getMenusSQL.line("  AND FIND_IN_SET(p.`id`, er.`permission`) AND p.type = '2' AND p.permission is not null and  p.permission!='' ");
		if (StringUtil.isNotBlank(permission)) {
			getMenusSQL.line("  AND p.permission = ? ", permission);
		}
		List<Record> records = Db.find(getMenusSQL.build(), getMenusSQL.params());
		if (records == null || records.size() <= 0) {
			return "0";
		}
		String menus = "";
		for (Record r : records) {
			if (StringUtil.isBlank(menus)) {
				menus = r.getStr("permission");
			} else {
				menus = menus + "," + r.getStr("permission");
			}
		}
		return menus;
	}

	/**
	 * 获取平代理商员工的小程序操作权限
	 */
	public static List<String> getTraderEmpMenusForSmallProgram(String roleId) {
		SqlBuilder getMenusSQL = new SqlBuilder();
		getMenusSQL.line(" SELECT DISTINCT(p.permission) as permission ");
		getMenusSQL.line(" FROM crm_platform_employee_role er, sys_menu_pro p ");
		getMenusSQL.line(" WHERE er.id = ?", roleId);
		getMenusSQL.line(" AND FIND_IN_SET(p.`id`, er.`permission`) AND p.type = '2' AND p.permission is not null");
		return Db.query(getMenusSQL.build(), getMenusSQL.params());
	}

	/**
	 * 判断代理商员工是否拥有某个操作权限
	 *
	 * @return 返回 true表示拥有，false表示不拥有
	 */
	public static boolean checkMiniTraderPremissForEmp(String userId, String permission) {
		SqlBuilder sql = new SqlBuilder();
		sql.line("SELECT COUNT(1) ");
		sql.line("FROM crm_trader_employe e");
		sql.line("INNER JOIN crm_platform_employee_role er ON er.id = e.role_id");
		sql.line("LEFT JOIN sys_menu_pro p ON FIND_IN_SET(p.id, er.permission)");
		sql.line("WHERE e.user_id = ?", userId);
		sql.line("AND p.permission = ?", permission);
		sql.line("AND p.type = '2' AND p.permission is not null");
		return Db.queryLong(sql.build(), sql.params()) > 0;
	}

	/**
	 * 判断平台员工是否拥有某个操作权限
	 * @param permission 为0表示判断是否拥有数据查看权限，非0表示判断是否拥有对应操作权限
	 * @return 返回 true表示拥有，false表示不拥有
	 */
	public static boolean checkMiniOptPremissForEmp(String empId, String permission) {
		// 判断员工是否拥有查看数据权限
		if ("NULL".equals(permission)) {
			String menu = getMiniViewPremissForEmp(empId);
			if (StringUtil.isBlank(menu)) {
				return false;
			}
			return true;
		}
		String menu = getPlatEmpMenusForSmallProgram(empId, permission);
		if (menu.equals(permission)) {
			return true;
		}
		return false;
	}

	/**
	 * 获取小程序权限对应值
	 * @param type 0.小程序查询数据权限 1.设计审核操作权限 2.安装验收操作权限 3.并网验收操作权限
	 */
	public static String getMiniOptPremissVal(int type) {
		switch (type) {
			case 0:
				return "HYXCX";
			case 1:
				return "HYXCX_SJSH_B";
			case 2:
				return "HYXCX_ANYS_B";
			case 3:
				return "HYXCX_BWYS_B";
			default:
				return null;
		}
	}

	/**
	 * 获取平台员工是否拥有小程序查询的菜单权限，有则返回菜单id
	 */
	public static String getMiniViewPremissForEmp(String empId) {
		// TODO 菜单关键字待确认
		String menuKey = getMiniOptPremissVal(0);
		SqlBuilder checkMainPremiss = new SqlBuilder();
		checkMainPremiss.line(" select DISTINCT(p.id) as id ");
		checkMainPremiss.line(" FROM crm_platform_employee_role er, crm_platform_employee_role_rel r, sys_menu_pro p ");
		checkMainPremiss.line(" WHERE r.`employee_id` = ? AND FIND_IN_SET(er.id, r.role_ids) AND p.`href` = ? ", empId, menuKey);
		checkMainPremiss.line("  AND FIND_IN_SET(p.`id`, er.`permission`) AND p.type = '2' ");
		checkMainPremiss.line(" limit 1 ");
		return Db.queryStr(checkMainPremiss.build(), checkMainPremiss.params());
	}

	public static List<String> getLeftMainMenusFromSmall(String roleId,User user){
		//第一级菜单
		List<Record> menus1 = Db.find("SELECT a.id FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id` WHERE a.status = '0' AND a.target = '0' AND a.parent_id = '1' AND b.`role_id`=? ORDER BY sort DESC", roleId);
		//第二级菜单
		List<Record> menus2 = Db.find("SELECT a.id,a.parent_id FROM `sys_role_menu` b LEFT JOIN `sys_menu_pro`a ON b.`menu_id`=a.`id`WHERE a.status = '0' AND a.target = '0' AND a.parent_id != '1' AND a.parent_id != '0' AND b.`role_id`=? ORDER BY a.parent_id ASC, sort DESC", roleId);

		AbstractPermissionFilter apf = user.getApf();
		boolean doFilter = false;
		Map<String, String> permissionMap = Maps.newHashMap();

		if(apf != null && "4".equals(user.getUserType())){
			doFilter = true;
			permissionMap = apf.getVo().getData();
		}

		List<String> retMenus = Lists.newArrayList();

		for(Record rd1 : menus1){
			String menuId1 = rd1.getStr("id");
			if(doFilter && !permissionMap.containsKey(menuId1)){
				continue;
			}
			for(Record rd2 : menus2){
				String pid2 = rd2.getStr("parent_id");
				String menuId2 = rd2.getStr("id");
				if(doFilter && !permissionMap.containsKey(menuId2)){
					continue;
				}
				if(pid2.equals(menuId1)){
					retMenus.add(menuId2);
				}else{
					continue;
				}
			}
		}
		return retMenus;
	}

	/**
	 * 小程序获取代理商员工权限
	*/
	public static List<String> findMiniTraderEmpPremins(String empId){
		List<String> list = Lists.newArrayList();
		SqlBuilder sql = new SqlBuilder();
		sql.line(" select p.permission ");
		sql.line(" FROM crm_platform_employee_role er, crm_trader_employe r, sys_menu_pro p ");
		sql.line(" WHERE r.`id` = ? AND er.id= r.role_id ", empId);
		sql.line("  AND FIND_IN_SET(p.`id`, er.`permission`)  and p.permission  is not null  ");
		List<Record> rds = Db.find(sql.build(), sql.params());
		for(Record rd :rds){
			list.add(rd.getStr("permission"));
		}
		return list;
	}



}
