package com.neusoft.smart.pos.wxopen.controller;

import com.neusoft.smart.pos.wxopen.service.WxOpenService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerInfoResult;
import me.chanjar.weixin.open.bean.result.WxOpenQueryAuthResult;
import org.springframework.beans.factory.annotation.Autowired;
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;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("api")
public class WechatApiController {
    @Autowired
    private WxOpenService wxOpenService;

    @GetMapping("auth/goto_auth_url")
    public void gotoPreAuthUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, WxErrorException {
        String host = request.getHeader("host");
        String url = "http://" + host + "/api/auth/jump";
        url = wxOpenService.getWxOpenComponentService().getPreAuthUrl(url);
        response.sendRedirect(url);
    }

    @GetMapping("auth/jump")
    public WxOpenQueryAuthResult jump(@RequestParam("auth_code") String authorizationCode) throws WxErrorException {
        return wxOpenService.getWxOpenComponentService().getQueryAuth(authorizationCode);
    }

    @GetMapping("get_authorizer_info")
    public WxOpenAuthorizerInfoResult getAuthorizerInfo(@RequestParam String appId) throws WxErrorException {
        return wxOpenService.getWxOpenComponentService().getAuthorizerInfo(appId);
    }
}