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

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.lang.Character.Subset;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
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.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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.internal.matchers.SubstringMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
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.Log;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.model.Size;
import com.cloudcross.ssp.service.IAdGroupService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IBannerService;
import com.cloudcross.ssp.service.IBannerTemplateService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;
import com.cloudcross.ssp.service.ISizeService;
import com.cloudcross.ssp.service.impl.BannerService;
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.DateUtil.DateFmts;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SWFHeader;





/**
 * 创意创意列表。
 *
 * @author Dongjiapeng
 */
@Controller
@RequestMapping("/advertiser/main/ad/target/create-banner")
public class CreateBannerController extends SimpleController{
	private Logger LOG = Logger.getLogger(CreateBannerController.class);
	@Autowired
	IBannerTemplateService bat;
	@Autowired
	IBannerService bs;
	@Autowired
	IOrderService orderService ;
	@Autowired
	IAdvertiserService advs;
	@Autowired
	IAdGroupService adGroupService;
	@Autowired
	IBannerService bannerService;
	@Autowired
	ISizeService sizeService;
	@Autowired
	ILogService logService;
	@Autowired
	Config config;
//	@RequestMapping
//    public String index(Model model,@RequestParam Long adGroupId) {
//	model.addAttribute("adGroupId", adGroupId);
//	return redirect(page("list"));
//	}
	//文件系统可上传的文件后缀集合
		private static Set<String> noStuffixSet = new HashSet<String>();
				
			//初始化可上传文件后缀
		static {
				noStuffixSet.add("jpg");
				noStuffixSet.add("gif");
				noStuffixSet.add("png");
			}
	
	@RequestMapping("/list")
	public String list(Model model, @RequestParam Map<String, Object> paramMap,
			@RequestParam Long adGroupId,
			@RequestParam(defaultValue = "1") int page,HttpServletRequest request) {
		HttpSession session = request.getSession();
		paramMap.put("adGroupId", adGroupId);
		//根据投放名，查找所有创建列表找总数
		int totalRow = bs.countByParams(paramMap);
		LOG.debug("totalRow="+totalRow);
		AdGroup adGroup = adGroupService.findById(adGroupId);
		Long campaignId = adGroup.getCampaignId();
		Long orderId = adGroup.getOrderId();
		Order order = orderService.findById(orderId);
		LOG.debug("order==="+order);
		Long advertiserId = order.getAdvertiserId();
		model.addAttribute("campaignId", campaignId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("advertiserId", advertiserId);
	 //查询符合条件的创意
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<Banner> createBannerList = bs.findByParams(paramMap, pager);
		LOG.debug("createBannerList="+createBannerList);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("createBannerList", createBannerList);
		model.addAttribute("adGroupId", adGroupId);
		model.addAttribute("sessionid", session.getId());
		return page("list");
		}
	
	//删除之后状态变为-1 djp
	@RequestMapping("/delete")
	public @ResponseBody String delete(Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			bs.updateStatus(LangUtil.array2List(id), 
					Status.delete.value);
		}
		return OK;
	}
	

	@RequestMapping("/save")
	public  String save(HttpServletRequest request, Model model,@RequestParam Map<String, Object> paramMap,@RequestParam(required = false) Long adGroupId) {
	
		
		String bannerObjs = (String)paramMap.get("bannerObjs");
		LOG.debug(bannerObjs);
		//JSONArray result = new JSONArray(); // 用来存储转换结果的JSONArray
		List<Banner> bannerList = new ArrayList<Banner>();
		try{
			JSONArray jsonArray = new JSONArray(bannerObjs);// 传过来JSONArray
			LOG.debug("a111"+jsonArray);
//		}
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				Banner banner = new Banner();
				banner.setId(object.getLong("id"));
				banner = bs.findById(banner.getId());
				banner.setVisitAddress(object.getString("visitAddress"));
				banner.setClickAddress(object.getString("clickAddress"));
				banner.setImpressionAddress(object.getString("impressionAddress"));
				banner.getBannerTemplate().setName(object.getString("name"));
				
				/**
				 * 先得到编辑前的信息
				 */
				Banner formerBanner = bannerService.findById(banner.getId());
				
				((BannerService) bs).edit(banner);
				
				/**
				 * 编辑成功后，与以前的banner信息进行比较如果发生了变化，则添加修改记录
				 */
				//修改标志，默认为没有修改
				boolean updatedMark = false;
				//存储修改的字符串
				String str = "对原有的创意: " + formerBanner.getBannerTemplate().getName() + " 进行了修改:";
				//创意名称的比较
				if(!(formerBanner.getBannerTemplate().getName().equals(object.getString("name")))) {
					str = str + "创意名称" + " " + formerBanner.getBannerTemplate().getName() + "-->" + banner.getBannerTemplate().getName();
					updatedMark = true;
				}
				
				//到达地址的比较
				if(!(formerBanner.getVisitAddress().equals(banner.getVisitAddress()))) {
					str = str + "到达地址" + " " + formerBanner.getVisitAddress() + "-->" + banner.getVisitAddress();
					updatedMark = true;
				}
				
				//点击地址的比较
				if(!(formerBanner.getClickAddress().equals(banner.getClickAddress()))) {
					str = str + "点击地址" + " " + formerBanner.getClickAddress() + "-->" + banner.getClickAddress();
					updatedMark = true;
				}
				
				//曝光地址的比较
				if(!(formerBanner.getImpressionAddress().equals(banner.getImpressionAddress()))) {
					str = str + "曝光地址" + " " + formerBanner.getImpressionAddress() + "-->" + banner.getImpressionAddress();
					updatedMark = true;
				}
				
				Log log= new Log();
				//对应模块
				log.setModule("Ad");
				//对应的表名
				log.setTableName("t_banner");
				//对应的bannerId
				log.setRecordId(banner.getId());
				//操作类型
				log.setActionType("编辑");	
				//变更详情
				log.setAction(str);
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(new Long(getLoginUser().getId()));
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(getLoginUser().getAccountName());
				
				//判断是否编辑前后的投放信息如果真的改变则添加修改日志
				if(updatedMark) {
				logService.add(log); 
			}
				
				
				bannerList.add(banner);	
				LOG.debug("a222="+bannerList);
			}
		}catch (JSONException e) {
				// TODO Auto-generated catch block
				LOG.info("@@@@@@@@解析错误");
				e.printStackTrace();
			}

