package com.iamberry.wechat.handles.cart;

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

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

import com.iamberry.redis.RedisUtils;
import com.iamberry.wechat.core.entity.eo.Promotions;
import com.iamberry.wechat.core.entity.eo.Spike;
import com.iamberry.wechat.core.entity.product.*;
import com.iamberry.wechat.face.porduct.IndexProductService;
import com.iamberry.wechat.service.ActivityUtil;
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.RequestParam;
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.cart.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.cart.UserGiftDto;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
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.member.MemberService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.face.porduct.ProductImageTextService;
import com.iamberry.wechat.face.porduct.ProductPictureService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StaticInfo;

@Controller
@RequestMapping("/wechat/product")
public class ProductInfoHandler {
	
	@Autowired
	private ProductInfoService productInfoService;
	
	@Autowired
	private ProductImageTextService productImageTextService;
	
	@Autowired
	private ProductPictureService productPictureService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private CartService cartService;

	@Autowired
	private ProductColorService productColorService;

	@Autowired
	private IndexProductService indexProductService;

	@Autowired
	private ActivityUtil activityUtil;

	/**
	 * 首页进入商城
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/productIndex",method = RequestMethod.POST)
	public ResultMsg productIndex(HttpServletRequest request,
			@RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
			@RequestParam(value = "productName", defaultValue = "")String productName,
			@RequestParam(value = "productType", defaultValue = "1") Integer productType,
			@RequestParam(value = "productRentType", defaultValue = "1") Integer productRentType) throws Exception {
		
		ResultMsg remsg= new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		//member.setUserId(11907);
		//member.setUserOpenid("o-icas-WiwbEXfwO1wLGDKQ1iWJU");
		Product product = new Product();
		if (null != productName && !"".equals(productName)) {
			product.setProductName(productName);
		}
		product.getProductType().setTypeId(productType);
		product.setProductRentType(productRentType);
		product.getPage().setPageNumber(pageNO);
		product.getPage().setPageSize(pageSize);
		product.getPage().initRecordBegin();
		List<Product> productList = productInfoService.selectPageProduct(product);
		Promotions promotions = activityUtil.getAllPromotions();
		if(promotions != null){
			for (Product pc:productList) {
				for (ProductColor color : pc.getColorList()) {
					for (Spike spike:promotions.getSpikeList()) {
						if(spike.getSpikeColorId() == color.getColorId()){
							pc.setProductPrice(spike.getSpikePrice());
							pc.setProductDiscount(spike.getSpikeDiscount());
							color.setColorDiscount(spike.getSpikeDiscount());
							color.setColorPrice(spike.getSpikePrice());
						}
					}
				}
			}
		}

		int num = this.productInfoService.selectProductCount(product);
		int count = num % pageSize == 0? num/pageSize:(num/pageSize)+1;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productList", productList);
		map.put("total", count);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}


	/**
	 * 微商城首页-热销产品
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/productIndexSellWell",method = RequestMethod.POST)
	public ResultMsg productIndexSellWell(HttpServletRequest request) throws Exception {
		ResultMsg remsg= new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);

		IndexProduct firColuProduct = new IndexProduct();
		firColuProduct.setIndeProdType(1);
		List<IndexProduct> firColuProductList = indexProductService.getIndexProductList(firColuProduct);

		IndexProduct SecColuProduct = new IndexProduct();
		SecColuProduct.setIndeProdType(2);
		List<IndexProduct> SecColuProductList = indexProductService.getIndexProductList(SecColuProduct);


		Map<String, Object> map = new HashMap<String, Object>();
		map.put("firColuProductList", firColuProductList);
		map.put("SecColuProductList", SecColuProductList);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}
	
	/**
	 * 进入产品详细信息页面
	 * @param request
	 * @param response
	 * @param productId
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getProductByProductId")
	public ResultMsg getProductByProductId(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "productId",defaultValue = "") String productId, 
			@RequestParam("colorId") Integer colorId 
			) throws Exception {

		ResultMsg remsg = new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		//member.setUserId(11907);
		//member.setUserOpenid("o-icas-WiwbEXfwO1wLGDKQ1iWJU");
		Map<String, Object> map=null;
		/*
		 * 判断用户信息及其参数
		 */
		if (member == null || member.getUserOpenid() == null) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setStatus(false);
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		if (productId == null) {
			remsg.setStatus(false);
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			return remsg;
		}
		
