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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayOpenAuthTokenAppModel;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IMchAutoAuthService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.thirdparty.model.AlipayClientWrapper;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
* 支付宝： 商户授权实现类
*
* @author terrfly
*
* @date 2021/6/8 17:21
*/
@Service
@Slf4j
public class AlipayMchAutoAuthService implements IMchAutoAuthService {

    @Autowired private ConfigContextQueryService configContextQueryService;


    @Override
    public JSONObject mchAuth(MchAppConfigContext mchAppConfigContext, String appAuthCode) {

        AlipayClientWrapper alipayClientWrapper = configContextQueryService.getAlipayClientWrapper(mchAppConfigContext);

        AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
        AlipayOpenAuthTokenAppModel model = new AlipayOpenAuthTokenAppModel();
        model.setGrantType("authorization_code");
        model.setCode(appAuthCode);
        request.setBizModel(model);

        // expiresIn: 该字段已作废，应用令牌长期有效，接入方不需要消费该字段
        // reExpiresIn: 刷新令牌的有效时间（从接口调用时间作为起始时间），单位到秒
        // DateUtil.offsetSecond(new Date(), Integer.parseInt(resp.getExpiresIn()));
        AlipayOpenAuthTokenAppResponse resp = alipayClientWrapper.execute(request);
        if(!resp.isSuccess()){
            throw new BizException(AlipayKit.appendErrMsg(resp.getMsg(), resp.getSubMsg()));
        }

        return (JSONObject) JSON.toJSON(resp);
    }
}
