package com.jeequan.jeepay.thirdparty.service.wxmp;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.AccessMsgException;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.AppletResult;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.model.QRCodeParams;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.oauth2.WxpayOauth2Params;
import com.jeequan.jeepay.core.model.openapi.AccessError;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TODO
 * 微信托管相关业务处理
 * @author crystal
 * @date 2023/11/29 11:08
 */
@Service
public class WxTgAppletService {

    public final static String THIRD_ACCESS_TOEN = "authAccessToken";

    public final static String THIRD_COMPONENT_TOKEN = "componentToken";

    public final static String TG_API_DOMAIN = "https://xcx.shouyinbei.cn/prod-mini-api";

    @Autowired private ConfigContextQueryService configContextQueryService;

    @Autowired private WxLiteUrlLinkService wxLiteUrlLinkService;


    /**
     * 获取托管小程序支付参数
     * @param mchAppConfigContext
     * @return
     */
    public AppletResult toAppletPayment(PayOrder payOrder, MchAppConfigContext mchAppConfigContext,QRCodeParams qrCodeParams) {
        WxpayOauth2Params wxpayOauth2Params;
        if(mchAppConfigContext.isIsvsubMch()){
            // 先获取 特约商户的 小程序 配置信息
            wxpayOauth2Params = (WxpayOauth2Params) configContextQueryService.queryNormalOauth2Params(mchAppConfigContext.getMchApplyment().getIsvNo(), mchAppConfigContext.getMchApp().getAppId(), CS.IF_CODE.WXPAY);
            // 商户未配置 || 使用服务商的小程序时 ：  查询服务商的配置信息
            if(wxpayOauth2Params == null || wxpayOauth2Params.getIsUseSubmchAccount() == null ||  wxpayOauth2Params.getIsUseSubmchAccount() == CS.NO){
                // 查询服务商的配置，  判断取哪个 配置条目。
                // 查询商户 配置 的oauth2配置 ( 支付参数配置 )    selectOauth2InfoId: 配置的oauth2参数
                String ifCodeByMchPassage = configContextQueryService.queryIfCodeByPageType(mchAppConfigContext, QRCodeParams.PAGE_TYPE_WECHAT_LITE);
                String selectOauth2InfoId = configContextQueryService.queryAgentOrIsvSelectOauth2InfoId(mchAppConfigContext.getMchApplyment(), ifCodeByMchPassage);
                wxpayOauth2Params = (WxpayOauth2Params) configContextQueryService.queryIsvOauth2ParamsByAutoSelectOauth2InfoId(mchAppConfigContext.getMchApplyment().getIsvNo(), CS.IF_CODE.WXPAY, selectOauth2InfoId);
            }
        }else{
            wxpayOauth2Params = (WxpayOauth2Params)configContextQueryService.queryNormalOauth2Params(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), CS.IF_CODE.WXPAY);
        }
        if (wxpayOauth2Params == null || StringUtils.isBlank(wxpayOauth2Params.getLiteAppId()) || StringUtils.isBlank(wxpayOauth2Params.getLiteAppSecret())) {
            throw new BizException("请配置微信oauth2小程序参数");
        }
        String accessToken = getThirdAccessToken(wxpayOauth2Params.getLiteAppId());
        String query =  JeepayKit.TOKEN_KEY +"=" + qrCodeParams.getTk() + "&order_no="+payOrder.getPayOrderId() + "&price=" + AmountUtil.convertCent2Dollar(payOrder.getFindAmt()) + "&env=h5";
        wxpayOauth2Params.setLitePagePath("pages/payment/index");
        String schemeLink = wxLiteUrlLinkService.getSchemeLink(wxpayOauth2Params, accessToken, query, payOrder.getExpiredTime().getTime());
        AppletResult result = new AppletResult(wxpayOauth2Params,schemeLink,query);
        result.setStatus(payOrder.getState());
        return result;
    }

    public String getComponentToken(String appid) {
        return getAccessToken(appid,THIRD_COMPONENT_TOKEN);
    }

    public String getThirdAccessToken(String appid) {
        String accessToken = getAccessToken(appid, THIRD_ACCESS_TOEN);
        if(StringUtils.isEmpty(accessToken)){
            throw new AccessMsgException(AccessError.dataError("当前微信APPID["+appid+"]参数未授权到系统"));
        }
        return accessToken;
    }

    public String getAccessToken(String appid,String tokenName) {
        String url = TG_API_DOMAIN + "/api/open/cache/get?appid="+appid;
        String response = HttpUtil.get(url);
        if(StringUtils.isEmpty(response)){
            throw new BizException("接口异常");
        }
        JSONObject respData = JSON.parseObject(response);
        int code = respData.getIntValue("code");
        if(code != HttpStatus.HTTP_OK){
            throw new BizException(respData.getString("msg"));
        }
        JSONObject bizData = respData.getJSONObject("data");
        return bizData.getString(tokenName);
    }
}
