package com.wechat.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.wechat.common.Constants;
import com.wechat.common.utils.MvcUtil;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dto.WxUserInfoDto;
import com.wechat.model.responseDto.JsonResp;
import com.wechat.service.GroupService;
import com.wechat.service.WeiXinService;


/**
 * FAQ问答
 * 
 */
@Controller
@RequestMapping("group")
public class GroupController extends BaseController {

    //菜单设置
    @Value("#{configProperties['weixin.menu']}")
    private String wxMenuUrl;
    
    @Resource
    private WeiXinService wxService;
    
    @Resource
    private GroupService groupService;
    
    /**
     * 验证用户是否关注公众号
     * 
     * @param userSentTextRequest 用户发送的信息
     */
    @RequestMapping(value = "isSubscribe", method = RequestMethod.POST)
    public void isSubscribe(@RequestParam String openId, HttpServletRequest request, HttpServletResponse response) throws Exception{
        JsonResp<String> ret = new JsonResp<String>();
        //通过openid，检索用户信息
        WxUserInfoDto userInfo= wxService.getUserInfo(openId);
        
        if(userInfo != null)
        {
        	//token过期的情况
        	if(StringsUtils.isEqual(userInfo.getErrorCode().toString(), Constants.STR_TOKEN_ERO))
        	{
        		//强制更新token
        		wxService.updAccessTokenInfo();
        		log.info("重取用户信息");
        		//取得用户微信信息
        		userInfo= wxService.getUserInfo(openId);
        	}
        	//取不到openid说明出错
        	if(StringsUtils.isEmpty(userInfo.getOpenid()))
        	{
        		 log.error("isSubscribe 拉取用户信息异常！");
                 log.error("errcode:【" + userInfo.getErrorCode() + "】");
                 log.error("errmsg:【" + userInfo.getErrorMsg() + "】");
             	 ret.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
        	}
        	else
        	{
            	//值为0时，代表此用户没有关注该公众号
            	ret.setInfo(userInfo.getSubscribe());
        	}
        }
        
        String json = JSON.toJSONString(ret, true);
        try {
            MvcUtil.writeJson(request, response, json);
        } catch (IOException e) {
           log.error(e);
        } 
    }
    
    /**
     * 微信菜单设置
     * 
     */
    /*@RequestMapping(value = "setWechatMenu", method = RequestMethod.GET)
    public void setWechatMenu(HttpServletRequest request, HttpServletResponse response) throws Exception{
        JsonResp<String> ret = new JsonResp<String>();
        JSONObject menuObj = groupService.getWechatMenu();
    	//设置菜单
        BaseResponse resp = NetworkUtils.getRemoteResponseAsJson(MessageUtils.getText(wxMenuUrl, wxService.getAccessToken()), menuObj,BaseResponse.class);

        if (resp.getErrorCode() != 0) {
            log.error(InfoMsg.ERROR_WECHAT_MENU.getMsg());
            log.error("errcode:【" + resp.getErrorCode() + "】");
            log.error("errmsg:【" + resp.getErrorMsg() + "】");
            ret.setResult(Constants.RESULT_WARNING);
            ret.setMsg(InfoMsg.ERROR_WECHAT_MENU);
        }  

        String json = JSON.toJSONString(ret, true);
        try {
            MvcUtil.writeJson(request, response, json);
        } catch (IOException e) {
           log.error(e);
        } 
    }*/

    
    /**
     * 通过openid获取用户信息
     * 
     * @param userSentTextRequest 用户发送的信息
     */
    @RequestMapping(value = "getUserInfoByOpenid", method = RequestMethod.GET)
	public void getUserInfoByOpenid(@RequestParam String openId, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		JsonResp<WxUserInfoDto> ret = new JsonResp<WxUserInfoDto>();
		WxUserInfoDto wxUserInfoDto = new WxUserInfoDto();
		// 通过开团id，检索参团用户
		if (!StringsUtils.isEmpty(openId)) {
			// 取得用户微信信息
			wxUserInfoDto = wxService.getUserInfo(openId);
			// token过期的情况
			if (StringsUtils.isEqual(wxUserInfoDto.getErrorCode().toString(), Constants.STR_TOKEN_ERO)) {
				// 强制更新token
				wxService.updAccessTokenInfo();
				log.info("重取用户头像列表");
				// 取得用户微信信息
				wxUserInfoDto = wxService.getUserInfo(openId);
			}
		}

		// 数据返回
		ret.setInfo(wxUserInfoDto);

		String json = JSON.toJSONString(ret, true);
		try {
			MvcUtil.writeJson(request, response, json);
		} catch (IOException e) {
			log.error(e);
		}
	}
    
}
