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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.RefundOrder;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvParams;
import com.jeequan.jeepay.core.model.params.yspay.YspayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.channel.AbstractChannelRefundNoticeService;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.SignRsaUtil;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.SignSmUtil;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import com.jeequan.jeepay.thirdparty.util.ChannelCertConfigKitBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.util.Map;

/**
 * 斗拱退款回调接口实现类
 *
 * @author xiaoyu
 *
 * @date 2021/12/24 11:31
 */
@Service
@Slf4j
public class DgpayChannelRefundNoticeService extends AbstractChannelRefundNoticeService {

    @Override
    public String getIfCode() {
        return CS.IF_CODE.DGPAY;
    }

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {
        try {
            // 回调参数body【回调参数顺序固定】
            JSONObject reqParamJSON = getReqParamJSON();
            JSONObject dataJson = reqParamJSON.getJSONObject("resp_data");
            String payOrderId = dataJson.getString("req_seq_id");
            return MutablePair.of(payOrderId, reqParamJSON);
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, RefundOrder refundOrder, MchAppConfigContext mchAppConfigContext, NoticeTypeEnum noticeTypeEnum) {
        try {
            // 获取请求参数
            JSONObject jsonParams = (JSONObject) params;
            String dataJson = jsonParams.getString("resp_data");
            String sign = jsonParams.getString("sign");
            log.info("【斗拱】退款回调参数：{} ", jsonParams);
            // 公钥参数
            DgpayIsvParams isvParams = (DgpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment());
            // 验证签名
            boolean verifyResult = DgPayKit.verify(dataJson, isvParams.getRsaPublicKey(), sign);
            //验签失败
            if(!verifyResult){
                throw ResponseException.buildText("ERROR");
            }
            //验签成功后判断上游订单状态
            ResponseEntity okResponse = textResp("SUCCESS");
            ChannelRetMsg result = new ChannelRetMsg();
            // 默认退款中
            result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            // 获取请求参数
            JSONObject respData = jsonParams.getJSONObject("resp_data");
            if(DgPayKit.STATE_SUCCESS_S.equals(respData.getString("trans_stat"))){
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);

            }else if(DgPayKit.STATE_FAIL_F.equals(respData.getString("trans_stat"))){
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                // 交易状态失败存储
                DgPayKit.channelMsgError(respData, result);
            }
            result.setResponseEntity(okResponse);
            result.setChannelOrderId(respData.getString("hf_seq_id"));
            result.setPlatformMchOrderNo(respData.getString("party_order_id"));
            return result;
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }


    /**
     * 验证银盛退款通知参数
     * @return
     */
    public boolean verifyParams(JSONObject jsonParams, MchAppConfigContext mchAppConfigContext) {
        try {
            log.info("【银盛】退款回调参数: jsonParams：{}", jsonParams);
            String sign = jsonParams.getString("sign");
            Map<String, String> paramsMap = jsonParams.toJavaObject(Map.class);
            if (StringUtils.isEmpty(sign)) {
                log.info("验签参数为空：sign：{}", sign);
                return false;
            }
            // 校验支付回调
            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment());
            // 证书地址
            ChannelCertConfigKitBean channelCertConfigKitBean = SpringBeansUtil.getBean(ChannelCertConfigKitBean.class);
            String certFilePath = channelCertConfigKitBean.getCertFilePath(isvParams.getPublicKeyFile());
            boolean verifyResult = false;
            if ("RSA".equals(isvParams.getSignType())) {
                FileInputStream fileInputStream = new FileInputStream(channelCertConfigKitBean.getCertFile(isvParams.getPublicKeyFile()));
                verifyResult = SignRsaUtil.asynVerifyYsRsa(fileInputStream, paramsMap);
            }else if ("SM".equals(isvParams.getSignType())){
                verifyResult = SignSmUtil.asynVerifyYsSm(certFilePath, paramsMap);
            }else {
                log.error("未识别的签名类型");
            }
            //验签失败
            if(!verifyResult) {
                log.info("【银盛】退款回调验签失败！ 回调参数：parameter = {} ", jsonParams);
                return false;
            }
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
