package com.iamberry.wechat.handles.porduct;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.banner.MessageDTO;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.product.ProductPicture;
import com.iamberry.wechat.core.entity.product.ProductType;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.face.porduct.ProductPictureService;
import com.iamberry.wechat.face.porduct.ProductService;
import com.iamberry.wechat.face.porduct.ProductTypeService;
/**
 *	后台产品管理 handler
 * 	@author: iamberry~
 *	@createDate: 2016年4月20日
 */
@Controller
@RequestMapping("/admin/product")
public class ProductHandler {
	@Autowired
	private ProductService productService;				//产品service
	
	@Autowired
	private ProductInfoService productInfoService;
	
	@Autowired
	private ProductPictureService productPictureService;		//介绍图service
	
	@Autowired
	private ProductTypeService productTypeService;
	
	@Autowired
	private ProductColorService productColorService;
	/**
	 * 查询所有产品 并分页 (支持查询条件模糊搜索)
	 * 2016年4月21日
	 * @author mzx
	 * @param page	分页信息
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView getProductList(@RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO, 
			HttpServletRequest request) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer url = new StringBuffer("/admin/product/list?pageSize=" + pageSize);
		ModelAndView mv = new ModelAndView("admin/product/productList");
		String goodName = request.getParameter("goodsInfoGoodname");
		String minMoney = request.getParameter("minMoney");
		String maxMoney = request.getParameter("maxMoney");
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		Product product = new Product();
		product.getPage().setPageSize(pageSize);
		product.getPage().setPageNumber(pageNO);
		
		if (null != goodName && !"".equals(goodName)) {
			product.setProductName(goodName);
			url.append("&goodsInfoGoodname=" + goodName);
		}
		if (null != minMoney && !"".equals(minMoney)) {
			url.append("&minMoney=" + minMoney);
			product.setMinMoney(Integer.parseInt(minMoney) * 100);
		}
		if (null != maxMoney && !"".equals(maxMoney)) {
			url.append("&maxMoney=" + maxMoney);
			product.setMaxMoney(Integer.parseInt(maxMoney) * 100);
		}
		if (null != beginDate && !"".equals(beginDate)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				product.setBeginDate(format.parse(new String(beginDate.getBytes("ISO-8859-1"), "UTF-8")));
			} else {
				product.setBeginDate(format.parse(beginDate));
			}
			url.append("&beginDate=" + beginDate);
		}
		if (null != endDate && !"".equals(endDate)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				product.setEndDate(format.parse(new String(endDate.getBytes("ISO-8859-1"), "UTF-8")));
			} else {
				product.setEndDate(format.parse(endDate));
			}
			url.append("&endDate=" + endDate);
		}

		List<Product> list = productService.selectAllProductInfo(product);
		mv.addObject("list", list);
		
		url.append("&pageNO=");
		int count = productService.selectProductCount(product);
		int pageCount =  count % product.getPage().getPageSize() == 0? count/product.getPage().getPageSize():(count/product.getPage().getPageSize())+1;
		//分页用
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url);
		mv.addObject("goodsInfoGoodname", product.getProductName());
		mv.addObject("minMoney", minMoney);
		mv.addObject("maxMoney", maxMoney);
		mv.addObject("beginDate", beginDate);
		mv.addObject("endDate", endDate);
		mv.addObject("pageSize", pageCount);	
		return mv;
	}
	
	/**
	 * 进入添加页面
	 * 2016年4月21日
	 * @author mzx
	 * @return
	 */
	@RequestMapping("/toAdd")
	public ModelAndView toAddProduct(){
		ModelAndView mv = new ModelAndView("admin/product/addProduct");
		List<ProductType> list = productTypeService.getAll();
		mv.addObject("typeList", list);
		return mv;
	}
	
