package com.ruoyi.front.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.ruoyi.front.enums.EnvVersion;
import com.ruoyi.front.service.IWxService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * 微信小程序服务类
 * @author 金鹏
 */
@Service
@RequiredArgsConstructor
@ConditionalOnBean(WxMaService.class)
public class WxMiniAppServiceImpl implements IWxService {

    private final WxMaService wxMaService;

    /**
     * 根据授权码获取用户OpenId
     * @param jsCode 获取用户openid授权码
     * @return 用户OpenId
     * @throws WxErrorException 微信API通信异常信息
     */
    @Override
    public String getOpenId(String jsCode) throws WxErrorException {
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(jsCode);
       return wxMaJscode2SessionResult.getOpenid();
    }
    /**
     * 根据授权码获取用户OpenId
     * @param code 获取用户手机后授权码
     * @return 微信用户手机号
     * @throws WxErrorException 微信API通信异常信息
     */
    @Override
    public String getPhoneNumber(String code) throws WxErrorException {
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNumber(code);
        return phoneNoInfo.getPhoneNumber();
    }

    /**
     * 根据授权码获取用户OpenId
     * @param scene 获取用户手机后授权码
     * @return 微信用户手机号
     */
    @Override
    public File createWxaCode(String scene, String page, EnvVersion envVersion) throws WxErrorException {
        return wxMaService.getQrcodeService().createWxaCodeUnlimit(scene, page, false, envVersion.getValue(), 430, true, null, false);
    }

}
