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

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.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.channel.yspay.utils.YspayKit;
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 YspayChannelRefundNoticeService extends AbstractChannelRefundNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {
        try {
            JSONObject reqParamJSON = getReqParamJSON();
            String payOrderId = reqParamJSON.getString("out_trade_no");
            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;
            log.info("【银盛】退款回调参数：{} ", jsonParams);
            // 校验支付回调
            boolean verifyResult = verifyParams(jsonParams, mchAppConfigContext);
            // 验证参数失败
            if(!verifyResult) {
                log.info("【银盛】验证参数失败， orderId:{}", refundOrder.getRefundOrderId());
                throw ResponseException.buildText("ERROR");
            }
            ResponseEntity okResponse = textResp("success");
            ChannelRetMsg result = new ChannelRetMsg();
            result.setResponseEntity(okResponse);
            result.setChannelOrderId(jsonParams.getString("trade_no"));
            result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            String trade_status = jsonParams.getString("trade_status");
            if(YspayKit.TRADE_PROCESS.equals(trade_status)){
                result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            }else if(YspayKit.TRADE_SUCCESS.equals(trade_status) || YspayKit.TRADE_PART_REFUND.equals(trade_status) || YspayKit.TRADE_ALL_REFUND.equals(trade_status)){
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
            }
            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;
        }
    }
}