		model.addAttribute("adGroupId", adGroupId);
		return redirect(page("../ad/list"));
	
	}
	
	
	@RequestMapping(value="/upload")  

	public @ResponseBody String upload(Model model,HttpServletResponse response,HttpServletRequest request) throws IOException{  
		String uploadName;
		String fileType;
		//文件路径
		String path;
		//缩略图路径
		String pathSmall;
		String responseStr="null";
		int width;
		int height;
		//广告位宽高
		int _width;
		int _height;
		Long adGroupId = 1l;
	 
	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() !=""){  
					
					//处理上传文件路径
					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();
				//匹配广告位
				 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));	
				adGroupId =Long.parseLong(ids[0]);
				AdGroup adGroup = adGroupService.findById(adGroupId);
				Long campaignId = adGroup.getCampaignId();
				Long orderId = adGroup.getOrderId();
				Order order = orderService.findById(orderId); 
				Long advertiserId = order.getAdvertiserId();
				Advertiser advertiser = advs.findById(advertiserId);
				Long agentId = advertiser.getAgentId();
				model.addAttribute("campaignId",campaignId);
				model.addAttribute("orderId",orderId);
				model.addAttribute("advertiserId",advertiserId);
				model.addAttribute("agentId", agentId);
				
				bannerTemplate.setName(uploadName);
				bannerTemplate.setType(judgeType(fileType));
				bannerTemplate.setStatus(0);
				bannerTemplate.setAdvertiserId(advertiserId);
				bannerTemplate.setAgentId(agentId);
				//添加素材
				bat.add(bannerTemplate);
				
				//创建创意
				Banner banner = new Banner();
				banner.setBannerTemplate(bannerTemplate);
				banner.setAdGroupId(adGroupId);
				banner.setBannerTemplateId(bannerTemplate.getId());
				banner.setCampaignId(campaignId);
				banner.setOrderId(orderId);
				banner.setChecked(1);
				banner.setMemo("");
				banner.setStatus(0);
				banner.setVisitAddress("visitAddress");
				banner.setClickAddress("clickAddress");
				banner.setImpressionAddress("impressionAddress");
				//添加创意，如果添加成功则添加新增日志
				if(bannerService.add(banner)) {
					Log log = new Log();
					//对应模块，这里应该是投放模块
					log.setModule("Ad");
					//对应的表名，这里是t_adgroup
					log.setTableName("t_banner");
					//对应的投放id
					log.setRecordId(banner.getId());
					//对应的操作类型
					log.setActionType("新增");
					//变更详情
					log.setAction("新增了创意：" + bannerTemplate.getName());
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
					
				}
				
						}
					}
				}
			}catch(IOException e){
						
						responseStr="上传失败";
						return responseStr;
			}
			
		}	
				return responseStr; 
	}
	
	
	
	 //取素材的大小
	public BannerTemplate setWidthAndHeight(BannerTemplate bannerTemplate,String urls,String fileType){
	    //本地上传的文件
					 if("jpeg".equalsIgnoreCase(fileType)||"jpg".equalsIgnoreCase(fileType) ||"gif".equalsIgnoreCase(fileType)||"png".equalsIgnoreCase(fileType)){
						 //把文件读取到本地	
						 File file = new File(urls);
						 	FileInputStream istream = null;
							try {
								istream = new FileInputStream(file);
							} catch (FileNotFoundException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							BufferedImage image=null;
							try {
								image = javax.imageio.ImageIO.read(istream);
							} catch (IOException e) {
								e.printStackTrace();
							}
							if(image!=null){
								bannerTemplate.setWidth((long)image.getWidth());
								bannerTemplate.setHeight((long)image.getHeight());
							}else{
								System.out.println("aaaa");
							}
							try {
								istream.close();
							} catch (IOException e) {
								
								e.printStackTrace();
							}
					 }else if("swf".equalsIgnoreCase(fileType)){      //swf文件类型的设置
						 File file=new File(urls);
							SWFHeader swfh = new SWFHeader();
							try {
								swfh = SWFHeader.load(file);
								bannerTemplate.setWidth((long)swfh.getWidth());
								bannerTemplate.setHeight((long)swfh.getHeight());
							} catch (IOException e) {
								// TODO Auto-generated catch block
								
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								// TODO Auto-generated catch block
								
								e.printStackTrace();
							}
					 }

		return bannerTemplate;
	}
	

	
//获取上传文件的绝对路径
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;
	}
}
		 	 
	
	

