package com.ruoyi.xq.controller.app;

import com.ruoyi.common.core.domain.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/mp")
@Tag(name = "公众号相关接口")
@Validated
@Slf4j
public class MpController {

    @Autowired
    private WxMpService wxMpService;

    @Operation(summary = "公众号静默获取基础数据")
    @GetMapping("/auth/access_token")
    public R<WxOAuth2AccessToken> getAccessToken(@RequestParam(value = "code") String code) {
        try {
            return R.ok(wxMpService.getOAuth2Service().getAccessToken(code));
        } catch (WxErrorException e) {
            log.error("error", e);
            return R.fail("获取失败");
        }
    }

    @Operation(summary = "jsapi的授权")
    @GetMapping("/jsapi/token")
    public R<WxJsapiSignature> jsApiToken(@RequestParam(value = "url") String url) {
        try {
            WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(url);
            return R.fail(jsapiSignature);
        } catch (WxErrorException e) {
            log.error("error", e);
            return R.fail("获取失败");
        }
    }
}