	/**
	 * 添加一个产品 包括介绍图、banner、产品颜色、图文
	 * 2017年4月13日 <改>
	 * @author mzx
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView addProduct(HttpServletRequest req,Product product){
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败！"));
		//设置产品类型
		if(product.getProductType().getTypeId() == null 
				|| product.getProductType().getTypeId() == 0
				|| product.getColorList() == null || product.getColorList().size() < 1
				|| StringUtils.isEmpty(product.getColorList().get(0).getColorName())){
			return mv; 
		}
		
		//添加商品banner图片
		List<ProductPicture> picList = new ArrayList<ProductPicture>();
		String imageUrls[] = req.getParameterValues("productBannerImg");//获取多个banner图地址
		ProductPicture pp = null;
		for(int i = 0 ; i < imageUrls.length;i++){
			pp = new ProductPicture();
			pp.setPictureCreateDate(new Date());
			pp.setPictureUrl(imageUrls[i]);
			picList.add(pp);
		}
		product.setProductCreateDate(new Date());
		mv = productService.addProduct(product, picList);
		
		if((Boolean) mv.getModelMap().get("status")){
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加成功！"));
			// 缓存
			productInfoService.cacheIndexPageProduct();
		}
		return mv;
	}
	
	/**
	 * 进入修改页面
	 * 2016年4月22日
	 * @author mzx
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "/toUpdate/{productId}", method = RequestMethod.GET)
	public ModelAndView toUpdateProduct(@PathVariable("productId") String productId){
		ModelAndView mv = new ModelAndView("admin/product/updateProduct");
		if(StringUtils.isNotEmpty(productId)){
			//查出该产品详细信息
			Product product = productService.selectProductByProductId(Integer.parseInt(productId));
			//查询该产品所有颜色
			List<ProductColor> colorList = productColorService.getLeaseProductColor(Integer.parseInt(productId));
			//查出所有产品类型
			List<ProductType> typelist = productTypeService.getAll();
			mv.addObject("colorList", colorList);
			mv.addObject("typeList", typelist);
			mv.addObject("product", product);
		}
		return mv;
	}
	
	/**
	 * 修改产品信息 
	 * 2016年4月22日
	 * @author mzx
	 * @param product
	 * @return
	 */
	@RequestMapping("/update")
	public ModelAndView updateProduct(HttpServletRequest req,Product product){
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		mv.addObject("msgObj", new MessageDTO(false, "操作结果", "修改失败！"));
		if(product.getProductId() == null || product.getProductType() == null
				|| product.getProductType().getTypeId() == null){ 
			return mv; 
		}
		/* 添加商品banner图 去掉重复的<url一样的图> */
		String[] imageUrls = req.getParameterValues("productBannerImg");//获取多个banner图地址
		mv = productService.updateProductByProductId(product, imageUrls);
		
		if((Boolean) mv.getModelMap().get("status")){
			// 缓存
			productInfoService.cacheIndexPageProduct();
		}
		return mv;
	}
	
	/**
	 * 修改商品状态
	 * 2016年4月22日
	 * @param request
	 * @param response
	 * @author mzx
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public Map<String,String> updateProductStatus(HttpServletRequest request,
			HttpServletResponse response,Product product) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		String productId = request.getParameter("productId");
		String productStatus = request.getParameter("productStatus");
		if("".equals(productId) || "".equals(productStatus)){
			map.put("status", "修改失败！");
			return  map;
		}
		product.setProductId(Integer.parseInt(productId));
		product.setProductStatus(Integer.parseInt(productStatus));
		
		Integer msg = productService.updateProductStatusByProductId(product);
		if(msg == 0){
			map.put("status", "修改失败！");
			return  map; 
		}
		// 缓存
		productInfoService.cacheIndexPageProduct();
		map.put("status", "修改成功！");
		return  map;
	}
	
	/**
	 * 删除商品banner图 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("deleteProductImage")
	@ResponseBody
	public Map<String,String> deleteProductPicture(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		String pictureId = request.getParameter("pictureId");
		if(StringUtils.isNotEmpty(pictureId)){
			Integer n = productPictureService.deleteProductPicture(Integer.parseInt(pictureId));
			if(n == 0){
				map.put("status", "删除失败！");
				return  map;
			}
		}
		map.put("status", "删除成功！");
		return  map;
	}
}
