package com.cloudcross.ssp.web.advertiser.main.ad;



import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.mail.Session;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AdGroup;
import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Banner;
import com.cloudcross.ssp.model.BannerTemplate;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.model.Size;
import com.cloudcross.ssp.service.IBannerTemplateService;
import com.cloudcross.ssp.service.ISizeService;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.DateUtil;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SWFHeader;
import com.cloudcross.ssp.common.utils.DateUtil.DateFmts;


/**
 * 创意中心(创意模板)功能相关页面。
 * 
 * @author Wanfu
 */
@Controller
@RequestMapping("/advertiser/main/ad/banner-template")
public class BannerTemplateController extends SimpleController {
	private static final Logger LOG = Logger
			.getLogger(BannerTemplateController.class);

	@Autowired
	private IBannerTemplateService bannerTemplateService;
	
	@Autowired
	private ISizeService sizeService;
	@Autowired
	Config config;
	
	//文件系统可上传的文件后缀集合
	private static Set<String> noStuffixSet = new HashSet<String>();
			
		//初始化可上传文件后缀
	static {
			noStuffixSet.add("jpg");
			noStuffixSet.add("gif");
			noStuffixSet.add("png");
		}

	/**
	 * 显示list方法。
	 * 根据创意尺寸，创意类型，状态显示相应的素材。
	 * 根据搜索框输入的姓名搜索显示相应的素材列表。
	 */
	@RequestMapping("/list")
	public String list(Model model, 
			@RequestParam Map<String, Object> paramMap,
			@RequestParam(defaultValue = "1") int page
			//HttpServletRequest request
			) {
		//HttpSession session = request.getSession();
		model.addAttribute("rwidth", paramMap.get("rwidth"));
		model.addAttribute("rheight", paramMap.get("rheight"));
		model.addAttribute("type", paramMap.get("type"));
		model.addAttribute("status", paramMap.get("status"));
		model.addAttribute("advertiserId",paramMap.get("advertiserId"));
		Account loginUser = getLoginUser();
		Long agentId = loginUser.getAgentId();
		paramMap.put("agentId", agentId);
		// 根据广告策略名模糊统计符合条件的策略总数
		int totalRow = bannerTemplateService.countByParams2(paramMap);
		// 查询符合条件的广告策略
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		//获取创意的列表
		List<BannerTemplate> bannerTemplateList = bannerTemplateService.findByParams2(
				paramMap, pager);
		//获取尺寸的列表
		List<Size> sizeList = sizeService.findAllSize();
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("bannerTemplateList", bannerTemplateList);
		model.addAttribute("sizeList", sizeList);
		return page("list");
	}

