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

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.exception.ChannelException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.oauth2.WxpayOauth2Params;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxLiteOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxLiteOrderRS;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.channel.dgpay.DgPayKit;
import com.jeequan.jeepay.thirdparty.channel.dgpay.DgpayPaymentService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 斗拱 微信jsapi
 *
 * @author xiaoyu
 *
 * @date 2022/6/13 17:52
 */
@Slf4j
@Service("dgpayPaymentByWxLiteService") //Service Name需保持全局唯一性
public class WxLite extends DgpayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {

        WxLiteOrderRQ bizRQ = (WxLiteOrderRQ) rq;
        if(StringUtils.isEmpty(bizRQ.getOpenid())){
            throw new BizException("[openId]不可为空");
        }

        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        WxLiteOrderRS res = ApiResBuilder.buildSuccess(WxLiteOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);
        try {

            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            WxpayOauth2Params oauth2Params = (WxpayOauth2Params) configContextQueryService.queryIsvOauth2Params(mchAppConfigContext.getMchApplyment().getIsvNo(), CS.IF_CODE.WXPAY);

            // 设置请求参数
            WxLiteOrderRQ bizRQ = (WxLiteOrderRQ) rq;
            JSONObject dataParams = DgPayKit.dataParams(payOrder, getNotifyUrl());
            dataParams.put("trade_type", "T_MINIAPP");

            JSONObject wxJson = new JSONObject();
            wxJson.put("sub_appid", oauth2Params.getLiteAppId());
            wxJson.put("sub_openid", bizRQ.getChannelUserId());

            // 接口上传的appId
            if (StringUtils.isNotEmpty(bizRQ.getSubAppid())) {
                wxJson.put("sub_appid", bizRQ.getSubAppid());
            }
            dataParams.put("wx_data", wxJson.toJSONString());

            // 设置订单是否需要分账
            if(isDivisionOrder(payOrder)) {
                dataParams.put("delay_acct_flag", "Y");
            }

            JSONObject response = DgPayKit.payRequest(mchAppConfigContext, dataParams, "/trade/payment/jspay", payOrder.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            channelRetMsg.setChannelBizData(resData);
            String code = resData.getString("resp_code");
            if(DgPayKit.STATE_ING.equals(code)){
                String channelOrderNo = resData.get("hf_seq_id").toString();
                //付款信息
                String payInfo = resData.getString("pay_info");
                channelRetMsg.setChannelOrderId(channelOrderNo);
                // 获取payInfo
                res.setPayInfo(payInfo);
                res.setPayData(payInfo);
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                // 开启轮询查单
                channelRetMsg.setNeedQuery(true);
            }else {  //其他状态, 表示下单失败

                DgPayKit.channelMsgError(resData, channelRetMsg);
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            }
        }catch (Exception e) {
            log.error(e.getMessage());
            throw ChannelException.sysError(e.getMessage());
        }
        return res;
    }

}
