package com.hzs.third.bankcard.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.domain.R;
import com.hzs.third.bankcard.dto.BankCardParam;
import com.hzs.third.bankcard.service.IBankCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * 银行卡验证接口
 */
@Slf4j
@Service
public class IBankCardServiceImpl implements IBankCardService {

    @Value("${bankCard.url}")
    private String url;
    @Value("${bankCard.appKey}")
    private String appKey;
    @Value("${bankCard.appCode}")
    private String appCode;

    @Override
    public R<?> verifyBankCard(BankCardParam bankCardParam) {
        Map<String, Object> param = new HashMap<>();
        param.put("bankcard", bankCardParam.getBankCard());
        param.put("idcard", bankCardParam.getIdCard());
        param.put("name", bankCardParam.getName());
        param.put("mobile", bankCardParam.getMobile());

        HttpResponse response = HttpRequest.post(url)
                .header(Header.AUTHORIZATION, "APPCODE " + appCode)
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8")
                .form(param)
                .timeout(10000)
                .execute();
        return parseResult(response);
    }

    /**
     * 解析返回的结果集
     */
    private R<?> parseResult(HttpResponse response) {
        String result = response.body();
        log.info("调用银行卡认证接口返回信息： " + result);

        if (HttpStatus.SUCCESS == response.getStatus()) {
            JSONObject resultObj = JSONUtil.parseObj(result);
            if ("200".equals(resultObj.getStr("code"))) {
                // 返回成功
                JSONObject dataObj = resultObj.getJSONObject("data");
                int resultInt = dataObj.getInt("result");
                if (resultInt == 0) {
                    // 一致
                    return R.ok();
                } else if (resultInt == 1) {
                    // 不一致
                    return R.fail("银行卡预留信息不一致，请确认后重试");
                } else {
                    // 查不到卡信息
                    return R.fail("银行卡信息不存在，请确认银行卡是否有效");
                }
            } else {
                // 返回失败
                return R.fail(resultObj.getStr("msg"));
            }
        } else {
            log.error("调用银行卡认证接口失败");
            return R.fail("银行卡认证失败，请重试");
        }
    }

}
