package com.jeequan.jeepay.thirdparty.channel.flpay;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ChannelException;
import com.jeequan.jeepay.core.model.DBPaymentConfig;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.thirdparty.channel.flpay.model.ReqEntity;
import com.jeequan.jeepay.thirdparty.channel.flpay.model.ReqMethod;
import com.jeequan.jeepay.thirdparty.channel.flpay.model.RespEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;

/**
 * TODO
 * 福禄打款
 * @author crystal
 * @date 2024/3/25 11:09
 */
@Slf4j
public class FlKit {

    /**
     * 发起请求
     * @param method
     * @param config
     * @param bizData
     * @return
     */
    public static JSONObject reqApi(ReqMethod.Method method, DBPaymentConfig config, JSONObject bizData) {
        ReqEntity reqEntity = initSign(config,bizData);
        String url = ReqMethod.getUrl(config,method);
        log.info("【福禄】请求参数：{}",JSON.toJSONString(reqEntity));
        HttpResponse response = HttpRequest.post(url).body(JSON.toJSONString(reqEntity)).execute();
        if(!response.isOk()){
            throw ChannelException.sysError("付款接口请求异常");
        }
        log.info("【福禄】返回参数：{}",response.body());
        RespEntity respEntity = JSON.parseObject(response.body(), RespEntity.class);
        return initResult(respEntity);
    }

    /**
     * 公共返回参数处理
     * @param resp
     * @return
     */
    public static JSONObject initResult(RespEntity resp) {
        if(!resp.isSuccess()){
            String msg = StringUtils.isNotEmpty(resp.getMsg()) ? resp.getMsg() : resp.getSubMsg();
            throw ChannelException.sysError(msg);
        }
        return JSON.parseObject(resp.getData());
    }

    public static ReqEntity initSign(DBPaymentConfig config,JSONObject bizData){
        bizData.put("taskNo", config.getTaskNo());
        bizData.put("appId", config.getAppId());
        ReqEntity reqEntity = new ReqEntity(config.getAppId(),bizData);
        reqEntity.setSign(genSign(reqEntity,config));
        return reqEntity;
    }

    /**
     * 校验回调签名
     * @param reqEntity
     * @param config
     * @return
     */
    public static boolean checkResultNotify(ReqEntity reqEntity, DBPaymentConfig config) {
        String sign =  genSign(reqEntity,config);
        return !sign.equalsIgnoreCase(reqEntity.getSign());
    }

    private static String genSign(ReqEntity reqEntity,DBPaymentConfig config) {
        String signStr = JeepayKit.getStrSort(reqEntity.toMap());
        //前5位
        String prefix = config.getSecret().substring(0,5);
        //后5位
        String suffix = config.getSecret().substring(config.getSecret().length() - 5);
        //拼接在首尾
        String signContent = prefix + signStr + suffix;
        try {
            String signText = DigestUtil.sha256Hex(signContent);
            byte[] secretSigning = DigestUtil.hmac(HmacAlgorithm.HmacSHA256, config.getSecret().getBytes(StandardCharsets.UTF_8)).digest(reqEntity.getTimestamp());
            String sign = DatatypeConverter.printHexBinary(DigestUtil.hmac(HmacAlgorithm.HmacSHA256,secretSigning).digest(signText)).toLowerCase();
            return sign;
        } catch (Exception e) {
            throw new BizException("生成签名异常");
        }
    }
}
