package cn.quantgroup.xyqb.security;

import cn.quantgroup.xyqb.entity.enums.Device;
import cn.quantgroup.xyqb.exception.DataException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static cn.quantgroup.xyqb.security.SecurityConstant.DEFAULT_DEVICE_ID;

/**
 * Created by Administrator on 2021/6/30 0030.
 */
public abstract class HttpAspect {

    public AssentHeader getAssentHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        AssentHeader header = new AssentHeader();
        String authorization = ObjectUtils.getDisplayString(request.getHeader("authorization"));
        if(!StringUtils.isEmpty(authorization)){
            String[] strings = authorization.split(" ");
            if(strings.length<2){
                throw new DataException("Header does not look like authorization. "+authorization);
            }
            header.setAuthType(strings[0]);
            header.setAuthMessage(strings[1]);
        }

        header.setIdfa(ObjectUtils.getDisplayString(request.getHeader("idfa")));
        header.setScDeviceId(ObjectUtils.getDisplayString(request.getHeader("scDeviceId")));
        header.setRemoteAddress(ObjectUtils.getDisplayString(request.getHeader("x-real-ip")));
        header.setDeviceCode(ObjectUtils.getDisplayString(request.getHeader("x-user-platform")));
        header.setPhoneNumber(ObjectUtils.getDisplayString(request.getHeader("x-user-phone")));
        header.setDeviceId(DEFAULT_DEVICE_ID);

        if (!"".equals(header.getScDeviceId())) {
            header.setDeviceId(header.getScDeviceId());
        } else if (!"".equals(header.getIdfa())) {
            header.setDeviceId(header.getIdfa());
        }
        header.setDevice(Device.valueOfCode(header.getDeviceCode()));

        return header;

    }
}
