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.BizException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelJsapiMsg;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.thirdparty.channel.AbstractPaymentService;
import com.jeequan.jeepay.thirdparty.util.PaywayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * 银盛支付
 *
 * @author xiaoyu
 *
 * @date 2022/7/8 11:24
 */
@Slf4j
@Service
public class SxfpayPaymentService extends AbstractPaymentService {

    /**
     * 随行付花呗分期参数支持选项
     */
    public static final int[] ALI_HB_FQ_NUM_ARR = {3,6,12};

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

    @Override
    public boolean isSupport(String wayCode) {
        return false;
    }


    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        return PaywayUtil.getRealPaywayService(this, payOrder.getWayCode()).preCheck(rq, payOrder);
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        try {
            return PaywayUtil.getRealPaywayService(this, payOrder.getWayCode()).pay(rq, payOrder, mchAppConfigContext);
        }catch (Exception e){
            upException(payOrder.getPayOrderId(),e);
            throw e;
        }
    }

    public void preCheckAli(UnifiedOrderRQ rq) {
        Integer hbFqNum = rq.getHbFqNum();
        if(hbFqNum != null){
            boolean isCheck = Arrays.stream(ALI_HB_FQ_NUM_ARR).anyMatch(num -> num == hbFqNum);
            if(!isCheck){
                throw new BizException("支付宝支付花呗分期参数有误，仅可支持数值为"+ StringUtils.join(ALI_HB_FQ_NUM_ARR,",") +"期");
            }
            Integer hbFqPercent = rq.getHbFqPercent();
            if(hbFqPercent != null && hbFqPercent != 0){
                throw new BizException("花呗分期商家承担手续费比例目前只支持用户承担手续费");
            }
            rq.setHbFqPercent(0);
        }
    }

    /**
     * 统一返回参数解析
     * @param respBizData
     * @param res
     */
    public void initCommonResult(JSONObject respBizData, ChannelRetMsg res) {
        res.setChannelState(ChannelRetMsg.ChannelState.WAITING);
        res.setNeedQuery(true);
        res.setChannelBizData(respBizData);
        res.setChannelErrCode(respBizData.getString("bizCode"));
        res.setChannelErrMsg(respBizData.getString("bizMsg"));
        if(!SxfpayKit.SUCCESS_CODE.equals(respBizData.getString("bizCode")) && !SxfpayKit.EXT_SUCCESS_CODE.equals(respBizData.getString("bizCode"))){
            res.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            res.setNeedQuery(false);
        }else{
            ChannelJsapiMsg jsapiMsg = new ChannelJsapiMsg(respBizData.getString("source"));
            jsapiMsg.setAppId(respBizData.getString("payAppId"));
            jsapiMsg.setPaySign(respBizData.getString("paySign"));
            jsapiMsg.setTimeStamp(respBizData.getString("payTimeStamp"));
            jsapiMsg.setNonceStr(respBizData.getString("paynonceStr"));
            jsapiMsg.setPayPackage(respBizData.getString("payPackage"));
            jsapiMsg.setSignType(respBizData.getString("paySignType"));
            jsapiMsg.setRedirectUrl(respBizData.getString("redirectUrl"));
            String tranSts = respBizData.getString("tranSts");
            res.setPlatformOrderNo(respBizData.getString("transactionId"));
            res.setChannelOrderId(respBizData.getString("uuid"));
            res.setPlatformMchOrderNo(respBizData.getString("sxfUuid"));
            res.setChannelUserId(respBizData.getString("buyerId"));
            if("SUCCESS".equals(tranSts)){
                res.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                res.setNeedQuery(false);
                String drType = respBizData.getString("drType");
                if(StringUtils.isNotEmpty(drType)){
                    switch (drType){
                        case "1":
                            res.setDrType(CS.DrType.DEBIT.getType());
                            break;
                        case "2":
                            res.setDrType(CS.DrType.CREDIT.getType());
                            break;
                        default:
                            res.setDrType(CS.DrType.OTHER.getType());
                            break;
                    }
                }else{
                    res.setDrType(CS.DrType.OTHER.getType());
                }
            }else if("FAIL".equals(tranSts)){
                res.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                res.setNeedQuery(false);
            }
            res.setJsapiMsg(jsapiMsg);
        }
    }
}
