package com.izouma.awesomeadmin.web;

import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.UserInfoService;
import com.izouma.awesomeadmin.service.WeiXinService;
import com.izouma.awesomeadmin.shiro.WechatToken;
import com.izouma.awesomeadmin.util.Base64;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import com.izouma.awesomeadmin.util.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WeiXinController {

    private static Logger logger = Logger.getLogger(WeiXinController.class);

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView auth(@RequestParam("redirectUri") String redirectUri) {
        if (StringUtils.isNotEmpty(redirectUri)) {
            redirectUri = Base64.getBase64(redirectUri);
        } else {
            redirectUri = "";
        }
        String wxRedirectUri = PropertiesFileLoader.getProperties("host")
                + "/wx/doAuth/" + redirectUri;
        return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                + PropertiesFileLoader.getProperties("weixinappid")
                + "&redirect_uri=" + wxRedirectUri
                + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
    }

    @RequestMapping("/doAuth/{redirectUri}")
    public ModelAndView doAuth(@RequestParam("code") String code, @PathVariable("redirectUri") String redirectUri) {
        ModelAndView modelAndView;
        if (StringUtils.isNotEmpty(redirectUri)) {
            redirectUri = Base64.getFromBase64(redirectUri);
            modelAndView = new ModelAndView("redirect:" + redirectUri);
        } else {
            redirectUri = "";
            modelAndView = new ModelAndView("redirect:/");
        }
        Subject subject = SecurityUtils.getSubject();
        WechatToken wechatToken = new WechatToken(code);
        try {
            subject.login(wechatToken);
        } catch (Exception e) {
            logger.error("doAuth", e);
            modelAndView = new ModelAndView("redirect:" + PropertiesFileLoader.getProperties("host")
                    + "/wx/auth?redirectUri=" + redirectUri);
        }
        return modelAndView;
    }

    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getSignature(HttpServletRequest request) {

        String shareUrl = request.getParameter("shareUrl");
        return weiXinService.getSignature(shareUrl);

    }

    @RequestMapping(value = "/checkSubscribe", method = RequestMethod.GET)
    @ResponseBody
    public Result checkSubscribe(@RequestParam("userId") String userId) {

        UserInfo userInfo = new UserInfo();
        userInfo.setId(Integer.valueOf(userId));
        userInfo = userInfoService.getUserInfo(userInfo);
        try {
            JSONObject jsonObject = WeixinUtil.loadJSON("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + weiXinService.getAccessToken()
                    + "&openid=" + userInfo.getOpenId());
            int subscribe = jsonObject.getInt("subscribe");
            if (subscribe == 1) {
                return new Result(true, null);
            } else {
                return new Result(false, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, null);
    }
}
