/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sifang.modules.sys.common;

import com.jfinal.kit.StrKit;
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.BusinessException;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.SpringContextHolder;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.dao.MenuDao;
import com.sifang.modules.sys.dao.RoleDao;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.extention.shiro.SystemAuthorizingRealm;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 用户工具类
 * @version 2019-11-15
 */
public class UserUtils extends BaseService {

	private static Logger logger = LoggerFactory.getLogger(UserUtils.class);

	private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);

	public static final String CACHE_USER = "user";
	
	public static User getUser(){
		User user = (User)getCache(CACHE_USER);
		if (user == null){
			try{
				Subject subject = SecurityUtils.getSubject();
				SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal)subject.getPrincipal();
				if (principal!=null){
					user = getUser(principal.getId());
					user.setApf(principal.getApf());
					putCache(CACHE_USER, user);
				}
			}catch (Exception e) {
				
			}
		}
		if (user == null){
			user = new User();
			try{
				SecurityUtils.getSubject().logout();
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		}
		return user;
	}

	public static User getUser(String userId){
		User user = userDao.getById(userId);
		if (user == null){
			throw new BusinessException("未查询用户信息");
		}
//		logger.info("getUser(String userId) : {}", userId);
		try {
			String userName = CrmUtils.getUserXM(user);
			user.setUserName(userName);
			String departmentId = "";
			String departmentName = "";
			Record record = CrmUtils.getEmpDepart(user);
			if (record != null) {
				if (StringUtil.isNotBlank(record.getStr("department_id"))) {
					departmentId = record.getStr("department_id");
				}
				if (StringUtil.isNotBlank(record.getStr("depart_name"))) {
					departmentName = record.getStr("depart_name");
				}
			}
			user.setDepartmentId(departmentId);
			user.setDepartmentName(departmentName);
			String roleIds = roleDao.getUserRole(user.getId());
			user.setRoleIds(roleIds);
			if (User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())) {
				Record traderRecord = CrmUtils.getUserTrader(user.getUserType(), user.getId());
				user.setTraderId(traderRecord.getStr("id"));
				user.setTraderType(traderRecord.getStr("type"));
				user.setTopTraderId(traderRecord.getStr("parent_id"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("用户部门角色信息有误");
		}
		return user;
	}
	
	public static User getUser(boolean isRefresh){
		if (isRefresh){
			removeCache(CACHE_USER);
		}
		return getUser();
	}

	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getCacheMap().get(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
		getCacheMap().put(key, value);
	}

	public static void removeCache(String key) {
		getCacheMap().remove(key);
	}
	
	public static Map<String, Object> getCacheMap(){
		//Map<String, Object> map = Maps.newHashMap();
		try{
			Subject subject = SecurityUtils.getSubject();
			SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal)subject.getPrincipal();
			return principal!=null?principal.getCacheMap(): new HashMap<String, Object>();
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return new HashMap<String, Object>();
	}


	public static String findName(User user){
		if(user ==null){
			return "代理商";
		}
		if(User.USER_TYPE_KJ.equals(user.getUserType())){
			return user.getUserName();
		}else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
			String traderId= CrmUtils.getUserRelId(user);
			String traderName=CrmUtils.getTraderNameById(traderId);
			return traderName+" "+findTraderRoleName(user.getId())+" "+user.getUserName();
		}
		String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+user.getUserName();

		return  otherName;
	}

	public static String findRoleName(String roleRds){
		List<Record> list = FormUtils.getPlatformRoleNameByIds(roleRds);
		StringBuilder roleSb = new StringBuilder("");
		for (Record rd : list) {
			roleSb.append(",").append(rd.getStr("name"));
		}
		if (StrKit.notBlank(roleSb.toString())) {
			String str = roleSb.toString().substring(1);
			return str;
		}
		return roleSb.toString();
	}

	public static String findRoleNameByEmp(String userId) {
		String roleIds = roleDao.getUserRole(userId);
		if (StringUtil.isBlank(roleIds)) {
			roleIds = "";
		}
		String name = findRoleName(roleIds);
		return name;
	}

	public static String findTraderRoleName(String userId) {
		Record rd = Db.findFirst("SELECT role_name FROM `crm_trader_employe` WHERE STATUS='0' AND user_id=?", userId);
		return rd.getStr("role_name");
	}
}
