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", required = false)String productName,
			@RequestParam(value = "productType", defaultValue = "1") Integer productType,
			@RequestParam(value = "productRentType", defaultValue = "1") Integer productRentType) throws Exception {
		// 获取当前登陆的用户
		WechatUtils.getUserBySession(request);
		// 组装查询数据
		Product product = new Product();
		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>(2);
		map.put("productList", productList);
		map.put("total", count);
		return ResultMsg.SUCCESS().setData(map);
	}


	/**
	 * 微商城首页-热销产品
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/productIndexSellWell",method = RequestMethod.POST)
	public ResultMsg productIndexSellWell(HttpServletRequest request) throws Exception {
		// 准备查询的数据
		IndexProduct firColuProduct = new IndexProduct();
		firColuProduct.setIndeProdType(1);
		IndexProduct seccoluproduct = new IndexProduct();
		seccoluproduct.setIndeProdType(2);
		// 开始返回
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put("firColuProductList", indexProductService.getIndexProductList(firColuProduct));
		map.put("SecColuProductList", indexProductService.getIndexProductList(seccoluproduct));
		return ResultMsg.SUCCESS().setData(map);
	}
	
	/**
	 * 进入产品详细信息页面
	 * @param request
	 * @param response
	 * @param productId
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getProductByProductId")
	public ResultMsg getProductByProductId(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "productId") String productId,
			@RequestParam("colorId") Integer colorId) throws Exception {
		// 获取当前登陆的用户信息
		Member member =  WechatUtils.getUserBySession(request);
		ResultMsg remsg = new ResultMsg();
		Map<String, Object> map=null;
		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>(3);
			map.put("product", product);
			map.put("shareOpenid", member.getUserOpenid());
			map.put("colorList", colorList);
			return ResultMsg.SUCCESS().setData(map);
		}
		
		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>(2);
			map.put("product", product);
			map.put("shareOpenid", member.getUserOpenid());
			return ResultMsg.SUCCESS().setData(map);
		} catch (Exception e) {
			return ResultMsg.ERROR().setData(e.getMessage());
		}
	}
	
	/**
	 * 获取商品详情（图文）
	 * @param request
	 * @param response
	 * @param productId
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getPictureByProductId")
	public ResultMsg getPictureByProductId(@RequestParam(value = "productId") String productId) throws Exception {
		if (StaticInfo.pattern.matcher(productId).find()) {
			ProductImageText productImageText = productImageTextService.getProductImageTextByProduectId(Integer.parseInt(productId));
			return ResultMsg.SUCCESS().setData(productImageText);
		}
		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);
			return ResultMsg.SUCCESS().setData(productImageText);
		} catch (Exception e) {
			return ResultMsg.ERROR().setData(e.getMessage());
		}
	}
	
	/**
	 * 根据商品名称查询商品信息
	 * @param request
	 * @param response
	 * @param productName
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getProductByProductName")
	public ResultMsg getProductByProductName(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "productName", required = false) String productName) throws Exception {
		// 获取登陆的用户
		Member member =  WechatUtils.getUserBySession(request);
		// 查询
		List<Product> productList = productInfoService.getProductByProductName(productName);
		if (productList == null || productList.isEmpty()) {
			return ResultMsg.SUCCESS().setData(productList);
		}
		/*
		 * 优惠价计算
		 */
		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);
			}
		}
		
		return ResultMsg.SUCCESS().setData(productList);
	}

	/**
	 * 为当前用户获取产品分享URL
	 * @param productId
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/shareProductUrl", method = RequestMethod.POST)
	public ResultMsg shareProductUrl(
			@RequestParam(value = "productId") Integer productId,
			HttpServletRequest request
			) throws Exception {
		Member member = WechatUtils.getUserBySession(request);
		// 是否分享,是否为产品,是否启动
		String buffer = NameUtils.getConfig("WECHAT_PRODUCT_SHARE_URL") +
				"?shareUser=" + StaticInfo.md5.encrypt(member.getUserOpenid()) +
				"&productId=" + StaticInfo.md5.encrypt(productId.toString()) +
				"&isShare=true&isProduct=true&isEnable=true";
		return ResultMsg.SUCCESS().setData(buffer);
	}
	
	/**
	 * 商城内内部跳转产品信息详情页面
	 * @param productId
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@Deprecated
	@RequestMapping(value = "/desc", method = RequestMethod.GET)
	public void productDesc(@RequestParam("productId") Integer productId,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//如果是分享 则绑定关系
		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);
	}
	
	
	/**
	 * 进入租赁产品详情页面
	 * @param productId
	 * @param request
	 * @param response
	 */
	@Deprecated
	@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;
	}
	/**
	 * 获取租赁产品详情
	 */
	@Deprecated
	@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;
	}
}
