package com.liquidnet.commons.lang.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class IdentityUtils {
    private static final Logger log = LoggerFactory.getLogger(IdentityUtils.class);
    private static final String aliThirdUrl = "https://1.api.apistore.cn/idcard3";
    private static final String aliThirdAppCode = "74884b154fbc49dc9ebf2fc977086f20";

    private static final String ALI_MOBILE_CERT_HOST = "https://mobilecert.market.alicloudapi.com";
    private static final String ALI_MOBILE_CERT3_META_URI = "/mobile3Meta";

    public static String aliThird(String realName, String cardNo) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("realName", realName);
        params.add("cardNo", cardNo);
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.add("Authorization", "APPCODE " + aliThirdAppCode);
        log.info("实名认证开始realName==============={}",realName);
        try {
            return HttpUtil.post(aliThirdUrl, params, header);
        } catch (Exception e) {
            log.error("###实名认证异常:{}", params, e);

            if (e instanceof UnknownHttpStatusCodeException) {
                UnknownHttpStatusCodeException unknownHttpStatusCodeException = (UnknownHttpStatusCodeException) e;
                return unknownHttpStatusCodeException.getMessage();
            }
            return null;
        }
    }

    /**
     * 三要素认证
     * eg:https://market.aliyun.com/products/57000002/cmapi029847.html
     *
     * @param realName
     * @param cardNo
     * @param mobile
     * @return
     */
    public static String ali3Meta(String realName, String cardNo, String mobile) {
        LinkedMultiValueMap<String, String> headersMap = CollectionUtil.linkedMultiValueMapStringString();
        headersMap.add("Authorization", "APPCODE ".concat(aliThirdAppCode));
        LinkedMultiValueMap<String, String> paramsMap = CollectionUtil.linkedMultiValueMapStringString();
        paramsMap.add("identifyNum", cardNo);
        paramsMap.add("mobile", mobile);
        paramsMap.add("userName", realName);
        try {
            return HttpUtil.get(ALI_MOBILE_CERT_HOST.concat(ALI_MOBILE_CERT3_META_URI), paramsMap, headersMap);
        } catch (Exception e) {
            log.error("###实名认证异常:{}", paramsMap, e);
            if (e instanceof UnknownHttpStatusCodeException) {
                UnknownHttpStatusCodeException unknownHttpStatusCodeException = (UnknownHttpStatusCodeException) e;
                return unknownHttpStatusCodeException.getMessage();
            }
            return null;
        }
    }
}
