package com.xxfc.platform.universal.service.authenticationInterface.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用北京畅游互联科技有限公司接口
 *
 * @author Administrator
 */
@Service
@Slf4j
@Primary
public class BJCYAuthentication implements UserAuthentication {
    private final String host = "http://aliyunverifyidcard.haoservice.com";
    private final String path = "/idcard/VerifyIdcardv2";
    private final String method = "GET";
    private final String appcode = "ee7710ce92054cae9f6c040f6864e6a7";
    private final String tokenHead = "Authorization";
    private final String token="APPCODE " + appcode;
    private final String cardNo ="cardNo";
    private final String realName ="realName";
    private final Integer  resultCode=0;
    private final String ret="error_code";
    @Override
    public boolean certificate(UserMessage message) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(tokenHead, token);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put(cardNo, message.getIdNumber());
        querys.put(realName, message.getName());
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            StatusLine statusLine = response.getStatusLine();
            log.error(response.toString());
            int statusCode = statusLine.getStatusCode();
            log.error(statusCode+"");
            //获取response的body
            if (statusCode == 200) {
                String result = EntityUtils.toString(response.getEntity());
                log.info("----认证结果result=========" + result);
                //认证返回的参数是否为空
                if (!StringUtils.isBlank(result)) {
                    Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
                    log.info("----certifRet=========" + map);
                    if (MapUtil.isNotEmpty(map) || resultCode.equals(map.get(ret))) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

