package com.iamberry.wechat.handles.home;

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.cart.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.cart.UserGiftDto;
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.CartService;
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;
import com.iamberry.wechat.tools.WeixinUtil;
import com.iamberry.wechat.tools.payUtil.RandomUtil;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月30日
 * @explain	商城首页
 */
@Controller
@RequestMapping("/wechat")
public class HomeHandler {
	private Logger logger = LoggerFactory.getLogger(HomeHandler.class);

	@Autowired
	private HomeService homeService;

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private CartService cartService;

	/**
	 * 微信商城首页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)){
			memberService.buildChildUser(shareOpenid, member,1,1);
		}
		request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_INDEX")).forward(request, response);
		//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
	}
	 */

	/**
	 * 获取首页Banner、广告位信息
	 * @param request
	 * @return
	 * @throws Exception
	 * @author 献
	 * @Time   2016年12月2日
	 */
	@ResponseBody
	@RequestMapping(value = "/indexData", method = RequestMethod.POST)
	public ResultMsg indexData(HttpServletRequest request) {
		Member m = memberService.getMemberByUserOpenId(WechatUtils.getUserBySession(request).getUserOpenid());
		// Banner、广告位集合
		List<ActionBannerImage> images = homeService.selectNowBannerByType();
		// 广告位
		int size = 0;
		if (images != null && images.size() >= 1) {
			size = images.size();
		}
		List<ActionBannerImage> banners = new ArrayList<ActionBannerImage>(size);
		List<ActionBannerImage> advs = new ArrayList<ActionBannerImage>(size);
		if (size > 0) {
			images.forEach((actionBannerImage) -> {
				if (actionBannerImage.getBannerId() == 1) {
					banners.add(actionBannerImage);
				} else {
					advs.add(actionBannerImage);
				}
			});
		}
		// 准备数据返回
		Map<String, Object> returnMap = new HashMap<String, Object>(3);
		returnMap.put("advs", advs);
		returnMap.put("banners", banners);
		returnMap.put("memberOpenid", m.getUserOpenid());
		// 组装前端需要的数据
		return ResultMsg.SUCCESS().setData(returnMap);
	}
	/**
	 * 刷新用户信息
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
	public ResultMsg getUserInfo(HttpServletRequest request) throws Exception {
		Member m = memberService.getMemberByUserOpenId(WechatUtils.getUserBySession(request).getUserOpenid());
		try{
				JSONObject jsonObject = WeixinUtil.getUserInfo(m.getUserOpenid());
                assert jsonObject != null;
                assert jsonObject.has("nickname");
				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.error("获取个人信息失败:{}", e);
		}
		return ResultMsg.SUCCESS();
	}

	/**
	 * 首页获取产品信息
	 * @return
	 * @author 献
	 * @Time   2016年12月2日
	 */
	@ResponseBody
	@RequestMapping(value = "/prodects", method = RequestMethod.GET)
	public ResultMsg getProdects(HttpServletRequest request) {
		Member member =  WechatUtils.getUserBySession(request);
		List<Product> productList = productInfoService.selectIndexPageProduct();
		/*
		// 判断是否为金牌会员下线，如果是，则以优惠价显示，如果不是则按原价显示
		// 查询金牌会员模板id
		int templateId = systemService.selectOneShopRuleById(114).getRuleNum().intValue();
		// 查询用户信息
		Member user = memberService.getMemberByUserOpenId(member.getUserOpenid());
		// 如果模板id等于金牌会模板id，则该用户为金牌会员下线
		if (user.getTemplateId() != null && templateId == user.getTemplateId() && user.getUserResType() == 3) {
			// 若果是金牌会员下线，产品的价格就以优惠价显示
			if (productList != null && productList.size() >= 1) {
				for (Product productInfo : productList) {
					UserGiftDto userGiftDto = new UserGiftDto();
					userGiftDto.setUserLevel(2);
					userGiftDto.setUserProductId(productInfo.getProductId());
					userGiftDto.setUserColorId(productInfo.getColorId());
					// 根据商品id和会员等级查询礼品信息
					userGiftDto = productInfoService.selectUserGift(userGiftDto);
					if (userGiftDto != null) {
						productInfo.setProductDiscount(userGiftDto.getUserDiscount());
					}
				}
			}
		}*/


		// 根据openid查询该用户是否购买过订单
		ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
		shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
		shopSalesOrderDto.setSalesStatus("2");
		int orderNum = cartService.selectOrderCount(shopSalesOrderDto);
		// 如果购买过订单，则滤芯的价格可按折扣价购买
		if (orderNum > 0) {
			if (productList != null && productList.size() >= 1) {
				for (Product productInfo : productList) {
					if (productInfo.getProductType().getTypeId() == 2) {
						UserGiftDto userGiftDto = new UserGiftDto();
						userGiftDto.setUserLevel(3);
						userGiftDto.setUserProductId(productInfo.getProductId());
						userGiftDto.setUserColorId(productInfo.getColorId());
						// 根据商品id和会员等级查询礼品信息
						userGiftDto = productInfoService.selectUserGift(userGiftDto);
						if (userGiftDto != null) {
							productInfo.setProductDiscount(userGiftDto.getUserDiscount());
						}
					}
				}
			}
		}

		// 准备数据
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("products", productList);
		return ResultMsg.SUCCESS().setData(returnMap);
	}

}
