package com.huimv.management.util;

import com.alibaba.fastjson.JSONObject;
import com.huimv.common.exception.RRException;
import com.huimv.common.utils.R;
import com.huimv.management.SpringContextUtils;
import com.huimv.management.entity.SysUserEntity;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Properties;

/**
 * <p>
 * 通过restTemplate获取用户的工具类
 * </p>
 *
 * @author yinhao
 * @date 2021/6/21 9:02
 */
public class GetUserUtil {

    private static String url;

    private static RestTemplate restTemplate = SpringContextUtils.getBean("restTemplate",RestTemplate.class);


    static {
        Resource resource = new ClassPathResource("application.properties");
        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            url = properties.getProperty("user.info.url");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SysUserEntity getUser(HttpServletRequest request) {
        String token = request.getHeader("token");

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        HttpEntity httpEntity = new HttpEntity<>(null, headers);

        ResponseEntity<R> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, R.class);
        R r = responseEntity.getBody();
        if (r != null && 401 == (Integer) (r.get("code"))) {
            throw new RRException((String) r.get("msg"), (Integer) r.get("code"));
        }
        String jsonString = null;
        if (r != null) {
            jsonString = JSONObject.toJSONString(r.get("user"));
        }
        SysUserEntity user = JSONObject.parseObject(jsonString, SysUserEntity.class);
        return user;
    }
}