		if (StaticInfo.pattern.matcher(productId).find()) {
			Product product = this.productInfoService.getProductByProductId(Integer.parseInt(productId),colorId);

			//根据openid查询该用户是否购买过订单
			ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
			shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
			shopSalesOrderDto.setSalesStatus("2");

			List<ProductPicture> pictureList = productPictureService.getProductPictureByproductId(Integer.parseInt(productId));
			product.setPictureList(pictureList);

			ProductColor productColor = new ProductColor();
			productColor.setColorStatus(1);
			productColor.setColorProductId(product.getProductId());
			List<ProductColor> colorList = productColorService.selectProductColorList(productColor);
			activityUtil.getColorSpike(colorList);

			if(colorList != null && colorList.size()>0){
				product.setProductPrice(colorList.get(0).getColorPrice());
				product.setProductDiscount(colorList.get(0).getColorDiscount());
			}

			/*
			 * 组装数据
			 */
			map = new HashMap<String, Object>();
//			map.put("isShow", ResultInfo.ISSHOW);
//			map.put("cartDesc", ResultInfo.CARTDESC);
//			map.put("cart_url", ResultInfo.CART_URL);
			map.put("product", product);
			map.put("shareOpenid", member.getUserOpenid());
			map.put("colorList", colorList);
			remsg.setData(map);
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			return remsg;
		}
		