	/**
	 * 单个或者批量启用功能。
	 * 删除将status更新为0值
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("/enable")
	public @ResponseBody String enable(Long[] id) {
		//输出log信息，控制台打印出id的值
		LOG.debug("Args's value: id=" + Arrays.toString(id));
		//将id转为List<Long>类型传入updateStatus函数
		if (ArrayUtils.isNotEmpty(id)) {
			bannerTemplateService.updateStatus(LangUtil.array2List(id),
					Status.enable.value);
		}
		return OK;
	}

	/**
	 * 单个或者批量禁用功能。 
	 * 删除将status更新为1值
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("/disable")
	public  @ResponseBody  String disable(Long[] id) {
		//输出log信息，控制台打印出id的值
		LOG.debug("Args's value: id=" + Arrays.toString(id));
		//将id转为List<Long>类型传入updateStatus函数
		if (ArrayUtils.isNotEmpty(id)) {
			bannerTemplateService.updateStatus(LangUtil.array2List(id),
					Status.disable.value);
		}
		return OK;
	}

	/**
	 * 单个或者批量删除功能。 
	 * 删除将status更新为-1值
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("/delete")
	public @ResponseBody
	String delete(Long[] id) {
		//将id转为List<Long>类型传入updateStatus函数
		if (ArrayUtils.isNotEmpty(id)) {
			bannerTemplateService.deleteUpdata(LangUtil.array2List(id),
					Status.delete.value);
		}
		return OK;
	}

	/**
	 * 修改素材名字功能。 
	 * 传入素材id和要修改的name
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("/alterName")
	public @ResponseBody String alterName(@RequestParam int id,
			@RequestParam String name) {
		//将id和name写入Map,ad-template.sql.xml读出使用
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("name", name);
		paramMap.put("id", id);
		bannerTemplateService.alterName(paramMap);
		return OK;
	}

	
	@RequestMapping(value="/upload")  

	public @ResponseBody String upload(Model model,HttpServletRequest request,Long advertiserId) throws IOException{  
		String uploadName;
		String resetName;
		String fileType;
		//文件路径
		String path;
		//缩略图路径
		String pathSmall;
		String responseStr="null";
		int width;
		int height;
		Account loginUser = getLoginUser();
		Long agentId = loginUser.getAgentId();
		Long operatorId = loginUser.getOperatorId();
 	 
	if(request.getMethod()=="POST"){ 
	
		//转	换成多部分request    
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
		
		String[] ids = multiRequest.getParameterValues("adGroupId");

		Map<String, MultipartFile> fileMap = multiRequest.getFileMap(); 
		try{
		//取得request中的所有文件名 
		  for(Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { 
			MultipartFile file = entity.getValue();
			BannerTemplate bannerTemplate = new BannerTemplate();
			if(file != null && file.getSize()<1024*2*1000){ 
				System.out.println(file.getSize());
				//取得当前上传文件的文件名称(不加路径)  
				uploadName = file.getOriginalFilename();  
				resetName = bannerTemplateService.resetName(uploadName);
				//获取文件类型
				 fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
				 
				 
				//判断文件类型
				  if(!noStuffixSet.contains(fileType)){
						return "不支持此文件类型";
					}
				  
				//如果名称不为“”,说明该文件存在，否则说明该文件不存在  
				if(uploadName.trim() !=""){  
		
					//处理上传文件路径
					path = bannerTemplateService.getLocalFilePath(resetName);

					File localFile = new File(path); 
					//上传目录不存在，则新建目录
					if (!localFile.getParentFile().exists()){
						localFile.getParentFile().mkdirs();
					}
					//生成上传文件
					file.transferTo(localFile);
					//取上传图片的宽高
					 BufferedImage image = ImageIO.read(new FileInputStream(path));
					 width = image.getWidth();
					 height = image.getHeight();
					 
					 //匹配广告位
					 bannerTemplate=bannerTemplateService.suitSize(width,height, bannerTemplate);
					//图片匹配
						if(bannerTemplate==null){
							return "图片尺寸错啦！！";
						}
					
				//取上传文件父级目录
				String absolutePath = localFile.getParentFile().getAbsolutePath();
				//生成缩略图路径名
				pathSmall = absolutePath.concat(File.separator).concat("small_").concat(resetName);
				//生成缩略图
				bannerTemplateService.compressPicture(localFile,pathSmall,150,60);
				
				 //设置文件上传路径
				 bannerTemplate.setPath(bannerTemplateService.replacePath(path));
				
				
				//设置缩略图文件路径
				bannerTemplate.setPathSmall(bannerTemplateService.replacePath(pathSmall));
				bannerTemplate.setName(uploadName);
				bannerTemplate.setType(bannerTemplateService.judgeType(fileType));
				bannerTemplate.setStatus(0);
				bannerTemplate.setAdvertiserId(advertiserId);
				bannerTemplate.setAgentId(agentId);
				bannerTemplate.setOperatorId(operatorId);
			
				//添加素材
				bannerTemplateService.add(bannerTemplate);
				responseStr="上传成功";
				}
			  }else{
				  return "图片尺寸超过2M啦";
			  }
			
			}
		 }catch(IOException e){
				 return "上传失败";
			}	
		}	
		  return responseStr; 
	}
	
	
	@RequestMapping(value="/replace")  

	public @ResponseBody String replace(Model model,HttpServletRequest request,Long bannerTemplateId) throws IOException{  
		String uploadName;
		String resetName;
		String fileType;
		//文件路径
		String path;
		//缩略图路径
		String pathSmall;
		String responseStr="null";
		//图片宽高
		int width;
		int height;
		//广告位宽高
		int _width;
		int _height;
		BannerTemplate bannerTemplate =bannerTemplateService.findById(bannerTemplateId);
	if(request.getMethod()=="POST"){ 
	
		//转换成多部分request    
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

		Map<String, MultipartFile> fileMap = multiRequest.getFileMap(); 
		try{
		//取得request中的所有文件名 
		  for(Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { 
			MultipartFile file = entity.getValue();
			if(file != null && file.getSize()<1024*2*1000){ 
				//取得当前上传文件的文件名称(不加路径)  
				uploadName = file.getOriginalFilename();  
				resetName = bannerTemplateService.resetName(uploadName);
				
				//获取文件类型
				 fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
				 
				 //判断文件类型
				  if(!noStuffixSet.contains(fileType)){
						return "不支持此文件类型";
					}
				 
				//如果名称不为“”,说明该文件存在，否则说明该文件不存在  
				if(uploadName.trim() !=""){  
					
					//处理上传文件路径
					path = bannerTemplateService.getLocalFilePath(resetName);
					
					File localFile = new File(path); 
					//上传目录不存在，则新建目录
					if (!localFile.getParentFile().exists()){
						localFile.getParentFile().mkdirs();
					}	
					//生成上传文件
					file.transferTo(localFile);
					//取上传图片的宽高
					 BufferedImage image = ImageIO.read(new FileInputStream(path));
					 width = image.getWidth();
					 height = image.getHeight();
					 _width =Integer.parseInt(bannerTemplate.getRwidth().toString()) ;
					 _height = Integer.parseInt(bannerTemplate.getRheight().toString());
					//取上传文件父级目录
					String absolutePath = localFile.getParentFile().getAbsolutePath();
					//生成缩略图路径名
					pathSmall = absolutePath.concat(File.separator).concat("small_").concat(resetName);
					//生成缩略图
					bannerTemplateService.compressPicture(localFile,pathSmall,150,60);
					
					if((width*_height)==(_width*height)){
						bannerTemplate.setWidth((long)width);
						bannerTemplate.setHeight((long)height);
					 }else{
							 return "图片尺寸错啦！！";
						 }
					//设置文件上传路径
					bannerTemplate.setPath(bannerTemplateService.replacePath(path));					
				
					//设置缩略图文件路径
					bannerTemplate.setPathSmall(bannerTemplateService.replacePath(pathSmall));
					bannerTemplate.setName(uploadName);
					bannerTemplate.setType(bannerTemplateService.judgeType(fileType));
				//更新素材
				bannerTemplateService.edit(bannerTemplate);
				responseStr="上传成功";
				}
			  }else{
				  return "图片尺寸超过2M啦";
			  }
			}
		 }catch(IOException e){
				  return "上传失败";
			}	
		}	
		  return responseStr; 
	}


}
