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.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 org.apache.commons.lang.StringUtils;

import com.iamberry.wechat.core.entity.banner.MessageDTO;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductImageText;
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.ProductImageTextService;
import com.iamberry.wechat.face.porduct.ProductPictureService;
import com.iamberry.wechat.face.porduct.ProductService;
import com.iamberry.wechat.face.porduct.ProductTypeService;
/**
 * 
 *		description: 商品查询handler
 * 	   		@author: 张应真
 *	    @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 ProductImageTextService productImageTextService;	//图文service	
	
	@Autowired
	private ProductTypeService productTypeService;
	/**
	 * 返回查询商品列表
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryProduct/{productName}", method = RequestMethod.POST)
	public  List<Product> queryProduct(@PathVariable("productName")String productName){
		List<Product>productList=new ArrayList<Product>();
		productList=productService.getProductByFuzzy(productName);
		return productList;
		
	}
	
	/**
	 * 查询所有产品 并分页
	 * 2016年4月21日
	 * @author 穆再兴
	 * @param page	分页信息
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView getProductList(@RequestParam(value= "pageSize",defaultValue= "15" ,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 穆再兴
	 * @return
	 */
	@RequestMapping("/toAdd")
	public ModelAndView toAddProduct(){
		ModelAndView mv = new ModelAndView("admin/product/addProduct");
		List<ProductType> list = productTypeService.getAll();
		mv.addObject("typeList", list);
		return mv;
	}
	
	/**
	 * 添加一个产品
	 * 2016年4月22日
	 * @author 穆再兴
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView addProduct(HttpServletRequest req,Product product){
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		//设置产品类型
		String typeId = req.getParameter("typeId");
		if(StringUtils.isNotEmpty(typeId)){
			ProductType type = new ProductType();
			type.setTypeId(Integer.parseInt(typeId));
			product.setProductType(type);
		}
		
		product.setProductCreateDate(new Date());
		String imageUrls[]=req.getParameterValues("productIntroduceImg");//获取多个介绍图地址
		if(imageUrls.length > 0){
			product.setProductIntroduceImg(imageUrls[0]);	//将第一个介绍图存入 基本信息表
		}
		Integer n = productService.addProduct(product);	//n 是productid
		if(n != null && n.intValue() > 0){
			String imgStr = req.getParameter("productsInfoProductdesc");
			if(n.intValue() > 0){
				//添加商品图文
				if(StringUtils.isNotEmpty(imgStr)){
					ProductImageText imageText = new ProductImageText();
					imageText.setImagetextContext(imgStr);
					imageText.setImagetextProduectId(n);
					imageText.setImagetextCreateDate(new Date());
					productImageTextService.addProductImageText(imageText);
					
				}
				//添加商品介绍图片
				ProductPicture pp = new ProductPicture();
				for(int i= 1 ; i <= imageUrls.length-1;i++){//去掉第一个介绍图 
					pp.setPictureProductId(n);
					pp.setPictureUrl(imageUrls[i]);
					pp.setPictureCreateDate(new Date());
					productPictureService.addProductPicture(pp);
				}
			}
		}
		if(n > 0){
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加成功！"));
			
			// 缓存
			productInfoService.cacheIndexPageProduct();
		}else{
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败！"));
		}
			
		return mv;
	}
	
	/**
	 * 进入修改页面
	 * 2016年4月22日
	 * @author 穆再兴
	 * @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<ProductType> typelist = productTypeService.getAll();
			mv.addObject("typeList", typelist);
			//查出该产品的一条图文信息
			ProductImageText imageText = productImageTextService.getProductImageTextByProduectId(Integer.parseInt(productId));
			//根据产品id查出所有介绍图
			List<ProductPicture> list = productPictureService.getProductPictureByproductId(Integer.parseInt(productId));
			
			mv.addObject("product", product);
			mv.addObject("imageText", imageText);
			mv.addObject("pictureList",list);
		}
		return mv;
	}
	
	/**
	 * 修改产品信息 
	 * 2016年4月22日
	 * @author 穆再兴
	 * @param product
	 * @return
	 */
	@RequestMapping("/update")
	public ModelAndView updateProduct(HttpServletRequest req,Product product){
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		if(product != null){
			//设置产品类型
			String typeId = req.getParameter("typeId");
			if(StringUtils.isNotEmpty(typeId)){
				ProductType type = new ProductType();
				type.setTypeId(Integer.parseInt(typeId));
				product.setProductType(type);
			}
			
			String imgStr = req.getParameter("productsInfoProductdesc");
			/* 修改商品图文 */
			if(StringUtils.isNotEmpty(imgStr)){
				ProductImageText imageText = productImageTextService.getProductImageTextByProduectId(product.getProductId());
				if(null != imageText){
					imageText.setImagetextContext(imgStr);
					productImageTextService.updateProductImageTextById(imageText);
				}
			}
			
			/* 添加商品介绍图片 去掉重复的<url一样的图> */
			ProductPicture pp = new ProductPicture();
			String imageUrls[]=req.getParameterValues("productIntroduceImg");//获取多个介绍图地址
			for(int i= 1 ; i <= imageUrls.length-1;i++){
				pp.setPictureProductId(product.getProductId());
				pp.setPictureUrl(imageUrls[i]);
				pp.setPictureCreateDate(new Date());
				productPictureService.addProductPicture(pp);
			}
			
			product.setProductIntroduceImg(imageUrls[0]);
			
			Integer i = productService.updateProductByProductId(product);
			if(i == 0){
				mv.addObject("msgObj", new MessageDTO(false, "操作结果", "修改失败！"));
			}else{
				mv.addObject("msgObj", new MessageDTO(true, "操作结果", "修改成功！"));
				// 缓存
				productInfoService.cacheIndexPageProduct();
			}
		}
		
		return mv;
	}
	
	/**
	 * 修改商品状态
	 * 2016年4月22日
	 * @param request
	 * @param response
	 * @author 穆再兴
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public Map updateProductStatus(HttpServletRequest request,
			HttpServletResponse response,Product product) throws Exception {
		Map map=new HashMap();
		String productId = request.getParameter("productId");
		String productStatus = request.getParameter("productStatus");
		if("".equals(productId) || "".equals(productStatus)){
			//return "{'status':'修改失败！'}";
			map.put("status", "修改失败！");
			return  map;
		}
		product.setProductId(Integer.parseInt(productId));
		product.setProductStatus(Integer.parseInt(productStatus));
		
		Integer msg = productService.updateProductStatusByProductId(product);
		if(msg == 0){
			//return "{'status':'修改失败！'}";
			map.put("status", "修改失败！");
			return  map; 
		}
		// 缓存
		productInfoService.cacheIndexPageProduct();
		//return "{'status':'修改成功！'}";
		map.put("status", "修改成功！");
		return  map;
	}
	
	/**
	 * 删除商品图片 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("deleteProductImage")
	@ResponseBody
	public Map deleteProductPicture(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map map=new HashMap();
		String pictureId = request.getParameter("pictureId");
		if(StringUtils.isNotEmpty(pictureId)){
			Integer n = productPictureService.deleteProductPicture(Integer.parseInt(pictureId));
			if(n == 0){
				map.put("status", "删除失败！");
				return  map;
			}
		}
		//return "{\"status\":\"删除成功！\"}";
		map.put("status", "删除成功！");
		return  map;
	}
}
