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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.ruipay.RyxpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.channel.AbstractChannelNoticeService;
import com.jeequan.jeepay.thirdparty.channel.ryxpay.model.PayRespEntity;
import com.jeequan.jeepay.thirdparty.channel.ryxpay.model.ReqMethod;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
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;

/**
 * 瑞银信 回调接口实现类
 */
@Service
@Slf4j
public class RyxpayChannelNoticeService extends AbstractChannelNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {
        try {
            JSONObject reqParamJSON = getReqParamJSON();
            String payOrderId = reqParamJSON.getString("reqMsgId");
            return MutablePair.of(payOrderId, reqParamJSON);
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, PayOrder payOrder, MchAppConfigContext mchAppConfigContext, NoticeTypeEnum noticeTypeEnum) {
        try {
            JSONObject respJson = (JSONObject) JSONObject.toJSON(params);
            //验证签名 并且解析参数
            PayRespEntity notifyData = verifyParams(respJson, mchAppConfigContext, payOrder);
            //验签成功后判断上游订单状态
            ResponseEntity okResponse = textResp(RyxpayKit.SUCCESS_CODE);
            ChannelRetMsg result = new ChannelRetMsg();
            result.setResponseEntity(okResponse);
            result.setChannelBizData(respJson);
            result.setChannelErrCode(notifyData.getRespCode());
            result.setChannelErrMsg(notifyData.getRespMsg());
            result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
            result.setChannelUserId(notifyData.getData().getString("buyerId"));
            result.setChannelOrderId(notifyData.getSmzfMsgId());
            //如果是支付宝 则需要去除前两位
            result.setPlatformOrderNo(notifyData.getData().getString("channelTradeNo"));
            result.setPlatformMchOrderNo(notifyData.getChannelMsgId());
            String payType = notifyData.getData().getString("payType");
            if(StringUtils.isNotEmpty(payType)){
                switch (payType){
                    case "1":
                        result.setDrType(CS.DrType.DEBIT.getType());
                        break;
                    case "2":
                        result.setDrType(CS.DrType.CREDIT.getType());
                        break;
                    default:
                        result.setDrType(CS.DrType.OTHER.getType());
                        break;
                }
            }else{
                result.setDrType(CS.DrType.OTHER.getType());
            }
            String respType = notifyData.getRespType();
            if(RyxpayKit.RESP_BIZ_FAIL.equals(respType)){
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            }else if(RyxpayKit.RESP_BIZ_ING.equals(respType)){
                result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            }
            return result;
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }


    /**
     * 解析瑞银信参数
     * @return
     */
    public PayRespEntity verifyParams(JSONObject params, MchAppConfigContext mchAppConfigContext, PayOrder payOrder) {
        String logPrefix = "【处理[瑞银信]支付回调】";
        log.info("{}回调参数: jsonParams：{}", logPrefix, params);
        // 校验支付回调
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        RyxpayIsvParams isvParams = (RyxpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment().getIsvNo(), payOrder.getIfCode());
        return RyxpayKit.resultParamsDecode(params, isvParams);
    }
}
