package com.ehking.demo.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.ehking.sdk.CipherWrapper;
import com.ehking.sdk.Constants;
import com.ehking.sdk.HttpClientUtils;
import com.ehking.sdk.exception.UnknownException;
import com.ehking.sdk.executer.Executer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyExecuter extends Executer {
    static final Logger LOGGER = LoggerFactory.getLogger(MyExecuter.class);

    public JSONObject ApiRequest(JsonBuilder jsonBuilder, String apiUrl) {
        try {
            JSONObject requestData = jsonBuilder.buildRequestParam();

            LOGGER.debug("API requestData:[" + requestData.toJSONString() + "]");
            //接口同步应答报文
            String responseStr = HttpClientUtils.post3(apiUrl, requestData);
            LOGGER.info("API responseStr :{}", responseStr);

            JSONObject responseData = JSONObject.parseObject(responseStr, new Feature[]{Feature.SortFeidFastMatch});
            if (Constants.ERROR.equals(responseData.getString(Constants.STATUS))) {
                //如果接口直接返回ERROR时，不需要解密
                return responseData;
            }

            //解密
            responseData = CipherWrapper.bothDecryptWrap(responseData);
            LOGGER.info("API response decrypt :{}", responseData);

            if (Constants.ERROR.equals(responseData.getString(Constants.STATUS))) {
                //解密后报文如果status=ERROR时，不需要验签
                return responseData;
            }

            //验签
            super.bothVerifyHmacOrder(responseData);

            LOGGER.info("API responseData :{}", responseStr);
            return responseData;

        } catch (Exception exception) {
            LOGGER.error("API request exception", exception);
            exception.printStackTrace();
            throw new UnknownException(exception);
        }
    }
}
