package com.clx.performance.component;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigRequest;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.clx.performance.config.AliSliderConfig;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.param.app.SendMobileCaptchaParam;
import com.msl.common.exception.ServiceSystemException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @author cuiwanzhe
 * @description
 * @date 2020/9/1 4:58 下午
 */
@Service
@Slf4j
@AllArgsConstructor
public class SendMessageMachineCheckComponent {


    private final AliSliderConfig aliSliderConfig;


    /**
     * 滑动验证
     *
     * @throws
     */
    public void sendMessageMachineSelectCheck(HttpServletRequest request, SendMobileCaptchaParam param) throws ServiceSystemException {
        if (StringUtils.isBlank(param.getSessionId())) {
            throw new ServiceSystemException(PerformanceResultEnum.SLIDER_CHECK_FAIL);
        }
        if (StringUtils.isBlank(param.getSig())) {
            throw new ServiceSystemException(PerformanceResultEnum.SLIDER_CHECK_FAIL);
        }
        if (StringUtils.isBlank(param.getToken())) {
            throw new ServiceSystemException(PerformanceResultEnum.SLIDER_CHECK_FAIL);
        }
        if (StringUtils.isBlank(param.getScene())) {
            throw new ServiceSystemException(PerformanceResultEnum.SLIDER_CHECK_FAIL);
        }
        Integer responseCode = machineCheckSelect(request, param);
        if (responseCode >= 400) {
            throw new ServiceSystemException(PerformanceResultEnum.SLIDER_CHECK_FAIL);
        }
    }

    private Integer machineCheckSelect(HttpServletRequest req, SendMobileCaptchaParam param) {
        Integer resultCode = null;
        IClientProfile profile = DefaultProfile.getProfile(aliSliderConfig.getRegionId(), aliSliderConfig.getAccessKeyId(), aliSliderConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        try {
            DefaultProfile.addEndpoint(aliSliderConfig.getRegionId(), aliSliderConfig.getRegionId(), aliSliderConfig.getProduct(), aliSliderConfig.getDomain());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        String ip = getIpAddress(req);
        log.info("=滑动验证=mobile==========>>" + param.getMobile() + "==sessionId========>>" + param.getSessionId() + "==sig=====>>>" + param.getSig() +
                "==token=====>>>" + param.getToken() + "==scene=====>>>" + param.getScene() + "==ip=====>>>" + ip);
        AuthenticateSigRequest request = new AuthenticateSigRequest();
        request.setSessionId(param.getSessionId());// 会话ID。必填参数，从前端获取，不可更改。
        request.setSig(param.getSig());// 签名串。必填参数，从前端获取，不可更改。
        request.setToken(param.getToken());// 请求唯一标识。必填参数，从前端获取，不可更改。
        request.setScene(param.getScene());// 场景标识。必填参数，从前端获取，不可更改。
        request.setAppKey("FFFF0N00000000009691");// 应用类型标识。必填参数，后端填写。
        request.setRemoteIp(ip);// 客户端IP。必填参数，后端填写。
        try {
            //response的code枚举：100验签通过，900验签失败
            AuthenticateSigResponse response = client.getAcsResponse(request);
            resultCode = response.getCode();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return resultCode;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    if (inet != null) {
                        ip = inet.getHostAddress();
                    }

                } catch (Exception e) {
                    log.error(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;


    }
}
