package com.ruoyi.common.valid.bank;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
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;
import java.util.Objects;

/**
 * 银行卡工具类
 * @author wjh
 * 2024/3/27
 */
public class BankValidUtils {

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

    public static BankCardInfo valid3Bank(String bankCard, String name, String idCard) {
        ServiceUtil.assertion(StringUtils.hasBlank(bankCard, name, idCard), "调用三要素参数错误：银行卡、姓名或身份证存在空值");

        String host = "https://zball.market.alicloudapi.com";
        String path = "/v3/bcheck";
        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("accountNo", bankCard);
        bodys.put("name", name);
        bodys.put("idCardCode", idCard);

        try {
            HttpResponse res = AliHttpUtils.doPost(host, path, method, headers, querys, bodys);
            BankValidResponseBody body = JSON.parseObject(EntityUtils.toString(res.getEntity()), BankValidResponseBody.class);

            ServiceUtil.assertion(body.getErrorCode() != 0 || body.getResult() == null, "调用三要素API查询失败");
            ServiceUtil.assertion(!Objects.equals(body.getResult().getRespCode(), "0"), body.getResult().getRespMsg());

            return body.getResult().getBankCardInfo();

        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

}
