package com.iamberry.wechat.handles.home;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

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

import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.product.ProductChildType;
import com.iamberry.wechat.core.entity.product.ProductType;
import com.iamberry.wechat.tools.WeixinUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
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.ResponseBody;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.banner.ActionBannerImage;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	微信商城首页Handler
 */
@Controller
@RequestMapping("/wechat")
public class HomeHandler {

	Logger logger = LoggerFactory.getLogger(HomeHandler.class);

	@Autowired
	private HomeService homeService;
	
	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private WechatUtils wechatUtils;

	@Autowired
	private MemberService memberService;

	@Autowired
	private SystemService systemService;

	
	/**
	 * 微信商城首页URL
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//如果是分享 则绑定关系
		Member member = wechatUtils.getUserBySession(request);
		String shareOpenid = request.getParameter("shareOpenid");
		if(StringUtils.isNotEmpty(shareOpenid)){
			build(shareOpenid, member);
		}
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_INDEX).forward(request, response);
	}
	
	/**
	 * post请求获取首页Banner数据
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/indexData")
	public ResultMsg indexData(HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();

		Member m = WechatUtils.getUserBySession(request);
		m = memberService.getMemberByUserOpenId(m.getUserOpenid());
		try{
			if(m.getUserHead() == null || "".equals(m.getUserHead())){
				JSONObject jsonObject = WeixinUtil.getUserInfo(m.getUserOpenid());
				String nickname = jsonObject.getString("nickname");
				String headimgurl = jsonObject.getString("headimgurl");
				try {
					nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					nickname = "";
				}
				m.setUserHead(headimgurl);
				m.setUserNickname(nickname);
				if(nickname != null && !"".equals(nickname)){
					m.setUserStatus(2);
				}
				homeService.updateWechatMemberInfoByByOpenid(m);
			}
		}catch (Exception e){
			logger.info("获取个人信息失败；openid："+m.getUserOpenid());
			e.printStackTrace();
		}

		Member member =  wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			msg.setStatus(false);
			return msg;
		}
		
		// 准备数据
		Map<String, Object> returnMap = new HashMap<String, Object>();
		/*List<Product> productList = productInfoService.selectIndexPageProduct();*/
		List<Product> selectProductTopper = productInfoService.selectIndexChoicenessProduct(1);//获取精选置顶产品
		List<Product> selectProduct = productInfoService.selectIndexChoicenessProduct(2);//获取精选产品

		//获取配件类型
		ShopSystemRule shopSystemRule = systemService.selectOneShopRuleById(255);
		List<ProductChildType> childTypesList = productInfoService.selectProductFittingsType(shopSystemRule.getRuleType());

		List<ActionBannerImage> images = homeService.selectNowBannerByType(); 	// Banner、广告位
		List<ActionBannerImage> banners = new ArrayList<ActionBannerImage>();	// banner
		List<ActionBannerImage> advs = new ArrayList<ActionBannerImage>();		// 广告位
		if (images != null && images.size() >= 1) {								// 分类注册
			for (ActionBannerImage actionBannerImage : images) {
				if (actionBannerImage.getBannerId() == 1) {
					banners.add(actionBannerImage);
				} else {
					advs.add(actionBannerImage);
				}
			}
		}

		//查询所有产品类型
		List<ProductType> productTypeList = productInfoService.selectProductType();
		returnMap.put("productTypeList", productTypeList);					//所有产品类型及子类型集合
		returnMap.put("advs", advs);
		returnMap.put("banners", banners);
		returnMap.put("selectProductTopper", selectProductTopper);
		returnMap.put("selectProduct", selectProduct);
		returnMap.put("memberOpenid", member.getUserOpenid()); 				// 当前用户信息 分享用
		returnMap.put("childTypesList", childTypesList);					// 配件子类型集合
		msg.setData(returnMap); 											// 封装数据
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 绑定用户关系
	 * @param shareOpenid	分享的人
	 * @param member		当前用户
	 */
	@Async
	public void build(String shareOpenid, Member member) {
		boolean flag = memberService.buildChildUser(shareOpenid, member,1);
		if(flag){
			memberService.updateUserFlagByOpenId(member.getUserOpenid());		// 绑定用户关系
		}
	}

	/**
	 * 刷新用户信息
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
	public ResultMsg getUserInfo(HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();

		Member m = WechatUtils.getUserBySession(request);
		m = memberService.getMemberByUserOpenId(m.getUserOpenid());
		try{
			JSONObject jsonObject = WeixinUtil.getUserInfo(m.getUserOpenid());
			String nickname = jsonObject.getString("nickname");
			String headimgurl = jsonObject.getString("headimgurl");
			try {
				nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				nickname = "";
			}

			Member mem = new Member();
			mem.setUserHead(headimgurl);
			mem.setUserNickname(nickname);
			mem.setUserOpenid(m.getUserOpenid());
			if(m.getUserStatus() == 2){
				memberService.nowUpdateUserByOpenId(mem);
			}else{
				if(nickname != null && !"".equals(nickname)){
					mem.setUserStatus(2);
				}
				homeService.updateWechatMemberInfoByByOpenid(mem);
			}
			logger.info("获取个人信息成功；openid："+m.getUserOpenid());
		}catch (Exception e){
			logger.info("获取个人信息失败；openid："+m.getUserOpenid());
			e.printStackTrace();
		}

		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
}