		try {
			String productIdString = StaticInfo.md5.decrypt(productId);
			Product product = this.productInfoService.getProductByProductId(Integer.parseInt(productIdString),colorId);
			List<ProductPicture> pictureList = productPictureService.getProductPictureByproductId(Integer.parseInt(productIdString));
			product.setPictureList(pictureList);
			/*
			 * 组装数据
			 */
			map = new HashMap<String, Object>();
//			map.put("isShow", ResultInfo.ISSHOW);
//			map.put("cartDesc", ResultInfo.CARTDESC);
//			map.put("cart_url", ResultInfo.CART_URL);
			map.put("product", product);
			map.put("shareOpenid", member.getUserOpenid());
			remsg.setData(map);
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
		} catch (Exception e) {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);			
		}
		return remsg;
	}
	
	/**
	 * 获取商品详情（图文）
	 * @param request
	 * @param response
	 * @param productId
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getPictureByProductId")
	public ResultMsg getPictureByProductId(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "productId",defaultValue = "") String productId) throws Exception {
		ResultMsg remsg = new ResultMsg();
		if (productId == null) {
			remsg.setStatus(false);
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			return remsg;
		}
		if (StaticInfo.pattern.matcher(productId).find()) {
			ProductImageText productImageText = productImageTextService.getProductImageTextByProduectId(Integer.parseInt(productId));
			remsg.setData(productImageText);
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			return remsg;
		}
		try {
			String productIdString = StaticInfo.md5.decrypt(productId);
			ProductImageText productImageText = productImageTextService.getProductImageTextByProduectId(Integer.parseInt(productId));
			List<ProductPicture> pictureList = productPictureService.getProductPictureByproductId(Integer.parseInt(productIdString));
			productImageText.setPictureList(pictureList);
			remsg.setData(productImageText);
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
		} catch (Exception e) {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);			
		}
		return remsg;
	}
	
	/**
	 * 根据商品名称查询商品信息
	 * @param request
	 * @param response
	 * @param productName
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getProductByProductName")
	public ResultMsg getProductByProductName(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "productName", defaultValue = "")String productName) throws Exception {
		
		List<Product> productList = new ArrayList<Product>();
		ResultMsg remsg=new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		
		/*
		 * 判断用户信息及其参数
		 */
		if (member == null || member.getUserOpenid() == null) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setStatus(false);
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		
		if (null != productName && !"".equals(productName)) {
			productName = "%" + productName + "%";
		}
		productList = this.productInfoService.getProductByProductName(productName);
		
		if (productList != null && productList.size() >= 1) {
			/*
			 * 优惠价计算
			 */
			boolean isPrice = false;
			if (member.getUserIdentity() != null && member.getUserIdentity() == 2) { 									// 微代理:优惠价
				isPrice = true;
			} else {
				if (member.getUserResType() != null && (member.getUserResType() == 2 || member.getUserResType() == 3)) { // 来源他人二维码:优惠价
					isPrice = true;
				} else {
					Member tempMember = memberService.selectUserResAndIdSByOpenId(member.getUserOpenid());
					member.setUserIdentity(tempMember.getUserIdentity());
					member.setUserResType(tempMember.getUserResType());
					if (tempMember.getUserIdentity() == 2) {// 微代理：优惠价
						isPrice = true;
					} else {
						if (tempMember.getUserResType() == 2 || tempMember.getUserResType() == 3) { // 来源他人二维码:优惠价
							isPrice = true;
						}
					}
				}
			}
			if (isPrice) {
				int price = systemService.selectOneShopRuleById(22).getRuleNum().intValue(); 
				for (Product product2 : productList) {
					product2.setProductPrice(product2.getProductDiscount());
					product2.setProductDiscount(price);
				}
			}
		}
		
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(productList);
		return remsg;
	}

	/**
	 * 为当前用户获取产品分享URL
	 * @param productId
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/shareProductUrl", method = RequestMethod.POST)
	public ResultMsg shareProductUrl(
			@RequestParam(value = "productId", required = false) Integer productId,
			HttpServletRequest request
			) throws Exception {
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		
		Member member = WechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		if (productId == null) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		StringBuffer buffer = new StringBuffer(NameUtils.getConfig("WECHAT_PRODUCT_SHARE_URL"));
		buffer.append("?shareUser=" + StaticInfo.md5.encrypt(member.getUserOpenid()));
		buffer.append("&productId=" + StaticInfo.md5.encrypt(productId.toString()));
		buffer.append("&isShare=true&isProduct=true&isEnable=true"); // 是否分享,是否为产品,是否启动
		
		msg.setData(buffer.toString());
		msg.setStatus(true);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		return msg;
	}
	
	/**
	 * 商城内内部跳转产品信息详情页面
	 * @param productId
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/desc", method = RequestMethod.GET)
	public void productDesc(
			@RequestParam("productId") Integer productId,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 校验数据
		if (productId == null || "".equals(productId)) {
			request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_PRODUCT_LIST_PAGE")).forward(request, response);return;
		}
		
		//如果是分享 则绑定关系
		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_PRODUCT_DESC_PAGE")).forward(request, response);
		//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_PRODUCT_DESC_PAGE"));
		return;
	}
	
	
	/**
	 * 进入租赁产品详情页面
	 * @param productId
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toLeasepProductDetails", method = RequestMethod.GET)
	public void toLeasepProductDetails(
			@RequestParam("productId") Integer productId,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 校验数据
		if (productId == null || "".equals(productId)) {
			request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_PRODUCT_LIST_PAGE")).forward(request, response);return;
		}
		request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_PRODUCT_DESC_PAGE")).forward(request, response);return;
	}
	/**
	 * 获取租赁产品详情
	 */
	@RequestMapping(value = "/leasepProductDetails", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg leasepProductDetails(@RequestParam("productId") Integer productId,
			HttpServletRequest request, HttpServletResponse response){
		String openid="";
		ResultMsg remsg = new ResultMsg();
		Map<String, Object> map = new HashMap<String, Object>();
		openid = WechatUtils.getUserBySession(request).getUserOpenid();
		List<ProductColor> productColorlist = null;
		// 校验数据
		if (productId == null || "".equals(productId)) {
			remsg.setStatus(false);
		}
		//查询产品信息
		Product leaseProduct = productInfoService.getLeaseProduct(productId);
		//查询产品颜色
		productColorlist =	productColorService.getLeaseProductColor(leaseProduct.getProductId());
		map.put("leaseProduct", leaseProduct);
		map.put("productColorlist", productColorlist);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}
}
