package com.yonge.toolset.thirdparty.user.realname.provider;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.thirdparty.user.realname.RealnameAuthenticationPlugin;
import com.yonge.toolset.utils.http.HttpUtil;

@Service
public class LinkfaceRealnameAuthenticationPlugin implements RealnameAuthenticationPlugin {

    private final static Logger log = LoggerFactory.getLogger(LinkfaceRealnameAuthenticationPlugin.class);

    @Value("${realnameAuthentication.linkface.projectid:2cd4937c8dbd4f6a9c70c6d3122df5f4}")
    public String appId;

    @Value("${realnameAuthentication.linkface.projectSecret:3f809f3800654780beff1ce09b780297}")
    public String appSecret;

    @Value("${realnameAuthentication.linkface.apisUrl:https://cloudapi.linkface.cn/data/verify_id_name}")
    public String apisUrl;

    private Map<String, String> reason = new HashMap<String, String>() {
        /**
         *
         */
        private static final long serialVersionUID = -5123335186604042998L;

        {
            // 定义错误原因
            put("ENCODING_ERROR", "参数非 UTF-8 编码");
            put("INVALID_ARGUMENT", "姓名或者身份证号填写错误");
            put("UNAUTHORIZED", "账号或密钥错误");
            put("KEY_EXPIRED", "账号过期");
            put("RATE_LIMIT_EXCEEDED", "调用频率过高");
            put("OUT_OF_QUOTA", "调用次数超出限额");
            put("NO_PERMISSION", "无调用权限");
            put("NOT_FOUND", "请求路径错误");
            put("DATA_SERVER_ERROR", "数据服务异常");
            put("INTERNAL_ERROR", "内部服务异常");
        }
    };

    public static String getName() {
        return "linkface";
    }

    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(appSecret) || StringUtils.isBlank(apisUrl)) {
            throw new ThirdpartyException("实名认证插件 - Linkface 系统参数缺失，请检查");
        }

    }

    @Override
    public boolean verify(String realname, String idcardNo) {
        String respJson = "";
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("api_id", appId);
        params.put("api_secret", appSecret);
        params.put("name", realname);
        params.put("id_number", idcardNo);
        try {
            respJson = HttpUtil.postForHttps(this.apisUrl, params);
        } catch (Exception e) {
            log.error("实名认证接口请求失败，参数：{}，异常信息：{}", JSONObject.toJSONString(params), e.getMessage());
            e.printStackTrace();
            throw new ThirdpartyException("实名认证请求失败");
        }
        JSONObject json = JSONObject.parseObject(respJson);

        String status = json.get("status").toString();
        Integer result = json.get("result") == null ? null : Integer.parseInt(json.get("result").toString());

        // 获取返回码
        if (StringUtils.equals("OK", status) && (result != null && result == 1)) {
            return true;
        } else {
            String msg = "";
            if (result != null) {
                if (result == 2) {
                    msg = "身份证号和姓名不一致";
                } else if (result == 3) {
                    msg = "查无此身份证号";
                }
            } else {
                //msg = reason.get(status);
                msg = "身份证号和姓名不一致";
            }
            throw new ThirdpartyException("实名认证失败，原因：{}", msg);
        }
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

    public void setApisUrl(String apisUrl) {
        this.apisUrl = apisUrl;
    }

	/*public static void main(String[] args) {
		LinkfaceRealnameAuthenticationPlugin plugin = new LinkfaceRealnameAuthenticationPlugin();
		plugin.setAppId("2cd4937c8dbd4f6a9c70c6d3122df5f4");
		plugin.setAppSecret("3f809f3800654780beff1ce09b780297");
		plugin.setApisUrl("https://cloudapi.linkface.cn/data/verify_id_name");

		System.out.println(plugin.verify("王武", "411526199706013217"));
	}*/
}
