package com.iamberry.wechat.handles.pay;

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

import com.iamberry.wechat.tools.WeixinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.tools.NameUtils;

/**
 * @author 何秀刚
 * Class Description: 微信授权handler
 * Create Date:2016年4月19日
 * Update Date:2016年4月19日
 */
@Controller
public class WechatBackHandler {
	
	@Autowired
	private HomeService homeService;
	public void setHomeService(HomeService homeService) {
		this.homeService = homeService;
	}

	@Autowired
	private WechatUtils wechatUtils;
	public void setWechatUtils(WechatUtils wechatUtils) {
		this.wechatUtils = wechatUtils;
	}

	/**
	 * 微信授权功能
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/wechatBack")
	public ModelAndView getOpenId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(NameUtils.redirectUrl_index);
		// 获取微信code
		String code = request.getParameter("code");
		if (code == null || code.isEmpty()) { // 判断code是否为空
			mv.setViewName("redirect:" + WechatUtils.getOpenIdFunction());
			return mv;
		}
		try {
			// 通过code get微信的openid
			String[] str = WeixinUtil.getOpenId(code, NameUtils.appId, NameUtils.appSecret);
			String openId = str[0];
			if (openId == null || openId.isEmpty()) {
				mv.setViewName("redirect:" + WechatUtils.getOpenIdFunction());
				return mv;
			}
			Member info = homeService.selectMemberInfoByOpenId(openId);
			if (info == null) {
				// 创建新的用户
				info = new Member();
				info.setUserOpenid(openId);
				info.setUserSex(0);
				info.setUserStatus(1);
				int flag = homeService.insertMemberInfo(info);
				if (flag < 1) {
					homeService.insertMemberInfo(info);
				}
			}
			info.setUserOpenid(openId);
			// 提前获取session中的地址
			String redirectUrl = (String) request.getSession().getAttribute(NameUtils.redirectUrl);
			wechatUtils.saveUserToSession(info, request, response);
			// 获取成功后转向地址
			if (redirectUrl != null) {
				// 重定向到此redirectUrl
				request.getSession().removeAttribute(NameUtils.redirectUrl);
				mv.setViewName("redirect:" + redirectUrl);
				return mv;
			} else {
				mv.setViewName(NameUtils.redirectUrl_index);
				return mv;
			}
		} catch (Exception e) {
			mv.setViewName("redirect:" + WechatUtils.getOpenIdFunction());
			return mv;
		}
	}
}
