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

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.sxfpay.SxfpayIsvParams;
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.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 SxfpayChannelNoticeService extends AbstractChannelNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {

        try {
            JSONObject reqParamJSON = getReqParamJSON();
            String payOrderId = reqParamJSON.getString("ordNo");
            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);
            boolean verifyResult = verifyParams(respJson, mchAppConfigContext, payOrder);
            // 验证参数失败
            if(!verifyResult){
                throw ResponseException.buildText("error");
            }
            //验签成功后判断上游订单状态
            ResponseEntity okResponse = jsonResp(SxfpayKit.ok());
            ChannelRetMsg result = new ChannelRetMsg();
            result.setResponseEntity(okResponse);
            result.setChannelBizData(respJson);
            result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
            result.setChannelUserId(respJson.getString("openid"));
            result.setChannelOrderId(respJson.getString("uuid"));
            //如果是支付宝 则需要去除前两位
            result.setPlatformOrderNo(respJson.getString("transactionId"));
            result.setPlatformMchOrderNo(respJson.getString("sxfUuid"));
            String drType = respJson.getString("drType");
            if(StringUtils.isNotEmpty(drType)){
                switch (drType){
                    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());
            }
            return result;
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }


    /**
     * 验证随行付支付通知参数
     * @return
     */
    public boolean verifyParams(JSONObject jsonParams, MchAppConfigContext mchAppConfigContext, PayOrder payOrder) {
        try {
            String logPrefix = "【处理[随行付]支付回调】";
            log.info("{} 回调参数: jsonParams：{}", logPrefix, jsonParams);
            String sign = jsonParams.getString("sign");
            if (StringUtils.isEmpty(sign)) {
                log.info("验签参数为空：sign：{}", sign);
                return false;
            }
            // 校验支付回调
            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            SxfpayIsvParams isvParams = (SxfpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment().getIsvNo(), payOrder.getIfCode());
            return SxfpayKit.checkSign(jsonParams, isvParams);
        }catch (Exception e) {
            log.error("验证签名异常", e);
            return false;
        }
    }
}
