package com.ruoyi.common.valid.realName;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.http.AliHttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

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

/**
 * 实名认证工具类
 * @author wjh
 * 2024/8/30
 */
public class RealNameValidUtils {

    public static final String APP_KEY = SpringUtils.getRequiredProperty("realName.appKey");
    public static final String APP_CODE = SpringUtils.getRequiredProperty("realName.appCode");
    public static final String APP_SECRET = SpringUtils.getRequiredProperty("realName.appSecret");

    public static RealNameResponseData getMobile3Info(String idCard, String mobile, String name) {
        String host = "https://jmmobeck3.market.alicloudapi.com";
        String path = "/mobile/3-validate-beckoning";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idcard", idCard);
        bodys.put("mobile", mobile);
        bodys.put("name", name);

        try {
            HttpResponse res = AliHttpUtils.doPost(host, path, method, headers, querys, bodys);
            RealNameResponseBody body = JSON.parseObject(EntityUtils.toString(res.getEntity()), RealNameResponseBody.class);
            ServiceUtil.assertion(body.getCode() == null || !body.getCode().equals("200"), body.getMsg());
            return body.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 校验手机号三要素是否一致
    public static boolean validMobile3Info(String idCard, String mobile, String name) {
        RealNameResponseData mobile3Info = getMobile3Info(idCard, mobile, name);
        return mobile3Info != null && mobile3Info.getResult() != null && mobile3Info.getResult().equals("0");
    }

}
