package com.lantone.common.util;

import cn.hutool.json.JSONUtil;
import com.lantone.common.constant.AuthConstant;
import com.lantone.common.domain.UserDto;
import com.lantone.common.exception.Asserts;
import com.nimbusds.jose.JWSObject;

/**
 * @Description: 用户工具类
 * @author: rengb
 * @time: 2021/1/5 18:27
 */
public class SysUserUtils {

    /**
     * 获取当前请求的token
     *
     * @return
     */
    public static String getToken() {
        return HttpUtils.getHeader(AuthConstant.JWT_TOKEN_HEADER);
    }

    /**
     * 从token中解析出用户信息
     *
     * @param token
     * @return
     */
    public static UserDto getUserByToken(String token) {
        UserDto userDto = null;
        try {
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            userDto = JSONUtil.toBean(jwsObject.getPayload().toString(), UserDto.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userDto;
    }

    /**
     * 获取当前请求的用户
     *
     * @return
     */
    public static UserDto getCurrentUser() {
        return getUserByToken(getToken());
    }

    /**
     * 获取当前请求的用户的名称
     *
     * @return
     */
    public static String getCurrentPrinciple() {
        UserDto userDto = getCurrentUser();
        return userDto == null ? null : userDto.getUserName();
    }

    /**
     * 获取当前请求的用户的Id
     *
     * @return
     */
    public static Long getCurrentPrincipleId() {
        UserDto userDto = getCurrentUser();
        return userDto == null ? null : userDto.getId();
    }

    /**
     * 获取当前请求的用户的当前医院id
     *
     * @return
     */
    public static Long getCurrentHospitalId() {
        if(StringUtil.isNotEmpty(HttpUtils.getHeader(AuthConstant.HOSPITAL_ID_HEADER))){
            return Long.parseLong(HttpUtils.getHeader(AuthConstant.HOSPITAL_ID_HEADER));
        }else {
            Asserts.fail("请求头中无医院id");
        }
        return null;
    }

    /**
     * 获取当前请求的用户的当前系统id
     *
     * @return
     */
    public static String getCurrentSoftwareId() {
        if(StringUtil.isNotEmpty(HttpUtils.getHeader(AuthConstant.SOFTWARE_ID_HEADER))){
            return HttpUtils.getHeader(AuthConstant.SOFTWARE_ID_HEADER);
        }else {
            Asserts.fail("请求头中无医院id");
        }
        return null;
    }

}