package com.iamberry.wechat.handles.pay;

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

import org.apache.commons.lang3.StringUtils;
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 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;
import com.iamberry.wechat.tools.WeixinUtil;

/**
 * @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;
	}

	/**
	 * 微信授权功能
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/wechatBack")
	public ModelAndView getOpenId(
			@RequestParam(value = "callback", required = false) String callback,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String callbackURL = NameUtils.getConfig("redirectUrl_index");
		if (callback != null) {
			callbackURL = "redirect:" + WechatUtils.getCallback(callback);
		}
		
		ModelAndView mv = new ModelAndView(callbackURL);
		// 获取微信code
		String code = request.getParameter("code");
		if (StringUtils.isEmpty(code)) { 
			// 判断code是否为空
			mv.setViewName("redirect:" + WechatUtils.getOpenIdFunction(null));
			return mv;
		}
		// 通过code get微信的openid
		String[] str = WeixinUtil.getOpenId(code, NameUtils.getConfig("appId"), NameUtils.getConfig("appSecret"));
		String openId = str[0];
		if (StringUtils.isEmpty(openId)) {
			mv.setViewName("redirect:" + WechatUtils.getOpenIdFunction(null));
			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中的地址
		WechatUtils.saveUserToSession(info, request, response);
		// 获取成功后转向地址
		mv.setViewName(callbackURL);
		return mv;
	}
}
