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");
		}

	@RequestMapping
	public String index(Model model, 
			@RequestParam Map<String, Object> paramMap) {
		// 查询符合条件的广告策略
		Account loginUser = getLoginUser();
		Long agentId = loginUser.getAgentId();
		paramMap.put("agentId", agentId);
		int totalRow = bannerTemplateService.countByParams2(paramMap);
		Pager pager = new Pager();
		pager.setPage(1);
		pager.setTotalRow(totalRow);
		//获取尺寸的列表
		List<Size> sizeList = sizeService.findAllSize();
		//获取创意的列表
		List<BannerTemplate> bannerTemplateList = bannerTemplateService.findByParams2(paramMap, pager);
		model.addAllAttributes(paramMap);
		model.addAttribute("bannerTemplateList", bannerTemplateList);
		model.addAttribute("sizeList", sizeList);
		model.addAttribute("pager", pager);
		return page("index");
	}

	/**
	 * 显示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("width", paramMap.get("width"));
		model.addAttribute("height", paramMap.get("height"));
		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,HttpServletResponse response,HttpServletRequest request,Long advertiserId) throws IOException{  
		String uploadName;
		String fileType;
		//文件路径
		String path;
		//缩略图路径
		String pathSmall;
		String responseStr="null";
		int width;
		int height;
		//广告位宽高
		int _width;
		int _height;
		Account loginUser = getLoginUser();
		Long agentId = loginUser.getAgentId();
	 
	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){ 
				//取得当前上传文件的文件名称(不加路径)  
				uploadName = file.getOriginalFilename();  
				
				//获取文件类型
				 fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
				 
				//判断文件类型
				  if(!noStuffixSet.contains(fileType)){
						return "不支持此文件类型";
					}
				  
				//如果名称不为“”,说明该文件存在，否则说明该文件不存在  
				if(uploadName.trim() !=""){  

//					//命名上传后的缩略图文件名  
//					String fileName = "small_".concat(file.getOriginalFilename()); 
					
					
					//处理上传文件路径
					path = getLocalFilePath(uploadName);
					System.out.println("qqqqqqq+==="+path);
					
					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=suitSize(width,height, bannerTemplate);
					//图片匹配
						if(bannerTemplate==null){
							return "图片尺寸错啦！！";
						}
					 _width =Integer.parseInt(bannerTemplate.getWidth().toString()) ;
					 _height = Integer.parseInt(bannerTemplate.getHeight().toString());	
					
				//取上传文件父级目录
				String absolutePath = localFile.getParentFile().getAbsolutePath();
				//生成缩略图路径名
				pathSmall = absolutePath.concat(File.separator).concat("small_").concat(uploadName);
				//生成缩略图
				compressPicture(localFile,pathSmall,150,60);
				//判断是否需要缩放
				if((width*_height)==(_width*height)){
					//压缩文件上传路径
					 String compressPath =absolutePath.concat(File.separator).concat("compress_").concat(uploadName);
					 //生成压缩图
					 compressPicture(localFile,pathSmall, _width,_height);
					//设置文件上传路径
					 bannerTemplate.setPath(replacePath(compressPath));
				 }else{
					 //设置文件上传路径
					 bannerTemplate.setPath(replacePath(path));
				 }
				responseStr="上传成功";
				//设置缩略图文件路径
				bannerTemplate.setPathSmall(replacePath(pathSmall));
				bannerTemplate.setName(uploadName);
				bannerTemplate.setType(judgeType(fileType));
				bannerTemplate.setStatus(0);
				bannerTemplate.setAdvertiserId(advertiserId);
				bannerTemplate.setAgentId(agentId);
			
				//添加素材
				bannerTemplateService.add(bannerTemplate);
				
				}
			  }
			}
		 }catch(IOException e){
						
						responseStr="上传失败";
						return responseStr;
			}	
		}	
		  return responseStr; 
	}
	
	
	@RequestMapping(value="/replace")  

	public @ResponseBody String replace(Model model,HttpServletResponse response,HttpServletRequest request,Long bannerTemplateId) throws IOException{  
		String uploadName;
		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){ 
				//取得当前上传文件的文件名称(不加路径)  
				uploadName = file.getOriginalFilename();  
				
				//获取文件类型
				 fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
				 
				 //判断文件类型
				  if(!noStuffixSet.contains(fileType)){
						return "不支持此文件类型";
					}
				 
				//如果名称不为“”,说明该文件存在，否则说明该文件不存在  
				if(uploadName.trim() !=""){  
					
					//处理上传文件路径
					path = getLocalFilePath(uploadName);
					
					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.getWidth().toString()) ;
					 _height = Integer.parseInt(bannerTemplate.getHeight().toString());
					//取上传文件父级目录
					String absolutePath = localFile.getParentFile().getAbsolutePath();
					//生成缩略图路径名
					pathSmall = absolutePath.concat(File.separator).concat("small_").concat(uploadName);
					//生成缩略图
					compressPicture(localFile,pathSmall,150,60);
					
					if((width*_height)==(_width*height)){
						//压缩文件上传路径
						 String compressPath =absolutePath.concat(File.separator).concat("compress_").concat(uploadName);
						 //生成压缩图
						 compressPicture(localFile,pathSmall, _width,_height);
						//设置文件上传路径
						 bannerTemplate.setPath(replacePath(compressPath));
					 }else{
						 if(width>_width||height>_height){
							 return "图片尺寸错啦！！";
						 }
						 //设置文件上传路径
						 bannerTemplate.setPath(replacePath(path));
					 }
				
					//设置缩略图文件路径
					bannerTemplate.setPathSmall(replacePath(pathSmall));
					bannerTemplate.setName(uploadName);
					bannerTemplate.setType(judgeType(fileType));
				//更新素材
				bannerTemplateService.edit(bannerTemplate);
				responseStr="上传成功";
				}
			  }
			}
		 }catch(IOException e){
						
						responseStr="上传失败";
						return responseStr;
			}	
		}	
		  return responseStr; 
	}
	
	

	
//处理上传文件的绝对路径
public String getLocalFilePath(String fileName){
					Account loginUser = getLoginUser();
					// 计算相对路径名，即不包括默认路径名
					String path = new StringBuilder()
							.append(File.separator)
							.append(loginUser == null ? "anon" : loginUser.getId())							
							.append(File.separator)
							.append(DateUtil.getDate(DateFmts.YYYYMMDD))
							.append(File.separator)
							.append(System.currentTimeMillis())
							.append(File.separator)
							.append(fileName)
							.toString();
					
					String localFilePath = config.getResourceUploadDir().concat(File.separator).concat("banner").concat(path);
					
//					// 计算在容器中实际路径名,添加文件所运行所在的实际目录
					String accessUrl = localFilePath;
					ServletContext servletContext = getServletContext();
						if (servletContext == null) {
							LOG.debug("单体测试情况，servletContext不存在。");
						} else {
						
							accessUrl = servletContext.getRealPath("/");
							File upFile = new File(accessUrl);
							accessUrl = upFile.getParent();
							LOG.info("\naaa----"+localFilePath+" -----"+accessUrl);
					//		获取绝对路径
							localFilePath = accessUrl.concat(File.separator).concat(localFilePath);
					}
					return localFilePath;
				}

//处理路径为web路径
	public String replacePath(String path){
		
		path = path.substring(path.indexOf("upload")-1);

	return path;
	}			
					
//判断文件类型				
public int judgeType(String fileType){
					int type = 2;
					if("jpg".equalsIgnoreCase(fileType)||"jpeg".equalsIgnoreCase(fileType)||"gif".equalsIgnoreCase(fileType)||"png".equalsIgnoreCase(fileType) ){
						type = 2;
					}else if("flv".equalsIgnoreCase(fileType)||"mp4".equalsIgnoreCase(fileType)){
						type = 3;
					}else{
						type = 1;
					}
					return type;
				}

	//生成缩略图
	public void compressPicture(File localFile,String pathNew,int width,int height) throws IOException{
		//新建缩略图文件
		File newFile = new File(pathNew);
		if (!newFile.getParentFile().exists()){
			newFile.getParentFile().mkdirs();
		}	
		//构造image图片
		Image src = javax.imageio.ImageIO.read(localFile);
		//表示该图像具有打包成整数的像素的8 位RGB颜色分量
		BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		//h绘制缩小后的图片
		tag.getGraphics().drawImage(src, 0, 0, width, height, null);
		//生成缩略图
		ImageIO.write(tag, "png", newFile);
	}

//匹配广告为宽高，用取平方差最小
public BannerTemplate suitSize(int width,int height,BannerTemplate bannerTemplate) throws IOException{

	//构造image图片

		long max_width = 0;
		long max_height = 0;
		Size size = new Size();		
		int i;
		int n =0; 
		//查找所有广告位
		List<Size> sizeList = sizeService.findAllSize();
		//取平方差
		double suit[] = new double[sizeList.size()];
		long _width[] = new long[sizeList.size()];
		long _height[] = new long[sizeList.size()];
		for ( i=0 ;i<sizeList.size();i++){
			size = sizeList.get(i); 
			_width[i] = size.getWidth(); 
			_height[i] = size.getHeight();
			if(width<_width[i]&&height<_height[i]){
				suit[i] =Math.sqrt(Math.abs(width-_width[i])*Math.abs(width-_width[i])+Math.abs(height-_height[i])*Math.abs(height-_height[i]));
			}else{
				if((width*_height[i])==(_width[i]*height)){
					suit[i] =Math.sqrt(Math.abs(width-_width[i])*Math.abs(width-_width[i])+Math.abs(height-_height[i])*Math.abs(height-_height[i]));
				}else{
				suit[i]=0;
				}
			}
			
			}
		
			//取最小值
			double min=10000;
			for (i=0;i<suit.length;i++){
				if(suit[i]!=0){			
					if (suit[i]<min){						
						min = suit[i];
						n=i;
					}	
				}	
			}
		if(min==10000){
				bannerTemplate=null;
			}else{
	
		bannerTemplate.setWidth(_width[n]);
		bannerTemplate.setHeight(_height[n]);
		}	
		return bannerTemplate;
	}



}
