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

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.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.ModelAttribute;
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.CommonsMultipartResolver;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
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.Common;
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.SqlHelper;
import com.cloudcross.ssp.common.utils.DateUtil.DateFmts;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AdGroup;
import com.cloudcross.ssp.model.Banner;
import com.cloudcross.ssp.model.BannerTemplate;
import com.cloudcross.ssp.model.Campaign;
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.ICampaignService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;
import com.cloudcross.ssp.service.ISizeService;


/**
 * 广告投放创意管理相关界面
 * @author chenyou
 *
 */
@Controller
@RequestMapping("/advertiser/main/ad/target/ad")
public class AdController extends SimpleController {
	private static final Logger LOG = Logger.getLogger(AdGroupController.class);
	@Autowired
	private IAdGroupService adGroupService;
	@Autowired
	private IAdvertiserService advertiserService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IBannerService bannerService;
	@Autowired
	private IBannerTemplateService bannerTemplateService;
	@Autowired
	private ILogService logService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	private ICampaignService campaignService;
	@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");
				}
		

	/**
	 * 创意管理列表页
	 * 前端需要传递四个参数，分别是广告主id（advertiserId），订单id（orderId），活动id（campaignId），投放id（adGroupId）
	 * 默认的广告主id,订单id,活动id，投放id传递过来的就是全部的，这时传过来的值为-1，或者不传或者传一个空值也是表示全部的
	 * 注：当广告主id传过来时是代表全部广告主时说明该登录账号是一个广告主代理商账号，这时查找的就是该代理商下的全部广告主的信息
	 * 还有页面搜索的时候是按创意名称进行搜索
	 * @param model
	 * @param paramMap
	 * @param selectedStatus 选择的状态变量，默认的是全部，为空值或者是“-1”
	 * @param adGroupId
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "2") int selectedStatus,
			@RequestParam(defaultValue = "1") int page
			) {
		LOG.debug("请求参数：page=" + page + "," + paramMap);
		
		Long adGroupId = null;
		Long campaignId = null;
		Long orderId = null;
		Long advertiserId = null;
		int totalRow = 0;
		Pager pager = null;
		List<Banner> bannerList = null;
		
		/**
		 * 对传入的数据做处理
		 * 第一：如果传入的投放id值为空或者空字符串或者是-1的话则表名投放id代表的是全部的投放这时让它的值设为-1，并且加上一个活动标志它的值设为全部（它用在sql语句的判断上）
		 * 第二：如果传入的活动id值为空值或者空字符串或者是-1的话如果投放id的值为-1的话这时让活动id的值设为-1，并且加上一个活动标志它的值设为全部（它用在sql语句的判断上）
		 * 否则活动id值为通过投放id查找到的活动id的值
		 * 第三：如果传入的订单id值为空值或者空字符串或者是-1的话，这时不能够直接认为它是全部的订单，要对活动id进行判断一下，如果活动id是全部活动的话，那么这时就是全部的订单，订单
		 * id就设为-1并且加上一个订单标志值设为全部，否则订单id的值为通过活动id查找到的订单id值
		 * 第四：如果传入的广告主id值为空值或者空字符串或者是-1的话则，这时也不能够直接认为它是全部的广告主，要对订单id进行判断，如果订单id是全部订单的话，那么这是就是全部广告主
		 * 这时广告主id的值为-1，同时通过当前登录账号得到代理商的id，使查出来的信息是该登录账号下的全部广告主，否则广告主id的值为通过订单id查找到的广告主id值
		 * 
		 */
		if(null == paramMap.get("adGroupId") || "".equals(paramMap.get("adGroupId")) 
				|| "-1".equals(paramMap.get("adGroupId"))) {
			paramMap.put("adGroupMark", "全部");
			paramMap.put("adGroupId", -1l);
			paramMap.put("selectedadGroupName", "全部投放");
		} else {
			//将前端传过来的adGroupId变成Long型
			adGroupId = Long.parseLong(String.valueOf(paramMap.get("adGroupId")));
			paramMap.put("adGroupId", adGroupId);
			AdGroup adGroup = adGroupService.findById(adGroupId);
			paramMap.put("selectedadGroupName", adGroup.getAdGroupName());
		}
		
		
		if(null == paramMap.get("campaignId") || "".equals(paramMap.get("campaignId")) 
				|| "-1".equals(paramMap.get("campaignId"))) {
			
			if(null == adGroupId) {
				paramMap.put("campaignMark", "全部");
				paramMap.put("campaignId", -1l);
				paramMap.put("selectedcampaignName", "全部活动");
			} else {
				AdGroup adGroup = adGroupService.findById(adGroupId);
				campaignId = adGroup.getCampaignId();
				paramMap.put("campaignId", campaignId);
				Campaign campaignObj = campaignService.findById(Long.valueOf(paramMap.get("campaignId").toString()));
				paramMap.put("selectedcampaignName", campaignObj.getName());
			}
			
		} else {
			//将前端传过来的campaignId变成Long型
			campaignId = Long.parseLong(String.valueOf(paramMap.get("campaignId")));
			paramMap.put("campaignId", campaignId);
			Campaign campaignObj = campaignService.findById(campaignId);
			paramMap.put("selectedcampaignName", campaignObj.getName());
		}
		
		
		if(null == paramMap.get("orderId") || "".equals(paramMap.get("orderId")) 
				|| "-1".equals(paramMap.get("orderId"))) {
			
			if(campaignId == null) {
				paramMap.put("orderMark", "全部");
				paramMap.put("orderId", -1l);
				paramMap.put("selectedorderName", "全部订单");
			} else {
				Campaign campaign = campaignService.findById(campaignId);
				orderId = campaign.getOrderId();
				paramMap.put("orderId", orderId);
				String orderName = orderService.selectOrderNameById(orderId);
				paramMap.put("selectedorderName", orderName);
			}
			
		} else {
			
			//将前端传过来的orderId变成Long型
			orderId = Long.parseLong(String.valueOf(paramMap.get("orderId")));
			paramMap.put("orderId", orderId);
			String orderName = orderService.selectOrderNameById(orderId);
			paramMap.put("selectedorderName", orderName);
		}
		
		
		if(null == paramMap.get("advertiserId") || "".equals(paramMap.get("advertiserId")) 
				|| "-1".equals(paramMap.get("advertiserId"))) {
			
			if(orderId == null) {
				paramMap.put("agentId", getLoginUser().getAgentId());
				paramMap.put("advertiserId", -1l);
				paramMap.put("selectedadvertiserName", "全部广告主");
			} else {
				paramMap.put("agentId", null);
				Order order = orderService.findById(orderId);
				advertiserId = order.getAdvertiserId();
				paramMap.put("advertiserId", advertiserId);
				String advertiserName = advertiserService.selectAdvertiserNameById(advertiserId);
				paramMap.put("selectedadvertiserName", advertiserName);
			}
			
		} else {
			paramMap.put("agentId", null);
			//将前端传过来的advertiserId变成Long型
			advertiserId = Long.parseLong(String.valueOf(paramMap.get("advertiserId")));
			paramMap.put("advertiserId", advertiserId);
			String advertiserName = advertiserService.selectAdvertiserNameById(advertiserId);
			paramMap.put("selectedadvertiserName", advertiserName);
		}
		
		
		Integer status = null;
		//对状态值进行判断2-表示全部，1-表示暂停，0-表示开启
		if(null == paramMap.get("selectedStatus") || "".equals(paramMap.get("selectedStatus")) 
				|| "2".equals(paramMap.get("selectedStatus"))) {
			status = null;
			paramMap.put("status", status);
		} else {
			status = Integer.parseInt(String.valueOf(paramMap.get("selectedStatus")));
			paramMap.put("status", status);
		}
		
		// 这里的搜索只是对投放创意名称进行搜索
				String bannerTemplateName = null;
				if (null != paramMap.get("searchValue")) {
					try {
						bannerTemplateName = new String((String.valueOf(paramMap
								.get("searchValue"))).getBytes("ISO-8859-1"), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
		paramMap.put("bannerTemplateName", SqlHelper.doLike(bannerTemplateName));
		paramMap.put("searchValue", bannerTemplateName);
		
		// 根据条件查询符合条件的创意总数
		totalRow = bannerService.countByParams1(paramMap);
		// 查询符合条件的广告创意
		pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		bannerList = bannerService.findByParams1(paramMap, pager);
		
		paramMap.put("selectedStatus", selectedStatus);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("bannerList", bannerList);
		return page("list");
	}

	@RequestMapping("/enable")
	public @ResponseBody
	String enable(HttpServletRequest request, Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到创意名称
			List<String> nameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Banner banner = bannerService.findById(id[i]);
				BannerTemplate bannerTemplate = bannerTemplateService.findById(banner.getBannerTemplateId());
				nameList.add(bannerTemplate.getName());
			}
			
			//如果开启成功，则增加对应的修改记录
			if(bannerService.updateStatus1(LangUtil.array2List(id),
					Status.enable.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是创意
					log.setModule("Ad");
					//对应的表名，这里是t_banner
					log.setTableName("t_banner");
					//对应的创意id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("开启");
					//变更详情
					log.setAction("开启了创意：" + nameList.get(i));
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
			
		}
		return OK;
	}

	@RequestMapping("/disable")
	public @ResponseBody
	String disable(HttpServletRequest request, Long[] id) {
		
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到创意名称
			List<String> nameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Banner banner = bannerService.findById(id[i]);
				BannerTemplate bannerTemplate = bannerTemplateService.findById(banner.getBannerTemplateId());
				nameList.add(bannerTemplate.getName());
			}
			
			//如果停用成功，则增加对应的修改记录
			if(bannerService.updateStatus1(LangUtil.array2List(id),
					Status.disable.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是创意
					log.setModule("Ad");
					//对应的表名，这里是t_banner
					log.setTableName("t_banner");
					//对应的创意id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("停用");
					//变更详情
					log.setAction("停用了创意：" + nameList.get(i));
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
			
		}
		return OK;
	}

	/**
	 * 批量删除时只是把这些选中的行的状态改为-1，并没有把它从表里面删掉
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	public @ResponseBody
	String delete(HttpServletRequest request, Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到创意名称
			List<String> nameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Banner banner = bannerService.findById(id[i]);
				BannerTemplate bannerTemplate = bannerTemplateService.findById(banner.getBannerTemplateId());
				nameList.add(bannerTemplate.getName());
			}
			
			//如果删除成功，则增加对应的修改记录
			if(bannerService.updateStatus1(LangUtil.array2List(id),
					Status.delete.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是创意
					log.setModule("Ad");
					//对应的表名，这里是t_banner
					log.setTableName("t_banner");
					//对应的创意id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("删除");
					//变更详情
					log.setAction("删除了创意：" + nameList.get(i));
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
			
		}
		return OK;
	}
	
	/**
	 * 
	 * @param 编辑创意  djp
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(Model model, @RequestParam HashMap<String, Object> paramMap
			,HttpServletRequest request) {
		// 根据id从数据库中查询创意。
		HttpSession session = request.getSession();
		Banner banner = bannerService.findById(Long.valueOf(paramMap.get("bannerId").toString()));
		Long adGroupId = banner.getAdGroupId();
		model.addAttribute("adGroupId", adGroupId);
		model.addAttribute("banner",banner);
		model.addAttribute("sessionid",session.getId());
		model.addAllAttributes(paramMap);
		return page("edit");
	}
	
	
	/**
	 *文件上传
	 * */
	@RequestMapping("/upload")
	public @ResponseBody String upload(HttpServletRequest request,HttpServletResponse response,Model model,Long bannerId) throws IOException{
	
	HttpSession session = request.getSession();	
	String uploadName = null;
	String path = null;
	String pathSmall = null;
	String fileType = null;
	String result = "null";	
	BannerTemplate bannerTemplate = bannerService.findById(bannerId).getBannerTemplate();
	// 创建一个通用的多部分解析器
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	// 判断 request 是否有文件上传,即多部分请求
		if(multipartResolver.isMultipart(request)){  
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			if(iter.hasNext()){
				//获得请求文件
				MultipartFile file = multiRequest.getFile(iter.next());
				//判断文件是否为空
				if(file != null){ 
					
					uploadName = file.getOriginalFilename();  
					//取上传文件类型
					fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
					
					//判断文件类型
					  if(!noStuffixSet.contains(fileType)){
							result = "~不支持此文件类型";
							return result;
						}
					  
					  
					//判断文件名书否存在
					if(uploadName.trim() !=""){  
	
						//添加上传文件标记
						String fileName = file.getOriginalFilename();  
						
						//获取上传路径
						path = getLocalFilePath(fileName);
						
				try{
						//新建上传路径下文件
						File localFile = new File(path);  
						if (!localFile.getParentFile().exists()){
							localFile.getParentFile().mkdirs();
						}
												
						//复制文件到上传文件
						file.transferTo(localFile);
						if(checkPic(localFile,bannerTemplate)){
							result = "~图片尺寸错啦！！";
							return result;
						}
												
					}catch(IOException e){
							e.printStackTrace();
							result="~文件上传失败 ";
							return result;
						}
					  
					}  			 
				}  
			} 
		}

		return path;
	}
	
	/**
	 * 
	 * @param model
	 * @param 编辑保存   djp
	 * @param paramMap
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/save")
	public String save(HttpServletRequest request, Model model, @ModelAttribute("form") Banner banner,
			@RequestParam Map<String, Object> paramMap) throws IOException {
			//图片宽高
			int width;
			int height;
			//广告位宽高
			int _width;
			int _height;
			//查找创意
			Banner formerBanner = bannerService.findById(banner.getId());
			//取模板素材
			BannerTemplate bannerTemplate = formerBanner.getBannerTemplate();
			
			
			if(paramMap.containsKey("uploadPath")&&paramMap.get("uploadPath")!=""
					&&paramMap.get("uploadPath")!=null){
				String uploadName = banner.getBannerTemplate().getName();
				String fileType = uploadName.substring(uploadName.lastIndexOf(".")+1);
				String filePath = (String)paramMap.get("uploadPath");
				
				
				//取上传文件位置
				File uploadFile = new File(filePath);
				if(!uploadFile.getParentFile().exists()){
					uploadFile.getParentFile().mkdirs();
				}
				//取上传文件父级目录
				String absolutePath = uploadFile.getParentFile().getAbsolutePath();
				//生成缩略图路径名
				String pathSmall = absolutePath.concat(File.separator).concat("small_").concat(uploadName);
				//生成缩略图
				compressPicture(uploadFile,pathSmall, 150,60);
				
				//取上传图片的宽高
				 BufferedImage image = ImageIO.read(new FileInputStream(filePath));
				 width = image.getWidth();
				 height = image.getHeight();
				 _width =Integer.parseInt(bannerTemplate.getWidth().toString()) ;
				 _height = Integer.parseInt(bannerTemplate.getHeight().toString());
				 
				 if(width>_width||height>_height){
					//设置压缩文件上传路径
					 String compressPath =absolutePath.concat(File.separator).concat("compress_").concat(uploadName);
					 //生成压缩图
					 compressPicture(uploadFile,pathSmall, _width,_height);
					//设置文件上传路径
					 bannerTemplate.setPath(replacePath(compressPath));
				 }else{
				 
					 //设置文件上传路径
					 bannerTemplate.setPath(replacePath(filePath));
				 }
				//设置缩略图上传路径
				bannerTemplate.setName(banner.getBannerTemplate().getName());
				bannerTemplate.setPathSmall(replacePath(pathSmall));
				bannerTemplate.setStatus(bannerTemplate.getStatus());
				bannerTemplate.setType(judgeType(fileType));
				bannerTemplateService.add(bannerTemplate);
				banner.setBannerTemplateId(bannerTemplate.getId());
				banner.setBannerTemplate(bannerTemplate);
				banner.setChecked(0);
				bannerService.updata(banner);
				
			}else{
				bannerService.edit(banner);
			}
			
				
				/**
				 * 编辑成功后，与以前的banner信息进行比较如果发生了变化，则添加修改记录
				 */
				//编辑后的创意对象
				banner = bannerService.findById(banner.getId());
				//修改标志，默认为没有修改
				boolean updatedMark = false;
				//存储修改的字符串
				String str = "对原有的创意: " + formerBanner.getBannerTemplate().getName() + " 进行了修改:";
				//创意名称的比较
				if(!(formerBanner.getBannerTemplate().getName().equals(banner.getBannerTemplate().getName()))) {
					str = str + "创意名称" + " " + formerBanner.getBannerTemplate().getName() + "-->" + banner.getBannerTemplate().getName();
					updatedMark = true;
				}
				
				
				//创意尺寸的比较
				if(formerBanner.getBannerTemplate().getHeight().longValue() != banner.getBannerTemplate().getHeight().longValue() || 
						formerBanner.getBannerTemplate().getWidth().longValue() != banner.getBannerTemplate().getWidth().longValue()) {
					str = str + "创意尺寸" + " " + formerBanner.getBannerTemplate().getWidth() + " x " +  formerBanner.getBannerTemplate().getHeight()
							+ "-->" + banner.getBannerTemplate().getWidth() + " x " +  banner.getBannerTemplate().getHeight();
					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); 
			}	
		model.addAttribute("adGroupId", banner.getAdGroupId());		
		return redirect(page("list"));
	}
	
	
	/**
	 * 创意信息修改记录显示
	 * 这里需要传递一个bannerId
	 * @param model
	 * @param paramMap
	 * @param page
	 * @return
	 */
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "1") int page) {
		// 查询总行数
		paramMap.put("tableName", "t_banner");
		paramMap.put("recordId", Long.parseLong(String.valueOf(paramMap.get("bannerId"))));
		int totalRow = logService.countByParams(paramMap,"Ad");
	
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
		List<Log> logList = logService.findByParams(paramMap, pager,"Ad");
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		return page("update");
	}
	
	/**
	 * 创意管理列表页导出excel功能的实现
	 * 前端需要传递四个参数，分别是广告主id（advertiserId），订单id（orderId），活动id（campaignId），投放id（adGroupId）
	 * 默认的广告主id,订单id,活动id，投放id传递过来的就是全部的，这时传过来的值为-1，或者不传或者传一个空值也是表示全部的
	 * 注：当广告主id传过来时是代表全部广告主时说明该登录账号是一个广告主代理商账号，这时查找的就是该代理商下的全部广告主的信息
	 * 还有页面搜索的时候是按创意名称进行搜索
	 * @param request
	 * @param response
	 * @param selectedStatus 选择的状态变量，默认的是全部，为空值或者是“-1”，0为开启，1为暂停
	 * @param paramMap
	 */
	@RequestMapping("/exportAdExcel")
	public void exportOtherReportExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(defaultValue = "2") int selectedStatus,
			@RequestParam Map<String, Object> paramMap) {
		
		Long adGroupId = null;
		Long campaignId = null;
		Long orderId = null;
		Long advertiserId = null;
		
		/**
		 * 对传入的数据做处理
		 * 第一：如果传入的投放id值为空或者空字符串或者是-1的话则表名投放id代表的是全部的投放这时让它的值设为-1，并且加上一个活动标志它的值设为全部（它用在sql语句的判断上）
		 * 第二：如果传入的活动id值为空值或者空字符串或者是-1的话如果投放id的值为-1的话这时让活动id的值设为-1，并且加上一个活动标志它的值设为全部（它用在sql语句的判断上）
		 * 否则活动id值为通过投放id查找到的活动id的值
		 * 第三：如果传入的订单id值为空值或者空字符串或者是-1的话，这时不能够直接认为它是全部的订单，要对活动id进行判断一下，如果活动id是全部活动的话，那么这时就是全部的订单，订单
		 * id就设为-1并且加上一个订单标志值设为全部，否则订单id的值为通过活动id查找到的订单id值
		 * 第四：如果传入的广告主id值为空值或者空字符串或者是-1的话则，这时也不能够直接认为它是全部的广告主，要对订单id进行判断，如果订单id是全部订单的话，那么这是就是全部广告主
		 * 这时广告主id的值为-1，同时通过当前登录账号得到代理商的id，使查出来的信息是该登录账号下的全部广告主，否则广告主id的值为通过订单id查找到的广告主id值
		 * 
		 */
		if(null == paramMap.get("adGroupId") || "".equals(paramMap.get("adGroupId")) 
				|| "-1".equals(paramMap.get("adGroupId"))) {
			paramMap.put("adGroupMark", "全部");
			paramMap.put("adGroupId", -1l);
			paramMap.put("selectedadGroupName", "全部投放");
		} else {
			//将前端传过来的adGroupId变成Long型
			adGroupId = Long.parseLong(String.valueOf(paramMap.get("adGroupId")));
			paramMap.put("adGroupId", adGroupId);
			AdGroup adGroup = adGroupService.findById(adGroupId);
			paramMap.put("selectedadGroupName", adGroup.getAdGroupName());
		}
		
		
		if(null == paramMap.get("campaignId") || "".equals(paramMap.get("campaignId")) 
				|| "-1".equals(paramMap.get("campaignId"))) {
			
			if(null == adGroupId) {
				paramMap.put("campaignMark", "全部");
				paramMap.put("campaignId", -1l);
				paramMap.put("selectedcampaignName", "全部活动");
			} else {
				AdGroup adGroup = adGroupService.findById(adGroupId);
				campaignId = adGroup.getCampaignId();
				paramMap.put("campaignId", campaignId);
				Campaign campaignObj = campaignService.findById(Long.valueOf(paramMap.get("campaignId").toString()));
				paramMap.put("selectedcampaignName", campaignObj.getName());
			}
			
		} else {
			//将前端传过来的campaignId变成Long型
			campaignId = Long.parseLong(String.valueOf(paramMap.get("campaignId")));
			paramMap.put("campaignId", campaignId);
			Campaign campaignObj = campaignService.findById(campaignId);
			paramMap.put("selectedcampaignName", campaignObj.getName());
		}
		
		
		if(null == paramMap.get("orderId") || "".equals(paramMap.get("orderId")) 
				|| "-1".equals(paramMap.get("orderId"))) {
			
			if(campaignId == null) {
				paramMap.put("orderMark", "全部");
				paramMap.put("orderId", -1l);
				paramMap.put("selectedorderName", "全部订单");
			} else {
				Campaign campaign = campaignService.findById(campaignId);
				orderId = campaign.getOrderId();
				paramMap.put("orderId", orderId);
				String orderName = orderService.selectOrderNameById(orderId);
				paramMap.put("selectedorderName", orderName);
			}
			
		} else {
			
			//将前端传过来的orderId变成Long型
			orderId = Long.parseLong(String.valueOf(paramMap.get("orderId")));
			paramMap.put("orderId", orderId);
			String orderName = orderService.selectOrderNameById(orderId);
			paramMap.put("selectedorderName", orderName);
		}
		
		
		if(null == paramMap.get("advertiserId") || "".equals(paramMap.get("advertiserId")) 
				|| "-1".equals(paramMap.get("advertiserId"))) {
			
			if(orderId == null) {
				paramMap.put("agentId", getLoginUser().getAgentId());
				paramMap.put("advertiserId", -1l);
				paramMap.put("selectedadvertiserName", "全部广告主");
			} else {
				paramMap.put("agentId", null);
				Order order = orderService.findById(orderId);
				advertiserId = order.getAdvertiserId();
				paramMap.put("advertiserId", advertiserId);
				String advertiserName = advertiserService.selectAdvertiserNameById(advertiserId);
				paramMap.put("selectedadvertiserName", advertiserName);
			}
			
		} else {
			paramMap.put("agentId", null);
			//将前端传过来的advertiserId变成Long型
			advertiserId = Long.parseLong(String.valueOf(paramMap.get("advertiserId")));
			paramMap.put("advertiserId", advertiserId);
			String advertiserName = advertiserService.selectAdvertiserNameById(advertiserId);
			paramMap.put("selectedadvertiserName", advertiserName);
		}
		
		
		Integer status = null;
		//对状态值进行判断2-表示全部，1-表示暂停，0-表示开启
		if(null == paramMap.get("selectedStatus") || "".equals(paramMap.get("selectedStatus")) 
				|| "2".equals(paramMap.get("selectedStatus"))) {
			status = null;
		} else {
			status = Integer.parseInt(String.valueOf(paramMap.get("selectedStatus")));
			paramMap.put("status", status);
		}
		

		// 这里的搜索只是对投放创意名称进行搜索
				String bannerTemplateName = null;
				if (null != paramMap.get("searchValue")) {
					try {
						bannerTemplateName = new String((String.valueOf(paramMap
								.get("searchValue"))).getBytes("ISO-8859-1"), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
		paramMap.put("bannerTemplateName", SqlHelper.doLike(bannerTemplateName));
		
		
		
		List<Banner> bannerList = null;
		bannerList = bannerService.findByParams1(paramMap);
		
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "report" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 7;
		paramMap.put("dataList", bannerList);
		paramMap.put("dataSize", bannerList.size());
		paramMap.put("column", column);
		String excelTemplate = templateProcessor.processTemplate(
				"excel/ad.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 投放信息修改记录的导出excel功能
	 * 需要传递一个bannerId
	 * @param request
	 * @param response
	 * @param paramMap
	 */
	@RequestMapping("/exportAmendmentLogExcel")
	public void exportAmendmentLogExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap) {
		
		paramMap.put("tableName", "t_banner");
		paramMap.put("recordId", Long.parseLong(String.valueOf(paramMap.get("bannerId"))));
		List<Log> logList = logService.findDeliverEffectAnalysis(paramMap);
		
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "report" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 5;
		paramMap.put("dataList", logList);
		paramMap.put("dataSize", logList.size());
		paramMap.put("column", column);
		paramMap.put("name", "创意信息修改记录");
		String excelTemplate = templateProcessor.processTemplate(
				"excel/amendmentLog.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

	
	//处理上传文件的绝对路径
	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;
	}
	
	//处理文件类型
	private 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 boolean checkPic(File localFile,BannerTemplate bannerTemplate) throws IOException{
		//构造image图片
		Image src = javax.imageio.ImageIO.read(localFile);	
		long width = src.getWidth(null);
		long height = src.getHeight(null);
		long _width = bannerTemplate.getWidth();
		long _height = bannerTemplate.getHeight();
		if(width>0&&height>0){
			if(width<=_width&&height<=_height){
				return false;
			}else{
				if((width*_height)==(_width*height)){
					return false;
				}
					return true;
			}	
		
		}
			return true;
	}
	
//	//如果是大于广告位且等比例的需要等比例缩小
//	public void compressPic(File localFile,String compressPath,) throws IOException{
//		File compressFile = new File(compressPath);
//		if (!compressFile.getParentFile().exists()){
//			compressFile.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", compressFile);
//		
//	}
		
}


