package org.cs.web.weixin;

import com.alibaba.fastjson.JSONObject;
import org.cs.constants.Constants;
import org.cs.core.ctl.BaseCtl;
import org.cs.mgr.user.service.IMgmUserService;
import org.cs.util.StringUtil;
import org.cs.web.weixin.ws.HrmUserWsInvok;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.util.Map;

/**
 * 单纯实现OAuth2验证，不使用注解及拦截器
 * Created by zhaoxinguo on 2017/7/11.
 */
@Controller
public class SimpleOAuth2Controller extends BaseCtl{

    private Logger logger = LoggerFactory.getLogger(SimpleOAuth2Controller.class);

    @Autowired
    private HrmUserWsInvok hrmUserWsInvok;
    @Autowired
    private IMgmUserService mgmUserService;
    /**
     * 拼接网页授权链接
     * 此处步骤也可以用页面链接代替
     * @return
     */
    @RequestMapping(value = { "/oauth2wx" })
    public String Oauth2API(HttpServletRequest request){
        //获取项目域名
        String requestUrl = request.getServerName();
        String contextPath = request.getContextPath();
        logger.info("domain name: " + requestUrl + " project name: " + contextPath);
        //拼接微信回调地址
        String backUrl ="http://" + requestUrl + contextPath + "/oauth2me.cs";
        String redirect_uri = "";
        try {
            redirect_uri = java.net.URLEncoder.encode(backUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("ecdoe error: " + e.getMessage());
        }
        String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinQiYeConstants.CORPID + "&redirect_uri=" + redirect_uri
                + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        return "redirect:" + oauth2Url;
    }

    /**
     * 授权回调请求处理
     * @return
     */
    @RequestMapping(value = { "/oauth2me" })
    public String oAuth2Url(HttpServletRequest request, @RequestParam String code){
        // 调用获取access_token的接口
        AccessToken accessToken = WeiXinQiYeUtil.access_token();
        HttpSession session = request.getSession();
        if (accessToken != null && accessToken.getAccess_token() != null) {
            // 调用获取用户信息的接口
            String UserId = getMemberGuidByCode(accessToken.getAccess_token(), code, WeiXinQiYeConstants.AGENTID);
            logger.info("UserId: " + UserId);
            if (StringUtil.isNotBlank(UserId)) {
                session.setAttribute("UserId", UserId);
                com.alibaba.fastjson.JSONObject json = null;
                try {
                    json = hrmUserWsInvok.getUserRet(UserId);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                if(json != null && "1".equals(json.get("ret")) && "1".equals(json.get("status"))){
                    Map<String, Object> user = mgmUserService.getUserMap(json.get("personcode").toString());
                    if(user == null){
                        return "app/login/login";
                    }
                    JSONObject userJson = getJson(1, user, null);
                    Map<String, String> user0 = getMapFromJson(userJson.getJSONObject("data").toString());
                    request.getSession().setAttribute(Constants.SESSION_WEB_USER, user0);
                    logger.info("UserId放入session成功!");
                    return "app/weixin_index";
                }else{
                    return "app/login/login";
                }
            }else{
                return "app/login/login";
            }
        }else{
            return "app/login/login";
        }
        // 这里简单处理,存储到session中
        //return "app/weixin_index";
    }

    /**
     * 调用接口获取用户信息
     *
     * @param token
     * @param code
     * @return
     */
    public String getMemberGuidByCode(String token, String code, String agentId) {
        logger.info("code==" + code + " token=" + token + " agentId=" +agentId);
        Result result = WeiXinQiYeUtil.oAuth2GetUserByCode(token, code, agentId);
        logger.info("result= " + result);
        if (result.getErrcode().equals("0")) {
            if (result.getUserId() != null  && result.getUserId().length() > 0) {
                // 此处可以通过微信授权用code还钱的Userid查询自己本地服务器中的数据
                return result.getUserId();
            }
        }
        return "";
    }
}