package com.cloudcross.ssp.web.operator.main.ad;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
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.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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 com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.base.web.result.AjaxResult;
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.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Industry;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Size;
import com.cloudcross.ssp.model.Zone;
import com.cloudcross.ssp.model.ZoneDomain;
import com.cloudcross.ssp.model.ZoneIndustry;
import com.cloudcross.ssp.service.IIndustryService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.ISizeService;
import com.cloudcross.ssp.service.IZoneDomainService;
import com.cloudcross.ssp.service.IZoneIndustryService;
import com.cloudcross.ssp.service.IZoneService;



@Controller("operator.zoneController")
@RequestMapping("/operator/main/ad/zone")
public  class ZoneController extends SimpleController {


	@Autowired
	protected IZoneService zoneService;
	@Autowired
	protected ILogService logService;
	@Autowired
	protected ISizeService sizeService;
	@Autowired
	protected IZoneIndustryService zoneIndustryService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	protected IZoneDomainService zoneDomainService;
	@Autowired
	protected IIndustryService industryService;
	@Autowired
	Config config;
	
	//文件系统可上传的文件后缀集合
	private static Set<String> noStuffixSet = new HashSet<String>();
		
	//初始化可上传文件后缀
	static {
		noStuffixSet.add("jpg");
		noStuffixSet.add("gif");
	}
	private static final Logger log = Logger.getLogger(ZoneController.class);
	@RequestMapping
	public String index(Model model,@RequestParam HashMap<String, Object> paramMap,@RequestParam(defaultValue="1") int page) {
		//获取当前账号的id
		Account account = getLoginUser();
		paramMap.put("operatorId", account.getOperatorId());
		model.addAllAttributes(paramMap);
		int totalRow = zoneService.countByParams(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Zone> zoneList = zoneService.findByParams(paramMap, pager);					
		List<Size> sizeList = sizeService.findAllSize();											
		model.addAttribute("pager", pager);
		model.addAttribute("zoneList", zoneList);
		model.addAttribute("sizeList", sizeList);
		return page("index");
	}
	
	@RequestMapping("/schedule/list")
	public String list1(Model model,
			@RequestParam HashMap<String, Object> paramMap,
//			@RequestParam(required = false) int zoneId,
			@RequestParam(required = false) Date date,
			@RequestParam(defaultValue="1") int page
			) {
//		paramMap.put("zoneId", zoneId);
		paramMap.put("date", "date");
//		List<String> adgroupNameList = zoneService.findAdgroupNameByZoneIdAndSchedule(paramMap);
		return page("schedule/list");
	}

	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,		
			@RequestParam(defaultValue="1") int page) {
		System.out.println("paramMap"+paramMap);
		//获取当前账号的id
		Account account = getLoginUser();
		paramMap.put("operatorId", account.getOperatorId());
		model.addAttribute("width", paramMap.get("width"));
		model.addAttribute("height", paramMap.get("height"));
		model.addAttribute("device", paramMap.get("device"));
		model.addAttribute("position", paramMap.get("position"));
		model.addAttribute("status", paramMap.get("status"));
		int totalRow = zoneService.countByParams(paramMap);
		System.out.println("totalRow"+totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);					
		List<Zone> zoneList = zoneService.findByParams(paramMap, pager);
		System.out.println("zoneList"+zoneList);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("zoneList", zoneList);
		return page("list");
	}

	
	@RequestMapping("/create")
	public String create(Model model,HttpServletRequest request)  {
		List<Industry> industryList = industryService.findAll();
		List<Size> sizeList = sizeService.findAllSize();
		System.out.println("abc"+sizeList.toString());
		model.addAttribute("sizeList", sizeList);
		model.addAttribute("industryList",industryList);
		model.addAttribute("sessionid", request.getSession().getId());
		return page("create");
	}
	
