package com.qxgmat.controller.gateway;

import com.nuliji.tools.MessageHelp;
import com.nuliji.tools.Response;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.help.ShiroHelp;
import com.qxgmat.help.WechatHelp;
import com.qxgmat.service.UsersService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/gateway/oauth")
public class OauthController {

    @Value("${third.redirectUrl}")
    private String redirectUrl;

    @Autowired
    private WechatHelp wechatHelp;

    @Autowired
    private ShiroHelp shiroHelp;

    @Autowired
    private UsersService usersService;


    @RequestMapping(value = "/wechat_pc", method = RequestMethod.GET)
    @ApiOperation(value = "微信二维码登录", httpMethod = "GET")
    public void wechatPc(
            @RequestParam(required = false, defaultValue = "") String jump,
            HttpSession session, HttpServletResponse response) throws IOException {
        session.setAttribute("jump", jump);
        response.sendRedirect(wechatHelp.redirectPc("state", redirectUrl+"/gateway/oauth/callback/wechat_pc"));
    }

    @RequestMapping(value = "/callback/wechat_pc", method = RequestMethod.GET)
    @ApiOperation(value = "微信二维码登录回调", httpMethod = "GET")
    public void callbackWechatPc(
            @RequestParam(required = false, defaultValue = "") String code,
            @RequestParam(required = false, defaultValue = "") String state,
            HttpSession session, HttpServletResponse response) throws IOException {
        User user = (User) shiroHelp.getLoginUser();
        if (user!=null){
            // 已登录用户，绑定
            usersService.Oauth(user, code, "wechat_pc");
        }
        shiroHelp.getSession().login(shiroHelp.oauth(code, "wechat_pc"));
        Object jump = session.getAttribute("jump");
        if (jump == null) {
            jump = "/";
        }else{
            session.removeAttribute("jump");
        }
        response.sendRedirect(jump.toString());
    }
}
