package com.jsowell.common.util;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.jsowell.common.constant.HttpStatus;
import com.jsowell.common.core.domain.entity.SysDept;
import com.jsowell.common.core.domain.entity.SysRole;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.domain.model.LoginUser;
import com.jsowell.common.core.domain.vo.AuthorizedDeptVO;
import com.jsowell.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**
 * 安全服务工具类
 *
 * @author jsowell
 */
@Slf4j
public class SecurityUtils {
	/**
	 * 用户ID
	 **/
	public static Long getUserId() {
		try {
			return getLoginUser().getUserId();
		} catch (Exception e) {
			throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 获取部门ID
	 **/
	public static Long getDeptId() {
		try {
			return getLoginUser().getDeptId();
		} catch (Exception e) {
			throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 获取用户账户
	 **/
	public static String getUsername() {
		try {
			return getLoginUser().getUsername();
		} catch (Exception e) {
			throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 获取用户
	 **/
	public static LoginUser getLoginUser() {
		try {
			return (LoginUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 获取Authentication
	 */
	public static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 生成BCryptPasswordEncoder密码
	 *
	 * @param password 密码
	 * @return 加密字符串
	 */
	public static String encryptPassword(String password) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.encode(password);
	}

	/**
	 * 判断密码是否相同
	 *
	 * @param rawPassword     真实密码
	 * @param encodedPassword 加密后字符
	 * @return 结果
	 */
	public static boolean matchesPassword(String rawPassword, String encodedPassword) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.matches(rawPassword, encodedPassword);
	}

	/**
	 * 是否为管理员
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	public static boolean isAdmin(Long userId) {
		return userId != null && 1L == userId;
	}

	// 查询登录用户权限
	public static AuthorizedDeptVO getAuthorizedMap() {
		// 登录用户
		LoginUser loginUser = getLoginUser();
		if (loginUser == null) {
			return null;
		}
		// 用户
		SysUser user = loginUser.getUser();
		if (user == null) {
			return null;
		}
		AuthorizedDeptVO resultVO = AuthorizedDeptVO.builder().build();
		// 登录用户所属部门（运营商或站点 根据父级id判断）
		SysDept dept = user.getDept();
		if (dept == null) {
			log.info("用户id:{}, 获取不到所属部门信息", user.getUserId());
			return null;
		}
		log.info("用户id:{}, 所属部门信息:{}", user.getUserId(), JSONObject.toJSONString(dept));
		// 登录用户角色
		List<SysRole> roles = user.getRoles();
		Long parentId = dept.getParentId();
		List<String> merchantDeptIds = Lists.newArrayList();
		List<String> stationDeptIds = Lists.newArrayList();
		if (parentId == 0L) {
			// 父级id是0，表明是该账号挂在平台下面，是系统管理员
		} else if (parentId == 100L) {
			// 父级id是100，表明是该账号挂在运营商下面，是运营商管理员
			merchantDeptIds.add(String.valueOf(dept.getDeptId()));
			resultVO.setMerchantDeptIds(merchantDeptIds);
		} else {
			// 其他情况，表明是站点管理员
			stationDeptIds.add(String.valueOf(dept.getDeptId()));
			resultVO.setStationDeptIds(stationDeptIds);
		}
		return resultVO;
	}
}