	@RequestMapping("/edit/{id}")
	public String edit(Model model, @PathVariable long id,HttpServletRequest request){
		//查询广告位信息
		Zone zone = zoneService.findById(id);
		
		//广告位网站黑名单
		String zoneDomainStr = "";
		//查询广告位开启状态的黑名单
		List<ZoneDomain> zoneDomainList = zoneDomainService.findAll(id);
		for(ZoneDomain a : zoneDomainList) {
			zoneDomainStr += a.getDomain()+",";
		}
		 //去掉域名黑名单最后一个“，”
		if(zoneDomainStr != null && zoneDomainStr.length() > 0){
			zoneDomainStr = zoneDomainStr.substring(0,zoneDomainStr.length()-1);
		}
		
		
		//查询所有的行业
		List<Industry> industryList = industryService.findAll();
		//查询所有的尺寸
		List<Size> SizeList = sizeService.findAllSize();
		//根据广告位的宽高查询广告位的ID
		Size Size = sizeService.findSizeId(zone.getHeight(),zone.getWidth());
		//设置广告位的sizeID
		zone.setSizeId(Size.getId());
		//查询开启状态广告位行业黑名单
		List<ZoneIndustry> zoneIndustryList = zoneIndustryService.findAll(zone.getId());
		//查询没有在黑名单里的行业
		List<Industry> notzoneIndustryList = industryService.findAllByZoneIdOperator(zone.getId());
		String industryStr = "";
		for(ZoneIndustry a : zoneIndustryList) {
			industryStr += a.getIndustryId()+",";
		}
		if(industryStr != null && industryStr.length() > 0){
			industryStr = industryStr.substring(0,industryStr.length()-1);
		}

		model.addAttribute("zone", zone);
		model.addAttribute("zoneDomainList", zoneDomainList);
		model.addAttribute("industryList",industryList);
		model.addAttribute("zoneIndustryList",zoneIndustryList);
		model.addAttribute("SizeList", SizeList);
		model.addAttribute("notzoneIndustryList",notzoneIndustryList);
		model.addAttribute("zoneDomainStr", zoneDomainStr);
		model.addAttribute("industryStr", industryStr);
		model.addAttribute("sessionid", request.getSession().getId());
		if(zone.getDefault_path() != "" || zone.getDefault_path() != null){
			String pictureName = zone.getDefault_path().substring(zone.getDefault_path().lastIndexOf("\\")+1, zone.getDefault_path().length());
			model.addAttribute("pictureName", pictureName);
		}
		return page("edit");
	}
	
