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.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.product.*;
import com.iamberry.wechat.core.entity.search.SearchInfo;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.service.cart.dao.CartDao;
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 org.apache.commons.lang.StringUtils;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.member.Member;
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.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;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	产品
 */
@Controller
@RequestMapping("/wechat/product")
public class ProductInfoHandler {
	
	@Autowired
	private ProductInfoService productInfoService;
	
	@Autowired
	private ProductImageTextService productImageTextService;
	
	@Autowired
	private ProductPictureService productPictureService;

	@Autowired
	private HomeService homeService;

	@Autowired
	private WechatUtils wechatUtils;
	
	@Autowired
	private MemberService memberService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private CartService cartService;
	/**
	 * 首页进入商城
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/productIndex")
	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 = "typeId", defaultValue = "")Integer typeId) throws Exception {
		
		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;
		}
		//查询所有产品类型
		List<ProductType> productTypeList = productInfoService.selectProductType();
		if (null != productName && !"".equals(productName)) {
			//判断历史记录是否已存在
			SearchInfo searchInfo = new SearchInfo();
			searchInfo.setSearchDetails(productName);
			searchInfo.setUserOpenId(member.getUserOpenid());
			SearchInfo info = productInfoService.getSearchInfo(searchInfo);
			if(info != null){
				productInfoService.updateSearchInfo(searchInfo);
			}else{
				productInfoService.insertSearchInfo(searchInfo);
			}
			productName = "%" + productName + "%";
		}
		if (null == typeId) {
			typeId = productTypeList.get(0).getTypeId();
		}
		ProductType productType = new ProductType();
		productType.setTypeId(typeId);
		Product product = new Product();
		product.setProductName(productName);
		product.setProductType(productType);
		List<Product> productList = productInfoService.selectPageProduct(pageSize, pageNO,productName,typeId);
		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("productTypeList", productTypeList);
		map.put("total", count);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}

	/**
	 * 获取历史搜索记录前五
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectSearchInfo")
	public ResultMsg productIndex(HttpServletRequest request,
								  @RequestParam(value = "productName", defaultValue = "")String productName) throws Exception {
		ResultMsg remsg=new ResultMsg();

		if (null == productName || "".equals(productName)) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setStatus(false);
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		Member member =  wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setStatus(false);
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		SearchInfo searchInfo = new SearchInfo();
		searchInfo.setUserOpenId(member.getUserOpenid());
		searchInfo.setSearchDetails(productName);
		List<SearchInfo> listSearchInfo =  productInfoService.selectSearchInfo(searchInfo);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("listSearchInfo", listSearchInfo);
		remsg.setMessage(ResultInfo.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) throws Exception {

		ResultMsg remsg = new ResultMsg();
		Member member =  wechatUtils.getUserBySession(request);
		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(ResultInfo.ERRORINFO);
			return remsg;
		}
		
		if (StaticInfo.pattern.matcher(productId).find()) {
			Product product = this.productInfoService.getProductByProductId(Integer.parseInt(productId));
			List<ProductPicture> pictureList = productPictureService.getProductPictureByproductId(Integer.parseInt(productId));
			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(ResultInfo.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));
			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(ResultInfo.SUCCESSINFO);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
		} catch (Exception e) {
			remsg.setMessage(ResultInfo.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(ResultInfo.ERRORINFO);
			return remsg;
		}
		if (StaticInfo.pattern.matcher(productId).find()) {
			ProductImageText productImageText = productImageTextService.getProductImageTextByProduectId(Integer.parseInt(productId));
			remsg.setData(productImageText);
			remsg.setMessage(ResultInfo.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(ResultInfo.SUCCESSINFO);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
		} catch (Exception e) {
			remsg.setMessage(ResultInfo.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(ResultInfo.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.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(ResultInfo.SUCCESSINFO);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		return msg;
	}
	
	/**
	 * 分享产品连接,需要绑定关系
	 * @param shareUserMd5
	 * @param productIdMd5
	 * @param isShare
	 * @param isProduct
	 * @param isEnable
	 * @param request
	 * @throws Exception 
	 */
	@RequestMapping(value = "/sharePorductDesc", method = RequestMethod.GET)
	public void sharePorductDesc(
			@RequestParam(value = "shareUser", required = false) String shareUserMd5,
			@RequestParam(value = "productId", required = false) String productIdMd5,
			@RequestParam(value = "isShare", required = false) String isShare,
			@RequestParam(value = "isProduct", required = false) String isProduct,
			@RequestParam(value = "isEnable", required = false) String isEnable,
			HttpServletRequest request,
			HttpServletResponse response
			) throws Exception {
		
		Member member = wechatUtils.getUserBySession(request);
		
		// 重要操作，判断是否登陆，防止服务器重启
		if (member == null || member.getUserOpenid() == null) { // 重新授权
			request.getSession().setAttribute(NameUtils.redirectUrl, request.getRequestURI().replace(request.getContextPath(), ""));
			return;
		}
		// 校验数据
		if (productIdMd5 == null || "".equals(productIdMd5)) {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_LIST_PAGE).forward(request, response);return;
		}
		try {
			String productIdString = StaticInfo.md5.decrypt(productIdMd5);
			Integer.parseInt(productIdString);
		} catch (Exception e) {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_LIST_PAGE).forward(request, response);return;
		}
		if (shareUserMd5 == null || "".equals(shareUserMd5)) {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
		}
		String shareUserOpenid = null;
		try {
			shareUserOpenid = StaticInfo.md5.decrypt(shareUserMd5);
		} catch (Exception e) {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
		}
		if (!"true".equals(isEnable) || !"true".equals(isProduct) || !"true".equals(isShare)) {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
		}
		
		// 绑定关系
		if (member.getUserIsFlag() == 2) { // 一旦绑定了关系，就没有必要交互数据库
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
		}
		Member tempMember = homeService.selectMemberInfoByOpenId(member.getUserOpenid());
		if (tempMember.getUserIsFlag() != null && tempMember.getUserIsFlag().intValue() == 1) {
			tempMember.setUserResType(2); // 好友推荐
    		homeService.updateUserResAndTypeByOpenid(tempMember); // 更新关系，将当前关系绑定
    		member.setUserIsFlag(2); // 更新session，避免二次点击，交互数据库
		}
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
	}
	
	/**
	 * 商城内内部跳转产品信息详情页面
	 * @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.WECHAT_SHOP_PRODUCT_LIST_PAGE).forward(request, response);return;
		}
		
		//如果是分享 则绑定关系
		Member member = null;
		try {
			member = wechatUtils.getUserBySession(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String shareOpenid = request.getParameter("shareOpenid");
		if(StringUtils.isNotEmpty(shareOpenid)){
			boolean flag = memberService.buildChildUser(shareOpenid, member,1);
			if(flag){
				memberService.updateUserFlagByOpenId(member.getUserOpenid());		// 绑定用户关系
			}
		}
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_PRODUCT_DESC_PAGE).forward(request, response);return;
	}


	/**
	 * 获取所有产品类型
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectProductType")
	public ResultMsg selectProductType(HttpServletRequest request) throws Exception {
		ResultMsg remsg=new ResultMsg();
		//查询所有产品类型
		List<ProductType> productTypeList = productInfoService.selectProductType();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productTypeList", productTypeList);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}


	/**
	 * 获取所有产品颜色
	 * @param request
	 * @return list
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectProductColor")
	public ResultMsg selectProductColor(HttpServletRequest request,@RequestParam("productId") Integer productId) throws Exception {
		ResultMsg remsg=new ResultMsg();
		// 校验数据
		if (productId == null || "".equals(productId)) {
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		Member member =  wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setStatus(false);
			remsg.setMessage(ResultInfo.loginOutError);
			return remsg;
		}
		//查询所有产品颜色
		List<ProductColor> productColorList = productInfoService.selectColorByPid(productId);
		if(productColorList.size() > 0){
			for (ProductColor color : productColorList){
				CartDto cartDto = new CartDto();
				cartDto.setCartColorId(color.getColorId());
				cartDto.setCartOpenId(member.getUserOpenid());
				cartDto = cartService.getCartByOpenId(cartDto);
				if(cartDto != null){
					color.setCartId(cartDto.getCartId());
					color.setCartNum(cartDto.getCartNum());
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productColorList", productColorList);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}
}
