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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.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.WxJsapiOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxJsapiOrderRS;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.channel.lklspay.LklspayKit;
import com.jeequan.jeepay.thirdparty.channel.lklspay.LklspayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklPayMethod;
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/4/15 15:37
 */
@Slf4j
@Service("lklspayPaymentByWxJsapiService") //Service Name需保持全局唯一性
public class WxJsapi extends LklspayPaymentService {

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

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

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        WxpayOauth2Params oauth2Params = (WxpayOauth2Params) configContextQueryService.queryIsvOauth2Params(mchAppConfigContext.getMchApplyment().getIsvNo(), CS.IF_CODE.WXPAY);
        WxJsapiOrderRS res = ApiResBuilder.buildSuccess(WxJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        WxJsapiOrderRQ bizRQ = (WxJsapiOrderRQ) rq;
        JSONObject bizContent = new JSONObject();
        LklspayKit.setPayParams(mchAppConfigContext, bizContent,payOrder.getClientIp());
        bizContent.put("out_trade_no",payOrder.getPayOrderId());
        bizContent.put("account_type","WECHAT");
        bizContent.put("trans_type","51");
        bizContent.put("total_amount",payOrder.getFindAmt());
        bizContent.put("subject",payOrder.getSubject());
        bizContent.put("notify_url",getNotifyUrl());
        bizContent.put("remark",payOrder.getBuyerRemark());
        JSONObject acc_busi_fields = new JSONObject();
        String expiredTime = DateUtil.formatBetween(DateUtil.between(payOrder.getCreatedAt(), payOrder.getExpiredTime(), DateUnit.MINUTE)).replace("毫秒", "");
        acc_busi_fields.put("timeout_express",expiredTime);
        if(StringUtils.isNotEmpty(bizRQ.getSubAppid())){
            acc_busi_fields.put("sub_appid",bizRQ.getSubAppid());
        }else{
            acc_busi_fields.put("sub_appid",oauth2Params.getAppId());
        }
        acc_busi_fields.put("user_id",bizRQ.getOpenid());
        if(bizRQ.getLimitPay() != null &&  bizRQ.getLimitPay() == 1){
            acc_busi_fields.put("limit_pay","no_credit");
        }
        bizContent.put("acc_busi_fields",acc_busi_fields);
        JSONObject response = LklspayKit.payRequest(LklPayMethod.Api.TRANS_PREORDER, mchAppConfigContext.getMchApplyment(), bizContent);
        JSONObject payInfo = this.initResult(response, channelRetMsg);
        if(payInfo != null){
            res.setPayInfo(JSON.toJSONString(channelRetMsg.getJsapiMsg()));
            res.setPayData(JSON.toJSONString(channelRetMsg.getJsapiMsg()));
        }
        res.setChannelRetMsg(channelRetMsg);
        return res;
    }

    public static void main(String[] args) {
        String ss = "{\"merchant_no\":\"8225210899900F0\",\"out_trade_no\":\"P1742858341545418753\",\"trade_no\":\"20240104110113130266215741766678\",\"log_no\":\"66215741766678\",\"settle_merchant_no\":\"\",\"settle_term_no\":\"\",\"acc_resp_fields\":{\"code\":\"\",\"code_image\":\"\",\"prepay_id\":\"wx041839451311948c0cb2454b2063190000\",\"app_id\":\"wx45c4343397131a20\",\"pay_sign\":\"rkUQ35bhG9LBmAKF2X1LhSDSrvyCWOnt0+teVcJ6xD0l5fEC4zfhJ/PEhGIis3xoM4Smjp6WDt5P3q0Eh+dCF8DjYVk1FnYNrw2XuXJ1LLr9iyW5YCDKlzFrfacR+FtGKgipNcnCJZfd+OtB6g3Fi34aaYFJVfyDZ+hJt05tEe46nWUIjDV1EsjHG6WlAwPiJgbwKcCEZwUMRCOvKXPoXfkmQTGsySJN1Iiv37sTr9dwJ+cyFUu6G+fJneFg85uftnqfYw4x9JJc/wiBvE28z1eHTHDLg7RvI4GOarwMWhDaJF2rEqVmnSW8PZvYn/SXSSvW1CLSGBkThz/kp6f4pQ==\",\"time_stamp\":\"1704364785\",\"nonce_str\":\"c8a228e920bd46c6a5db3b5b2bdd4d9d\",\"package\":\"prepay_id=wx041839451311948c0cb2454b2063190000\",\"sign_type\":\"RSA\",\"redirect_url\":\"\",\"best_pay_info\":\"\"}}";
        JSONObject bizData = JSON.parseObject(ss);
        WxJsapiOrderRS res = ApiResBuilder.buildSuccess(WxJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        WxJsapi jsapi = new WxJsapi();
        JSONObject payInfo = jsapi.initResult(bizData, channelRetMsg);
        if(payInfo != null){
            JSONObject outPayInfo = new JSONObject();
            outPayInfo.put("appId",payInfo.getString("app_id"));
            outPayInfo.put("nonceStr",payInfo.getString("nonce_str"));
            outPayInfo.put("timeStamp",payInfo.getString("time_stamp"));
            outPayInfo.put("package",payInfo.getString("package"));
            outPayInfo.put("signType",payInfo.getString("sign_type"));
            outPayInfo.put("paySign",payInfo.getString("pay_sign"));
            outPayInfo.put("prepayId",payInfo.getString("prepay_id"));
            res.setPayInfo(outPayInfo.toString());
        }
        res.setChannelRetMsg(channelRetMsg);

        System.out.println("ret"+JSON.toJSONString(channelRetMsg));
        System.out.println("res"+JSON.toJSONString(res));
    }
}
