/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.google.common.collect.Lists;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.constant.CacheNames;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.domain.SysParameter;
import com.jeeplus.sys.domain.SysParameterValue;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.sys.service.DataRuleService;
import com.jeeplus.sys.service.MenuService;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.*;
import com.jeeplus.sys.service.mapstruct.MenuWrapper;
import com.jeeplus.sys.sms.SMSUtils;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户工具类
 * @author jeeplus
 * @version 2021-06-05
 */
public class UserUtils {

	private static OfficeMapper officeMapper = SpringContextHolder.getBean(OfficeMapper.class);

	private static UserService userService = SpringContextHolder.getBean(UserService.class);

	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static UserDTO get(String id){
		UserDTO userDTO = (UserDTO) RedisUtils.getInstance ().get ( CacheNames.USER_CACHE_USER_ID, id );

		if(userDTO == null){
			userDTO = SpringUtil.getBean( UserService.class).get (id);
		}
		return userDTO;
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	@InterceptorIgnore
	public static UserDTO getByLoginName(String loginName){
		UserDTO userDTO = SpringUtil.getBean(UserService.class).getUserByLoginName ( loginName );
		return userDTO;
	}

	/**
	 * 根据用户名获取用户
	 * @param name
	 * @return 取不到返回null
	 */
	@InterceptorIgnore
	public static UserDTO getByName(String name){
		UserDTO userDTO = userService.getUserByName ( name );
		return userDTO;
	}

	/**
	 * 清除当前用户缓存
	 */
	public static void deleteCache(UserDTO userDTO){
		RedisUtils.getInstance ().delete ( CacheNames.USER_CACHE_USER_ID, userDTO.getId ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_DATA_RULE_LIST, userDTO.getId ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_MENU_LIST, userDTO.getId ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_ROLE_LIST, userDTO.getId ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_TOP_MENU, userDTO.getId ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_LOGIN_NAME, userDTO.getLoginName ());
		RedisUtils.getInstance ().delete  ( CacheNames.USER_CACHE_LOGIN_NAME, userDTO.getOldLoginName () );
	}


	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static UserDTO getCurrentUserDTO(){
		String username = SecurityUtils.getLoginName ();
		if (StrUtil.isNotEmpty ( username )){
			return getByLoginName( username);
		}
		return new UserDTO ();
	}

	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	public static List<RoleDTO> getRoleDTOList(){
		return getCurrentUserDTO ().getRoleDTOList ();
	}

	/**
	 * 获取当前用户授权菜单， admin用户不受角色权限控制可以获取全部菜单
	 * @return
	 */
	public static List<MenuDTO> getMenuDTOList(){
		String loginName = SecurityUtils.getLoginName ();
		return getMenuDTOListByLoginName ( loginName );
	}


	public static List<MenuDTO> getMenuDTOListByLoginName(String loginName){
		UserDTO user = UserUtils.getByLoginName ( loginName );
		List<MenuDTO> menuDTOList = (List<MenuDTO>)RedisUtils.getInstance ().get ( CacheNames.USER_CACHE_MENU_LIST, user.getId () );
		if (menuDTOList == null){

			if (user.isAdmin ()){
				menuDTOList = SpringUtil.getBean( MenuService.class).findList ();
			}else{
				menuDTOList = SpringUtil.getBean(MenuService.class).findByUserId(user.getId ());
			}
			RedisUtils.getInstance ().set ( CacheNames.USER_CACHE_MENU_LIST, user.getId (), menuDTOList );
		}
		return menuDTOList;
	}
	/**
	 * 获取当前用户授权数据权限， admin用户不受数据权限限制可以访问全部数据
	 * @return
	 */
	public static List<DataRuleDTO> getDataRuleList(){
		UserDTO userDTO = getCurrentUserDTO ();
		if (userDTO.isAdmin ()) {
			return Lists.newArrayList ();
		} else {
			return SpringUtil.getBean( DataRuleService.class).findByUserId(userDTO);
		}
	}

	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static MenuDTO getTopMenuDTO() {
		MenuDTO topMenuDTO = (MenuDTO) RedisUtils.getInstance ().get ( CacheNames.USER_CACHE_TOP_MENU, getCurrentUserDTO ().getId () );
		if (topMenuDTO == null) {
			topMenuDTO = MenuWrapper.INSTANCE.toDTO (SpringUtil.getBean(MenuService.class).getById ("1"));
			RedisUtils.getInstance ().set ( CacheNames.USER_CACHE_TOP_MENU, getCurrentUserDTO ().getId (), topMenuDTO );
		}
		return  topMenuDTO;
	}


	/**
	 * 获取用户权限
	 * @return
	 */
	public static Set <String> getPermissionsByLoginName(String loginName) {
		Set <String> info = new HashSet <> ( );
		List <MenuDTO> list = UserUtils.getMenuDTOListByLoginName ( loginName );
		for (MenuDTO menuDTO : list) {
			if ( StrUtil.isNotBlank ( menuDTO.getPermission ( ) ) ) {
				for (String permission : StrUtil.split ( menuDTO.getPermission ( ), "," )) {
					info.add ( permission );
				}
			}
		}
		return info;
	}
	public static Set <String> getPermissions() {
		String loginName = SecurityUtils.getLoginName ();
		return getPermissionsByLoginName ( loginName );
	}

	/**
	 * 获取系统参数
	 * parameter 参数类型
	 * branchOffice 分公司Id 分公司id为空传公司id
	 * @return
	 */
	public static String getSysParam(String parameter) {
		//查询当前登录人公司信息
		UserDTO userDTO = UserUtils.getCurrentUserDTO();
		OfficeDTO companyDTO = userDTO.getCompanyDTO();
		//当前登录人所属公司是子公司
		if (!"0".equals(companyDTO.getParentId()) && "1".equals(companyDTO.getType())) {
			//查询子公司简称
			if ("branch_shortname".equals(parameter)) {
				SysParameterValue sysParameterValue = officeMapper.findValueByParameter(parameter, companyDTO.getId());
				return sysParameterValue == null ? "" : sysParameterValue.getValue();
			}
			//查询公司简称
			if ("company_shortname".equals(parameter)) {
				SysParameterValue sysParameterValue = officeMapper.findValueByParameter(parameter, companyDTO.getParentId());
				return sysParameterValue == null ? "" : sysParameterValue.getValue();
			}
		} else {
			//当前登录人所属公司是总公司
			//查询公司简称
			if ("company_shortname".equals(parameter)) {
				SysParameterValue sysParameterValue = officeMapper.findValueByParameter(parameter, companyDTO.getId());
				return sysParameterValue == null ? "" : sysParameterValue.getValue();
			}
		}
		return "";
	}

	//发送注册码
	public static String sendRandomCode(String mobile, String randomCode) throws IOException {
		//发送内容
		String content = "【匞匞】您的验证码是："+randomCode+"，有效期5分钟，请在有效期内使用。";

		return SMSUtils.send(mobile, content,"","0");

	}

	//容联云通讯
	public static HashMap<String,Object> sendRandomCodes(String mobile, String randomCode) throws IOException {
		return SMSUtils.sends(mobile, randomCode);

	}

	//注册用户重置密码
	public static String sendPass(String uid, String pwd, String tel, String password) throws IOException {
		//发送内容
		String content = "您的新密码是："+password+"，请登录系统，重新设置密码。";
		return SMSUtils.send(tel, content,"","0");

	}

	//发送预警信息
	public static String sendWarning(String mobile, String warningContent) throws IOException {
		//发送内容
		String content = "【匞匞】系统预警通知："+warningContent;

		return SMSUtils.send(mobile, content,"","0");

	}

}