	@RequestMapping("/getCode")
	public @ResponseBody String getCode(
			@RequestParam long zoneId){
		try {
			Account account = getLoginUser();
			String res = "http://adx.datacross.cn/operator="+account.getOperatorId()+"&zone="+zoneId;
			return res;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}

	
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Zone t,HttpServletRequest request,HttpServletResponse response) {
	
	//String path = zoneService.fileUpload(request, response);
	//System.out.println(path);
	//得到当前登录用户
	Account account = getLoginUser();
		//添加时保存
	if(t.getId() == null) {
		t.setOperator_id(account.getOperatorId());
		//根据前端传回来的表单获得						
		Size size = sizeService.findSize(t.getSizeId());
		t.setWidth(size.getWidth());
		t.setHeight(size.getHeight());
		//保存广告位信息
		zoneService.add(t);
		
		//处理域名黑名单
		String domain=t.getDomain();
		if(null != domain && !"".equals(domain)){
			String [] domainArr= domain.split(",");
			//域名黑名单
			ZoneDomain zoneDomain=new ZoneDomain();
			for(int i=0;i<domainArr.length;i++){
				zoneDomain.setZoneId(t.getId());
				zoneDomain.setDomain(domainArr[i]);
				zoneDomain.setStatus(0);//新增默认开启
				//在域名黑名单中插入黑名单信息
				zoneDomainService.add(zoneDomain);
			}
		}
		
		//处理行业黑民单
		String industry = t.getIndustry();
		if(null != industry && !"".equals(industry)){
			String [] industryArr= industry.split(","); 
			ZoneIndustry zoneIndustry = new ZoneIndustry();
			for(int i = 0; i< industryArr.length; i++){
				zoneIndustry.setZoneId(t.getId());
				zoneIndustry.setIndustryId(Long.parseLong(industryArr[i]));
				zoneIndustry.setStatus(0);
				zoneIndustryService.add(zoneIndustry);
			}
		}
		
		//处理日志记录
		Log log =new Log();
		log.setModule("Zone");//对应模块
		log.setTableName("t_zone");//对应的表名
		//从表中查到新增zone的id
		//long newId= zoneService.findByName(t.getName());
		log.setRecordId(t.getId());//对应广告位id
		log.setActionType("新增");
		log.setAction("新增广告位: "+t.getName());
		//下面这几个字段目前后端数据没有得到。所以仅作测试用！
		log.setActionTime("100");
		log.setAccountId(account.getAgentId());
		log.setUserIp(Common.toIpAddr(request));
		log.setAccountName(account.getAccountName());
		logService.add(log);
		
	} else {
		//修改保存方法
		/**
		 * 编辑成功后如果编辑前的数据与编辑后的数据比较后发生了改变，那么要对广告位信息，域名信息和行业信息增加修改日志
		 * 那再编辑之前要先获得到这些信息，保存下，然后和编辑之后的信息做比较
		 */
		//修改前的广告位信息
		Zone formerZone = zoneService.findZone(t.getId());
		//修改前的行业黑民单信息（状态为0，开启的）
		List<ZoneIndustry> formerZoneIndustryList = zoneIndustryService.findAll(t.getId());
		//修改前的域名黑名单信息（状态为0，开启的）
		List<ZoneDomain> formZoneDomainList=zoneDomainService.findAll(t.getId());
		//修改后的尺寸信息
		Size size = sizeService.findSize(t.getSizeId());
		t.setHeight(size.getHeight());
		t.setWidth(size.getWidth());
		//对广告位进行编辑
	
		zoneService.edit(t);
		
		//对修改前和之后的每一项进行比较，如果发现哪一个字段发生了修改就记录下来，并且让修改标志设为true，
		boolean updatedMark = false;
		boolean industryFlag = false;
		boolean domainFlag = false;
		//为空表示新增
		if(formZoneDomainList != null && formZoneDomainList.size()>0){
			//编辑域名zonedomain ***伪删除，后台为update，可以修改当前zoneID的所有域名黑名单记录
			zoneDomainService.delete(t);//删除之前保存的网站黑名单（为伪删除）
		}
		
		String domain=t.getDomain();
		if(null != domain && !"".equals(domain)){
			String [] domainArr= domain.split(",");
			//域名黑名单
			ZoneDomain zoneDomain=new ZoneDomain();
			for(int i=0;i<domainArr.length;i++){
				zoneDomain.setZoneId(t.getId());
				zoneDomain.setDomain(domainArr[i]);
				zoneDomain.setStatus(0);//新增默认开启
				//在域名黑名单中插入黑名单信息
				zoneDomainService.add(zoneDomain);
			}
			
			//判断黑名单是否修改以决定是否添加日志
			 domainFlag = false;//false表示没有修改
			//对编辑前的网站黑名单对应的id转化成数组
			String[] formDomainArr = new String[formZoneDomainList.size()];
			for(int i = 0; i < formZoneDomainList.size(); i++) {
				formDomainArr[i] = formZoneDomainList.get(i).getDomain();
			}
			//对比一下编辑前后的网站黑名单id数组长度是否发生变化如果发生变化就去更新表并且新增修改记录,首先对比一下广告位的id数量是不是一样多如果发生变化就说明广告位有了变化否则再一条一条的对比  
			if(domainArr.length == formDomainArr.length) {
				for(int i = 0; i < domainArr.length; i++) {
					if(!domainArr[i].equals(formDomainArr[i])) {
						domainFlag = true;
						break;
						}
					}
			} else {
				domainFlag = true;
			}
			
			if(domainFlag) {
				//如果编辑广告位成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Zone");//对应模块
				logModify.setTableName("t_zone");//对应的表名
				logModify.setRecordId(t.getId());//对应广告位id
				logModify.setAction("编辑广告位的行业黑名单："+t.getId());//变更详情
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logModify.setActionTime("100");
				logModify.setAccountId(account.getAgentId());
				logModify.setUserIp(Common.toIpAddr(request));
				logModify.setAccountName(account.getAccountName());
				logModify.setActionType("编辑");
				logService.add(logModify); 
			}
		}
		
		
		//为空表示新增
		if(formerZoneIndustryList != null&&formerZoneIndustryList.size()>0){
			zoneIndustryService.delete(t);//删除之前保存的行业
		}
		//处理行业黑民单
		String industry = t.getIndustry();
		if(null != industry && !"".equals(industry)){
			String [] industryArr= industry.split(","); 
			ZoneIndustry zoneIndustry = new ZoneIndustry();
			for(int i = 0; i< industryArr.length; i++){
				zoneIndustry.setZoneId(t.getId());
				zoneIndustry.setIndustryId(Long.parseLong(industryArr[i]));
				zoneIndustry.setStatus(0);
				zoneIndustryService.add(zoneIndustry);
			}
			
			//判断是否对行业黑名单修改以决定是否添加日志
			industryFlag = false;
			//对编辑后的行业id进行处理
			Long[] industryId = new Long[industryArr.length];
			for(int i = 0; i < industryArr.length; i++) {
				industryId[i] =  Long.valueOf(industryArr[i]).longValue();
			}
			
			//对编辑前的行业id进行转化排序
			Long[] formindustryId = new Long[formerZoneIndustryList.size()];
			for(int i = 0; i < formerZoneIndustryList.size(); i++) {
				formindustryId[i] = formerZoneIndustryList.get(i).getIndustryId();
			}
			
			
			//对比一下编辑前后的广告位场景id长度是否发生变化如果发生变化就去更新表并且新增修改记录,首先对比一下广告位的id数量是不是一样多如果发生变化就说明广告位有了变化否则再一条一条的对比  
			if(industryId.length == formindustryId.length) {
				for(int i = 0; i < industryId.length; i++) {
					if(!industryId[i].equals(formindustryId[i])) {
						industryFlag = true;
						break;
						}
					}
			} else {
				industryFlag = true;
			}
			
			if(industryFlag) {
				//如果编辑广告位成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Zone");//对应模块
				logModify.setTableName("t_zone");//对应的表名
				logModify.setRecordId(t.getId());//对应广告位id
				logModify.setAction("编辑广告位的行业黑名单："+t.getId());//变更详情
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logModify.setActionTime("100");
				logModify.setAccountId(account.getAgentId());
				logModify.setUserIp(Common.toIpAddr(request));
				logModify.setAccountName(account.getAccountName());
				logModify.setActionType("编辑");
				logService.add(logModify); 
				}
		}
		

		/**
		 * 对广告位的修改的日志增加
		 */
		//重置修改标志
		updatedMark = false;
		String s =t.getName()+"：";
		if (!formerZone.getName().equals(t.getName())) {
			s=s.concat("广告位名  "+formerZone.getName()+" > "+t.getName()+" ");
			updatedMark = true;
			}
		if (!formerZone.getRecheck().equals(t.getRecheck())) {
			s=s.concat("是否需要再次审核 "+formerZone.getRecheck()+" > "+t.getRecheck()+" ");
			updatedMark = true;
			}
		if (!formerZone.getPosition().equals(t.getPosition())) {
			s=s.concat("位置 "+formerZone.getPosition()+" > "+t.getPosition()+" ");
			updatedMark = true;
			}
		
		if (!formerZone.getDefault_path().equals(t.getDefault_path())) {
			s=s.concat("垫底广告 path"+formerZone.getDefault_path()+" > "+t.getDefault_path()+" ");
			updatedMark = true;
			}
		
		if (!formerZone.getWidth().equals(t.getWidth())) {
			s=s.concat("改变尺寸  "+formerZone.getWidth()+" > "+t.getWidth()+" ");
			updatedMark = true;
			}
		if (!formerZone.getHeight().equals(t.getHeight())) {
			s=s.concat("改变尺寸  "+formerZone.getHeight()+" > "+t.getHeight()+" ");
			updatedMark = true;
			}
		
		if (!formerZone.getDevice().equals(t.getDevice())) {
			s=s.concat("类型  "+formerZone.getDevice()+" > "+t.getDevice()+" ");
			updatedMark = true;
			}
		
		
		if(updatedMark) {
			//如果编辑广告位成功，向log数据库中插入记录
			Log logModify= new Log();
			logModify.setModule("Zone");//对应模块
			logModify.setTableName("t_zone");//对应的表名
			logModify.setRecordId(t.getId());//对应广告位id
			logModify.setAction("编辑广告位的广告位信息："+t.getId());//变更详情
			//下面这几个字段目前后端数据没有得到。所以仅作测试用！
			logModify.setActionTime("100");
			logModify.setAccountId(account.getAgentId());
			logModify.setUserIp(Common.toIpAddr(request));
			logModify.setAccountName(account.getAccountName()); 
			logModify.setActionType("编辑"); 
			logService.add(logModify); 
		}
	}
	// 跳转到管理页面。
	return redirect(page(""));
}
	
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam Long zoneId,
			@RequestParam(defaultValue = "1") int page) {
		// 查询总行数
		paramMap.put("tableName", "t_zone");
		paramMap.put("recordId", zoneId);
		int totalRow = logService.countByParams(paramMap,"Zone");
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
	List<Log> logList = logService.findByParams(paramMap, pager,"Zone");
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("zoneId", zoneId);
		return page("update");
	}
	
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id,HttpServletRequest request) {
		Account account = getLoginUser();
		if (ArrayUtils.isNotEmpty(id)) {
			List<String> list =new ArrayList<String>();
			for (int i = 0; i < id.length; i++) {
				System.out.println("acb"+id[i]);
				Zone zone = zoneService.findById(new Long(id[i]));
				list.add(zone.getName());
			}
			if (zoneService.updateStatus(LangUtil.array2List(id),Status.enable.value)) {
				for (int i = 0; i < list.size(); i++) {
					Log log =new Log();
					log.setModule("Zone");//对应模块
					log.setTableName("t_zone");//对应的表名
					log.setRecordId(id[i]);//对应订单id
					log.setAction("启用广告位: "+list.get(i));//变更详情,广告位名称
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					log.setActionTime("100");
					log.setAccountId(account.getAgentId());
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(account.getAccountName());
					log.setActionType("开启广告位");
					logService.add(log);
				}
			}
		}
		return OK;
	}


	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id,HttpServletRequest request) {
		Account account = getLoginUser();
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到订单名称（批量或者单个都可以）___为了插入log记录的时候显示订单名称！_
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Zone zone = zoneService.findById(new Long(id[i]));
				list.add(zone.getName());
			}
			if( zoneService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				//如果禁用订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Zone");//对应模块
				log.setTableName("t_zone");//对应的表名
				log.setRecordId(id[i]);//对应订单id
				log.setAction("停用广告位: "+list.get(i));//变更详情,订单名称
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(account.getAgentId());
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(account.getAccountName());
				log.setActionType("关闭广告位");
				logService.add(log);
				}
			}
		}
		return OK;
	}
	

	@RequestMapping("delete")
	public @ResponseBody String delete(Long[] id,HttpServletRequest request) {
		Account account = getLoginUser();
		if (ArrayUtils.isNotEmpty(id)) {
		//循环得到订单名称（批量或者单个都可以）_________为了插入log记录的时候显示订单名称！
	
		List<String> list = new ArrayList<String>();
		for (int i = 0;i < id.length;i++) {
			Zone a = zoneService.findById(new Long(id[i]));
			list.add(a.getName());
		}
		if(zoneService.updateStatus(LangUtil.array2List(id),Status.delete.value) ) {
			//如果删除订单成功，向log数据库中插入记录！
			for (int i = 0;i < id.length;i++) {
			Log logDel= new Log();
			logDel.setModule("Zone");//对应模块
			logDel.setTableName("t_zone");//对应的表名
			logDel.setRecordId(id[i]);//对应广告位id
			logDel.setActionType("删除");//对应广告位的id
			logDel.setAction("删除了广告位:"+list.get(i));//变更详情
			//下面这几个字段目前后端数据没有得到。所以仅作测试用！
			logDel.setActionTime("100");
			logDel.setAccountId(account.getAgentId());
			logDel.setUserIp(Common.toIpAddr(request));
			logDel.setAccountName(account.getAccountName());
			logService.add(logDel);
			}
		}
	}
		return page("list");
	}
	
	
	//导出日志excel
	@RequestMapping("/exportLogReportExcel")
	public void exportLogReportExcel(HttpServletRequest request,
			HttpServletResponse response,
			Model model,
			@RequestParam Long zoneId,
			@RequestParam HashMap<String, Object> paramMap,		
			@RequestParam(defaultValue="1") int page
			
			) {
		paramMap.put("recordId", zoneId);
		/**
		 * 参数和list里要一样
		 */				
			
		List<Log> logList = logService.findByParams1(paramMap);
		
		paramMap.put("dataList", logList);
		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 = 9;
		
		paramMap.put("column", column);
		paramMap.put("zoneName", "测试");
		paramMap.put("startDate", "2015-04-01");
		paramMap.put("endDate", "2015-06-01");
		String excelTemplate = templateProcessor.processTemplate(
				"excel/logReport.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
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(HttpServletRequest request,
			HttpServletResponse response,
			Model model,
			@RequestParam HashMap<String, Object> paramMap,		
			@RequestParam(defaultValue="1") int page
			
			) {
		/**
		 * 参数和list里要一样
		 */
		
		int totalRow = zoneService.countByParams(paramMap);
		
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);					
		//List<Zone> reportList = zoneService.findDeliverEffectAnalysis(paramMap);				
		List<Zone> zoneList = zoneService.findByParams(paramMap, pager);
		
		paramMap.put("dataList", zoneList);
		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 = 9;
		paramMap.put("dataSize", zoneList.size());
		paramMap.put("column", column);
		paramMap.put("zoneName", "测试");
		paramMap.put("startDate", "2015-04-01");
		paramMap.put("endDate", "2015-06-01");
		String excelTemplate = templateProcessor.processTemplate(
				"excel/zone.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//   广告位排期中的设备筛选：
	@RequestMapping("/get")
	public @ResponseBody List<Zone> getZoneList() {
		//自己测试时没有传递参数
		//正式的时候把参数传进去 
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Integer zoneDevice = 1;
		//如果有设备的id值就可以在参数里添加一个设备的值
		if(zoneDevice != 0) {
			paramMap.put("zoneDevice", zoneDevice);
		}
		
		
		return zoneService.findByDevice(1);
	}
	
	
	/**
	 * 该方法（fileUpload）与下面方法（upload）任选一种即可
	 * @param file
	 * @param request
	 * @return
	 */
	/*@RequestMapping("/fileupload")
	@ResponseBody
	public AjaxResult fileUpload(HttpServletRequest request,HttpServletResponse response) {
		return this.zoneService.fileUpload(request, response);
		
	}*/
	

	@RequestMapping("/fileupload")
	@ResponseBody
	public AjaxResult upload(@RequestParam MultipartFile file,HttpServletRequest request) {
		AjaxResult result = new AjaxResult();
		if (validate(file)) {
			result.setStatus(OK);
			result.addData("url", handleUpload( file,request));
		} else {
			result.setMsg("上传图片格式或者大小不对");
			result.setStatus(ERROR);
		}
		return result;
	}
	
	/**
	 * 验证上传文件是否合法，如果不合法那么会抛出异常
	 * 
	 * @param file
	 *            用户上传的文件封装类
	 */
	public final boolean validate( MultipartFile file) {
		Assert.notNull(file, "文件不能为空!");
		String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
		if(!noStuffixSet.contains(fileExtension)){
			log.error("validate():文件类型不支持！");
			return false;
		}

		if (file.getSize()<=0 || file.getSize() > getUploadMaxSize()) {
			log.error("validate():文件超过"+getUploadMaxSize());
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * @return 设置文件上传大小上限（默认2M，单位字节）
	 */
	public long getUploadMaxSize() {
		return 2 * 8 * 1024 * 1024;
	}
	
	/**
	 * 
	 * 
	 * @param resourceType
	 * 			上传资源类型（video\image）
	 * @param file
	 * 			上传文件。
	 * @return 网络访问路径（url）
	 */
	protected String handleUpload(MultipartFile file,HttpServletRequest request) {
		String returnUrl = "";
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		String folder = getFilePath(request);
		String fileId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
		String path = folder+File.separator+fileId+"."+fileType;
		String smallName = fileId+"_small"+"."+fileType;
		String smallPath = folder+File.separator+smallName;
		
		// 保存文件
		File localFile = new File(path);
		copyFile(file, localFile);
		//保存缩略图
	
		try {
			smallPicture(localFile,smallPath,smallName);
		} catch (IOException e) {
			log.error("smallPicture():生成缩略图产生异常");
			e.printStackTrace();
		}
		returnUrl = path.substring(path.indexOf("upload")-1)+","+smallPath.substring(path.indexOf("upload")-1);
		return returnUrl;
	}
	
	
	/**
	 * 拷贝文件。
	 */
	protected final void copyFile(MultipartFile remoteFile, File localFile) {
		// 所属文件夹不存在，创建所有。
		File localDir = localFile.getParentFile();
		if (!localDir.exists()) {
			//LOG.info("创建路径：" + localDir.getAbsolutePath());
			localDir.mkdirs();
		}

		// 将文件保存到本地
		InputStream is = null;
		FileOutputStream os = null;
		try {
			is = remoteFile.getInputStream();
			os = new FileOutputStream(localFile);
			IOUtils.copy(is, os);
		} catch (IOException e) {
		//	LOG.error("将资源存到本地时失败。", e);
		} finally {
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(is);
		}
	}
	
	
	private String getFilePath(HttpServletRequest request){
		// 获取当前上传的年月日
		Calendar cal = Calendar.getInstance();
		// 当前年
		int year = cal.get(Calendar.YEAR);
		// 当前月
		int month = cal.get(Calendar.MONTH) + 1;
		// 当前日
		int day = cal.get(Calendar.DATE);
		//获取文件上传目录
		//获取项目目录
		String realPath = request.getSession().getServletContext().getRealPath("/");
		//获取项目的同级目录
		String root = new File(realPath).getParentFile().getAbsolutePath();
		//到配置文件中获取文件存放的目录
		String upload = config.getResourceUploadDir();
		String path = root+File.separator+upload+File.separator+"zone"+File.separator+year + File.separator + month + File.separator + day;
		return path;
	}
	
	//生成缩略图
	private void smallPicture(File sourceFile,String pathSmall,String uploadName) throws IOException{
		//新建缩略图文件
		File smallFile = new File(pathSmall);
		if (!smallFile.getParentFile().exists()){
			smallFile.getParentFile().mkdirs();
		}	
		//构造image图片
		Image src = javax.imageio.ImageIO.read(sourceFile);
		//表示该图像具有打包成整数的像素的8 位RGB颜色分量
		BufferedImage tag = new BufferedImage(150, 60, BufferedImage.TYPE_INT_BGR);
		//h绘制缩小后的图片
		tag.getGraphics().drawImage(src, 0, 0, 150, 60, null);
		//生成缩略图
		ImageIO.write(tag, "jpg", smallFile);
	}


}



