package com.iamberry.wechat.handles.home;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.iamberry.wechat.core.entity.product.QrcodeGift;
import com.iamberry.wechat.core.entity.qrcode.QrcodeResult;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import org.apache.commons.lang.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.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.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;

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

	@Autowired
	private HomeService homeService;
	public void setHomeService(HomeService homeService) {
		this.homeService = homeService;
	}

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private CartService cartService;

	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	/**
	 * 微信商城首页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);
	}

	/**
	 * 获取首页Banner、广告位信息
	 * @param request
	 * @return
	 * @throws Exception
	 * @author 献
	 * @Time   2016年12月2日
	 */
	@ResponseBody
	@RequestMapping(value = "/indexData", method = RequestMethod.POST)
	public ResultMsg indexData(HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		// 准备数据
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		/*
		 * 广告位、Banner处理
		 */
		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);
				}
			}
		}
		returnMap.put("advs", advs);
		returnMap.put("banners", banners);
		returnMap.put("memberOpenid", member.getUserOpenid()); 				// 当前用户信息 分享用

		msg.setData(returnMap); // 封装数据
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);

		return msg;
	}

	/**
	 * 首页获取产品信息
	 * @return
	 * @author 献
	 * @Time   2016年12月2日
	 */
	@ResponseBody
	@RequestMapping(value = "/prodects", method = RequestMethod.GET)
	public ResultMsg getProdects(HttpServletRequest request) {
		ResultMsg msg = new ResultMsg();

		Member member =  WechatUtils.getUserBySession(request);
		// 准备数据
		Map<String, Object> returnMap = new HashMap<String, Object>();

		List<Product> productList = productInfoService.selectIndexPageProduct();


        /*//如果是有二维码的商户，进入后显示优惠价
        int sum = productInfoService.getQrCodeByPlaceOpenId(member.getUserOpenid());
        if (sum > 0) {
            QrcodeGift gift = new QrcodeGift();
            List<QrcodeGift> giftList = productInfoService.listQrcodeGift(gift);
            if (giftList != null && giftList.size() > 0 && productList != null && productList.size() > 0) {
                for (Product productInfo : productList) {
                    for (QrcodeGift qrcodeGift : giftList) {
                        if (productInfo.getColorId().intValue() == qrcodeGift.getQrcodeColorId()
                            && qrcodeGift.getQrcodePreDiscount() != null
                            && qrcodeGift.getQrcodePreDiscount() > 0) {
                            productInfo.setProductDiscount(qrcodeGift.getQrcodePreDiscount());
                        }
                    }
                }
            }
        }*/


		// 判断是否为金牌会员下线，如果是，则以优惠价显示，如果不是则按原价显示
		// 查询金牌会员模板id
		int templateId = systemService.selectOneShopRuleById(114).getRuleNum().intValue();
		// 查询用户信息
		Member user = memberService.getMemberByUserOpenId(member.getUserOpenid());
		// 如果模板id等于金牌会模板id，则该用户为金牌会员下线
		if (user.getTemplateId() != null && templateId == user.getTemplateId().intValue() && user.getUserResType().intValue() == 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().intValue() == 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());
						}
					}
				}
			}
		}

		returnMap.put("products", productList); 							// 产品信息，10个
		msg.setData(returnMap); // 封装数据
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}

}
