 package com.cloudcross.ssp.web.back.main.ad.report;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.ArrayUtils;
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 com.cloudcross.ssp.back.model.Account;
import com.cloudcross.ssp.back.model.DeliverAnalysis;
import com.cloudcross.ssp.back.model.Dimension;
import com.cloudcross.ssp.back.service.IAdReportService;
import com.cloudcross.ssp.back.service.IDimensionService;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;

/**
 * 统计报表页面。
 * 
 * @author colin
 */
@Controller
@RequestMapping("/back/main/ad/report/advertiser-report")
public class AdvertiserReportController extends SimpleController {
	
	@Autowired
	private IAdReportService adReportService;
	@Autowired
	private IDimensionService dimensionService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	
	@RequestMapping
	public String index(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page)
		
		
	
	{
		
		//前端需要传广告主idadvertiser和时间过来dateRangePicker
		//判断前端传过来的登录账户id确定权限
		Account account = getLoginUser();
		paramMap.put("agentId", account.getAgentId());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = null;
		String endDate = null;
		// 广告主Id,订单Id，活动Id，投放Id
		Long advertiserId = null; 
		Long orderId = null; 
		Long campaignId = null; 
		Long adGroupId = null; 
		Long dimensionId = null; 
				
		String advertiserName = "全部广告主";
		String orderName = "全部订单";
		String campaignName = "全部活动";
		String adGroupName = "全部投放";
		String dimensionName = "请选择维度";
		
		/**
		 * 前端日期传值为dateRangePicker
		 * 中间是to分割。 
		 * 默认是昨天的数据
		 * 需要对这些数据进行处理和判断
		 * @author Hao
		 */
		
		if (null == paramMap.get("selectedadvertiserId")
				|| "".equals(paramMap.get("selectedadvertiserId"))) {
			advertiserId = null;
			advertiserName = "全部广告主";
		} else {
			// 如果要查询的是所有广告主则让广告主id为空
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadvertiserId"))) {
				advertiserId = null;
				advertiserName = "全部广告主";
			} else {
				advertiserId = Long.parseLong((String) paramMap
						.get("selectedadvertiserId"));
				advertiserName = (String)paramMap.get("selectedadvertiserName");
			}
		}
	
		//订单选择与否
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))) {
			orderId = null;
			orderName = "全部订单";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedorderId"))) {
				orderId = null;
				orderName = "全部订单";
			} else {
				orderId = Long.parseLong((String) paramMap
						.get("selectedorderId"));
				orderName = (String)paramMap.get("selectedorderName");
			}
		}
		
		//活动选择与否
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))) {
			campaignId = null;
			campaignName = "全部活动";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedcampaignId"))) {
				campaignId = null;
				campaignName = "全部活动";
			} else {
				campaignId = Long.parseLong((String) paramMap
						.get("selectedcampaignId"));
				campaignName = (String)paramMap.get("selectedcampaignName");
			}
		}
		
		//投放选择与否
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))) {
			adGroupId = null;
			adGroupName = "全部投放";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadGroupId"))) {
				adGroupId = null;
				adGroupName = "全部投放";
			} else {
				adGroupId = Long.parseLong((String) paramMap
						.get("selectedadGroupId"));
				adGroupName = (String)paramMap.get("selectedadGroupName");
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
		if (null == paramMap.get("dateRangePicker")
					|| "".equals(paramMap.get("dateRangePicker"))) {
			startDate = endDate = sdf.format(new Date((new Date())
						.getTime() - 24 * 60 * 60 * 1000));
		} else {
			String[] choosedDate = ((String) paramMap
						.get("dateRangePicker")).split("to");
			startDate = choosedDate[0].trim();
			endDate = choosedDate[1].trim();
		} 
		
		//选择维度
		if (null == paramMap.get("selecteddimensionId")
				|| "".equals(paramMap.get("selecteddimensionId"))) {
			dimensionId = null;
			dimensionName = "请选择维度";
		} else {
			// 如果要查询的是所有广告主则让广告主id为空
			if (-1 == Long.parseLong((String) paramMap
					.get("selecteddimensionId"))) {
				dimensionId = Long.parseLong("-1");
				dimensionName = "请选择维度";
			} else {
				dimensionId = Long.parseLong((String) paramMap
						.get("selecteddimensionId"));
				dimensionName = (String)paramMap.get("selecteddimensionName");
			}
		}
		
		paramMap.put("advertiserId", advertiserId);
		paramMap.put("orderId", orderId);
		paramMap.put("campaignId", campaignId);
		paramMap.put("adGroupId",  adGroupId);
		paramMap.put("startDate",  startDate);
		paramMap.put("endDate",  endDate);
		paramMap.put("selectedadvertiserName", advertiserName);
		paramMap.put("selectedorderName", orderName);
		paramMap.put("selectedcampaignName", campaignName);
		paramMap.put("selectedadGroupName",  adGroupName);
		paramMap.put("dimensionId",  dimensionId);
		paramMap.put("selecteddimensionName",  dimensionName);
		
		int totalRow = adReportService.findCountForDeliverEffectAnalysis(paramMap);
		
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<DeliverAnalysis> reportList = adReportService.findByTotalReport(paramMap, pager);
		
		
		
		
		
			
	//若是没有符合条件的数据，则对应的选项皆显示为0
		if(reportList.size() == 0){
			DeliverAnalysis map = new DeliverAnalysis();
			DeliverAnalysis deliver = new DeliverAnalysis();
			deliver.setImpression(0);
			deliver.setClick(0);
			deliver.setVisit(0);
			deliver.setConversion(0);
			deliver.setConsume(0);
			deliver.seteCmp(0);
			deliver.setClickRate(0);
			deliver.setVisitRate(0);
			deliver.setConversionRate(0);
			map = deliver;
			
			model.addAttribute("reportMap", map);
		}
		else {
		//数据报表中第一栏 全部  的显示
		HashMap<String,Double> map = new HashMap<String,Double>();
		map.put("impressionSum", reportList.get(0).getImpressionSum());
		map.put("clickSum", reportList.get(0).getClickSum());
		map.put("visitSum", reportList.get(0).getVisitSum());
		map.put("conversionSum", reportList.get(0).getConversionSum());
		map.put("consumeSum", reportList.get(0).getConsumeSum());
		map.put("eCmpSum", reportList.get(0).geteCmpSum());
		map.put("clickRatesum", reportList.get(0).getClickRatesum());
		map.put("visitRatesum", reportList.get(0).getVisitRatesum());
		map.put("conversionRatesum", reportList.get(0).getConversionRatesum());
		model.addAttribute("reportMap", map);
		System.out.println("tttttttttt");
		}
		
		
		
		
		if(null == paramMap.get("advertiserId")) {
			paramMap.put("selectedadvertiserId", "-1");
		} else {
			paramMap.put("selectedadvertiserId", paramMap.get("advertiserId"));
		}
		if(null == paramMap.get("orderId")) {
			paramMap.put("selectedorderId", "-1");
		} else {
			paramMap.put("selectedorderId", paramMap.get("orderId"));
		}
		if(null == paramMap.get("campaignId")) {
			paramMap.put("selectedcampaignId", "-1");
		} else {
			paramMap.put("selectedcampaignId", paramMap.get("campaignId"));
		}
		if(null == paramMap.get("adgroupId")) {
			paramMap.put("selectedadgroupId", "-1");
		} else {
			paramMap.put("selectedadgroupId", paramMap.get("adgroupId"));
		}
		
		//维度更新表格
		if(dimensionId == null){
			HashMap<String,Object> dimensionmap = dimensionService.selectDimensionIdBydefault();
			if(Integer.parseInt(dimensionmap.get("num").toString()) == 0){
				model.addAttribute("dimensionLength",null);
				model.addAttribute("dimensionTarget",null);
			}else{
				dimensionId = Long.valueOf(dimensionmap.get("id").toString());
				paramMap.put("selecteddimensionName", dimensionmap.get("name"));
				paramMap.put("dimensionId", dimensionId);
				List<HashMap<String,Object>> list = getDimensionById(dimensionId);
				if(list.size() >0 ){
					model.addAttribute("dimensionLength",list.size());
					model.addAttribute("dimensionTarget",list);
					
				}else{
					model.addAttribute("dimensionLength",null);
					model.addAttribute("dimensionTarget",null);
				}
			}
		}else if(dimensionId == -1){
			model.addAttribute("dimensionLength",null);
			model.addAttribute("dimensionTarget",null);
		}else{
			List<HashMap<String,Object>> list = getDimensionById(dimensionId);
			if(list.size() >0 ){
				model.addAttribute("dimensionLength",list.size());
				model.addAttribute("dimensionTarget",list);
				
			}else{
				model.addAttribute("dimensionLength",null);
				model.addAttribute("dimensionTarget",null);
			}
		}
		
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("reportList", reportList);
		return index;
	}
    //维度管理	
	@RequestMapping("/dimension")
	public String dimension(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		
		int totalRow = dimensionService.countByParams(paramMap);
		System.out.println("bbbdimension"+totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Dimension> dimensionList = dimensionService.findByParams(paramMap, pager);
	
		System.out.println("bbbdimension"+dimensionList);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("dimensionList", dimensionList);

		return page("dimension");
	}
	
	//维度管理	
	@RequestMapping("/dimensionlist")
	public @ResponseBody List<Dimension> dimensionlist(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		List<Dimension> dimensionList = dimensionService.findByParams(paramMap, null);
		return dimensionList;
	}
	
	//增加维度
	@RequestMapping("/create")
	public String create() {

		return page("create");
	}
    
	//编辑维度
	@RequestMapping("/edit")
	public String edit(Model model, 
			@RequestParam long id) {
		// 根据id从数据库中查询广告主对象。
		Dimension dimension = dimensionService.findById(id);
		String content = dimension.getContent();
		List<String> alllist = new ArrayList<String>();
		List<String> list = new ArrayList<String>();
		String[] allType = {"广告主","订单","活动","投放","创意","日期"};
		for (int i = 0; i < allType.length; i++) {
			alllist.add(allType[i]);
		}
		if(content!=null && !"".equals(content)){
			String[] contentArr = content.split("-");
			for (int j = 0; j < contentArr.length; j++) {
				if(alllist.contains(contentArr[j])){
					list.add(contentArr[j]);
					alllist.remove(contentArr[j]);
				}
			}
		}
		model.addAttribute("dimensionTypeList", list); 
		model.addAttribute("notdimensionTypeList", alllist); 
		model.addAttribute("dimension", dimension); 
		return page("edit");
	}
	
	//删除
		@RequestMapping("/delete")
		public @ResponseBody
		String delete(Long[] id) {
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			if (ArrayUtils.isNotEmpty(id)) {
				paramMap.put("idList", id);
				dimensionService.deleteById(paramMap);
			}
			return OK;
		}
	
		
		//保存
	@RequestMapping("/save")
	public String save(
				@ModelAttribute("form") Dimension dimension) {
	   // 校验参数
        
	   	System.out.println("ccc"+dimension.toString());
	   	System.out.println("ccc"+dimension.getId());
	   	if (dimension.getId() == null){
	   		dimensionService.add(dimension);
	   		
	   	}else{
	   		dimensionService.edit(dimension);
	   	}
			return redirect(page("dimension"));
		}
	
	
	//下面是地域报表

	@RequestMapping("/regionReport")
	public String regionReport(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		
		//日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = null;
		String endDate = null;
		
		//广告主，订单，活动，投放
		Long advertiserId = null;
		Long orderId = null;
		Long campaignId = null;
		Long adGroupId = null;
		
		String advertiserName = "全部广告主";
		String orderName = "全部订单";
		String campaignName = "全部活动";
		String adGroupName = "全部投放";
		/**
		 * 下面对下拉框中传进来的值进行判断，若是未操作，则为空值，前端设置时默认为全部（-1）
		 * 注意前后层次关系，同时要考虑到登录帐号权限问题，此时暂未考虑
		 * 下拉框传值Id需要同步
		 */
		
		//广告主选择与否
		if (null == paramMap.get("selectedadvertiserId")
					|| "".equals(paramMap.get("selectedadvertiserId"))) {
				advertiserId = null;
				advertiserName = "全部广告主";
			} else {
				// 如果要查询的是所有广告主则让广告主id为空
				if (-1 == Long.parseLong((String) paramMap
						.get("selectedadvertiserId"))) {
					advertiserId = null;
					advertiserName = "全部广告主";
				} else {
					advertiserId = Long.parseLong((String) paramMap
							.get("selectedadvertiserId"));
					advertiserName = (String)paramMap.get("selectedadvertiserName");
				}
			}
		
		//订单选择与否
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))) {
			orderId = null;
			orderName = "全部订单";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedorderId"))) {
				orderId = null;
				orderName = "全部订单";
			} else {
				orderId = Long.parseLong((String) paramMap
						.get("selectedorderId"));
				orderName = (String)paramMap.get("selectedorderName");
			}
		}
		
		//活动选择与否
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))) {
			campaignId = null;
			campaignName = "全部活动";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedcampaignId"))) {
				campaignId = null;
				campaignName = "全部活动";
			} else {
				campaignId = Long.parseLong((String) paramMap
						.get("selectedcampaignId"));
				campaignName = (String)paramMap.get("selectedcampaignName");
			}
		}
		
		//投放选择与否
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))) {
			adGroupId = null;
			adGroupName = "全部投放";
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadGroupId"))) {
				adGroupId = null;
				adGroupName = "全部投放";
			} else {
				adGroupId = Long.parseLong((String) paramMap
						.get("selectedadGroupId"));
				adGroupName = (String)paramMap.get("selectedadGroupName");
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
		if (null == paramMap.get("dateRangePicker")
					|| "".equals(paramMap.get("dateRangePicker"))) {
			startDate = endDate = sdf.format(new Date((new Date())
						.getTime() - 24 * 60 * 60 * 1000));
		} else {
			String[] choosedDate = ((String) paramMap
						.get("dateRangePicker")).split("to");
			startDate = choosedDate[0].trim();
			endDate = choosedDate[1].trim();
		} 
		
		paramMap.put("advertiserId", advertiserId);
		paramMap.put("orderId", orderId);
		paramMap.put("campaignId", campaignId);
		paramMap.put("adGroupId",  adGroupId);
		paramMap.put("startDate",  startDate);
		paramMap.put("endDate",  endDate);
		paramMap.put("selectedadvertiserName", advertiserName);
		paramMap.put("selectedorderName", orderName);
		paramMap.put("selectedcampaignName", campaignName);
		paramMap.put("selectedadGroupName",  adGroupName);
		/**
		 * 下面是对应的查询语句，逻辑很重要
		 */
		int totalRow = adReportService.findCountForLocation(paramMap);
		System.out.println("aaaareport"+totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
				
		List<DeliverAnalysis> reportList = adReportService.findByLocation(paramMap, pager);
			
		System.out.println("aaaareport"+reportList);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("reportList", reportList);
		return page("regionReport");
	}
	
	
	//下面是系统报表
	
	@RequestMapping("/osReport")
	public String osReport(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		
		//日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String startDate = null;
				String endDate = null;
				
				//广告主，订单，活动，投放
				Long advertiserId = null;
				Long orderId = null;
				Long campaignId = null;
				Long adGroupId = null;
				
				String advertiserName = "全部广告主";
				String orderName = "全部订单";
				String campaignName = "全部活动";
				String adGroupName = "全部投放";
				/**
				 * 下面对下拉框中传进来的值进行判断，若是未操作，则为空值，前端设置时默认为全部（-1）
				 * 注意前后层次关系，同时要考虑到登录帐号权限问题，此时暂未考虑
				 * 下拉框传值Id需要同步
				 */
				
				//广告主选择与否
				if (null == paramMap.get("selectedadvertiserId")
							|| "".equals(paramMap.get("selectedadvertiserId"))) {
						advertiserId = null;
						advertiserName = "全部广告主";
					} else {
						// 如果要查询的是所有广告主则让广告主id为空
						if (-1 == Long.parseLong((String) paramMap
								.get("selectedadvertiserId"))) {
							advertiserId = null;
							advertiserName = "全部广告主";
						} else {
							advertiserId = Long.parseLong((String) paramMap
									.get("selectedadvertiserId"));
							advertiserName = (String)paramMap.get("selectedadvertiserName");
						}
					}
				
				//订单选择与否
				if (null == paramMap.get("selectedorderId")
						|| "".equals(paramMap.get("selectedorderId"))) {
					orderId = null;
					orderName = "全部订单";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedorderId"))) {
						orderId = null;
						orderName = "全部订单";
					} else {
						orderId = Long.parseLong((String) paramMap
								.get("selectedorderId"));
						orderName = (String)paramMap.get("selectedorderName");
					}
				}
				
				//活动选择与否
				if (null == paramMap.get("selectedcampaignId")
						|| "".equals(paramMap.get("selectedcampaignId"))) {
					campaignId = null;
					campaignName = "全部活动";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedcampaignId"))) {
						campaignId = null;
						campaignName = "全部活动";
					} else {
						campaignId = Long.parseLong((String) paramMap
								.get("selectedcampaignId"));
						campaignName = (String)paramMap.get("selectedcampaignName");
					}
				}
				
				//投放选择与否
				if (null == paramMap.get("selectedadGroupId")
						|| "".equals(paramMap.get("selectedadGroupId"))) {
					adGroupId = null;
					adGroupName = "全部投放";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedadGroupId"))) {
						adGroupId = null;
						adGroupName = "全部投放";
					} else {
						adGroupId = Long.parseLong((String) paramMap
								.get("selectedadGroupId"));
						adGroupName = (String)paramMap.get("selectedadGroupName");
					}
				}		
							
					//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
					if (null == paramMap.get("dateRangePicker")
							|| "".equals(paramMap.get("dateRangePicker"))) {
						startDate = endDate = sdf.format(new Date((new Date())
								.getTime() - 24 * 60 * 60 * 1000));
					} else {
						String[] choosedDate = ((String) paramMap
								.get("dateRangePicker")).split("to");
						startDate = choosedDate[0].trim();
						endDate = choosedDate[1].trim();
					} 
				
				paramMap.put("advertiserId", advertiserId);
				paramMap.put("orderId", orderId);
				paramMap.put("campaignId", campaignId);
				paramMap.put("adGroupId",  adGroupId);
				paramMap.put("selectedadvertiserName", advertiserName);
				paramMap.put("selectedorderName", orderName);
				paramMap.put("selectedcampaignName", campaignName);
				paramMap.put("selectedadGroupName",  adGroupName);
				paramMap.put("startDate",  startDate);
				paramMap.put("endDate",  endDate);
		
		/**
		 * 搜索查询对应的数据
		 */
				int totalRow = adReportService.findCountForOs(paramMap);
				System.out.println("aaaareport"+totalRow);
				Pager pager = new Pager();
				pager.setPage(page);
				pager.setTotalRow(totalRow);
				
				List<DeliverAnalysis> reportList = adReportService.findByOs(paramMap, pager);
				
				
				if(reportList.size() == 0){
					DeliverAnalysis map = new DeliverAnalysis();
					DeliverAnalysis deliver = new DeliverAnalysis();
					deliver.setImpression(0);
					deliver.setClick(0);
					deliver.setVisit(0);
					deliver.setConversion(0);
					deliver.setConsume(0);
					deliver.seteCmp(0);
					deliver.setClickRate(0);
					deliver.setVisitRate(0);
					deliver.setConversionRate(0);
					map = deliver;
					
					model.addAttribute("reportMap", map);
				}
				else {
				//数据报表中第一栏 全部  的显示
				HashMap<String,Double> map = new HashMap<String,Double>();
				map.put("impressionSum", reportList.get(0).getImpressionSum());
				map.put("clickSum", reportList.get(0).getClickSum());
				map.put("visitSum", reportList.get(0).getVisitSum());
				map.put("conversionSum", reportList.get(0).getConversionSum());
				map.put("consumeSum", reportList.get(0).getConsumeSum());
				map.put("eCmpSum", reportList.get(0).geteCmpSum());
				map.put("clickRatesum", reportList.get(0).getClickRatesum());
				map.put("visitRatesum", reportList.get(0).getVisitRatesum());
				map.put("conversionRatesum", reportList.get(0).getConversionRatesum());
				model.addAttribute("reportMap", map);
				System.out.println("tttttttttt");
				}
				
				model.addAllAttributes(paramMap);
				model.addAttribute("pager", pager);
				model.addAttribute("reportList", reportList);
		        return page("osReport");
	}
	
	//下面是场景报表

	@RequestMapping("/sceneReport")
	public String sceneReport(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		
		//日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String startDate = null;
				String endDate = null;
				
				//广告主，订单，活动，投放
				Long advertiserId = null;
				Long orderId = null;
				Long campaignId = null;
				Long adGroupId = null;
				
				String advertiserName = "全部广告主";
				String orderName = "全部订单";
				String campaignName = "全部活动";
				String adGroupName = "全部投放";
				/**
				 * 下面对下拉框中传进来的值进行判断，若是未操作，则为空值，前端设置时默认为全部（-1）
				 * 注意前后层次关系，同时要考虑到登录帐号权限问题，此时暂未考虑
				 * 下拉框传值Id需要同步
				 */
				
				//广告主选择与否
				if (null == paramMap.get("selectedadvertiserId")
							|| "".equals(paramMap.get("selectedadvertiserId"))) {
						advertiserId = null;
						advertiserName = "全部广告主";
					} else {
						// 如果要查询的是所有广告主则让广告主id为空
						if (-1 == Long.parseLong((String) paramMap
								.get("selectedadvertiserId"))) {
							advertiserId = null;
							advertiserName = "全部广告主";
						} else {
							advertiserId = Long.parseLong((String) paramMap
									.get("selectedadvertiserId"));
							advertiserName = (String)paramMap.get("selectedadvertiserName");
						}
					}
				
				//订单选择与否
				if (null == paramMap.get("selectedorderId")
						|| "".equals(paramMap.get("selectedorderId"))) {
					orderId = null;
					orderName = "全部订单";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedorderId"))) {
						orderId = null;
						orderName = "全部订单";
					} else {
						orderId = Long.parseLong((String) paramMap
								.get("selectedorderId"));
						orderName = (String)paramMap.get("selectedorderName");
					}
				}
				
				//活动选择与否
				if (null == paramMap.get("selectedcampaignId")
						|| "".equals(paramMap.get("selectedcampaignId"))) {
					campaignId = null;
					campaignName = "全部活动";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedcampaignId"))) {
						campaignId = null;
						campaignName = "全部活动";
					} else {
						campaignId = Long.parseLong((String) paramMap
								.get("selectedcampaignId"));
						campaignName = (String)paramMap.get("selectedcampaignName");
					}
				}
				
				//投放选择与否
				if (null == paramMap.get("selectedadGroupId")
						|| "".equals(paramMap.get("selectedadGroupId"))) {
					adGroupId = null;
					adGroupName = "全部投放";
				} else {
					if (-1 == Long.parseLong((String) paramMap
							.get("selectedadGroupId"))) {
						adGroupId = null;
						adGroupName = "全部投放";
					} else {
						adGroupId = Long.parseLong((String) paramMap
								.get("selectedadGroupId"));
						adGroupName = (String)paramMap.get("selectedadGroupName");
					}
				}		
							
					//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
					if (null == paramMap.get("dateRangePicker")
							|| "".equals(paramMap.get("dateRangePicker"))) {
						startDate = endDate = sdf.format(new Date((new Date())
								.getTime() - 24 * 60 * 60 * 1000));
					} else {
						String[] choosedDate = ((String) paramMap
								.get("dateRangePicker")).split("to");
						startDate = choosedDate[0].trim();
						endDate = choosedDate[1].trim();
					} 
				
				paramMap.put("advertiserId", advertiserId);
				paramMap.put("orderId", orderId);
				paramMap.put("campaignId", campaignId);
				paramMap.put("adGroupId",  adGroupId);
				paramMap.put("selectedadvertiserName", advertiserName);
				paramMap.put("selectedorderName", orderName);
				paramMap.put("selectedcampaignName", campaignName);
				paramMap.put("selectedadGroupName",  adGroupName);
				paramMap.put("startDate",  startDate);
				paramMap.put("endDate",  endDate);
				
				//查询搜索对应的数据
				int totalRow = adReportService.findCountForScene(paramMap);
			
				Pager pager = new Pager();
				pager.setPage(page);
				pager.setTotalRow(totalRow);
				
				List<DeliverAnalysis> reportList = adReportService.findByPlaceName(paramMap, pager);
				
				if(reportList.size() == 0){
					DeliverAnalysis map = new DeliverAnalysis();
					DeliverAnalysis deliver = new DeliverAnalysis();
					deliver.setImpression(0);
					deliver.setClick(0);
					deliver.setVisit(0);
					deliver.setConversion(0);
					deliver.setConsume(0);
					deliver.seteCmp(0);
					deliver.setClickRate(0);
					deliver.setVisitRate(0);
					deliver.setConversionRate(0);
					map = deliver;
					model.addAttribute("reportMap", map);
				}
				else {
				//数据报表中第一栏 全部  的显示
				HashMap<String,Double> map = new HashMap<String,Double>();
				map.put("impressionSum", reportList.get(0).getImpressionSum());
				map.put("clickSum", reportList.get(0).getClickSum());
				map.put("visitSum", reportList.get(0).getVisitSum());
				map.put("conversionSum", reportList.get(0).getConversionSum());
				map.put("consumeSum", reportList.get(0).getConsumeSum());
				map.put("eCmpSum", reportList.get(0).geteCmpSum());
				map.put("clickRatesum", reportList.get(0).getClickRatesum());
				map.put("visitRatesum", reportList.get(0).getVisitRatesum());
				map.put("conversionRatesum", reportList.get(0).getConversionRatesum());
				model.addAttribute("reportMap", map);
				}
				
				
				model.addAllAttributes(paramMap);
				model.addAttribute("pager", pager);
				model.addAttribute("reportList", reportList);
		        return page("sceneReport");
	}
	
	@RequestMapping("/exportDataReportExcel")//导出excel
	public void  exportDataReportExcel(Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String,Object> paramMap,
			@RequestParam(defaultValue="1") int page){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = null;
		String endDate = null;
		Long advertiserId = null; 
		Long orderId = null; 
		Long campaignId = null; 
		Long adGroupId = null;
		Long dimensionId = null;
		
		String advertiserName = "";
		String orderName = "";
		String campaignName = "";
		String adGroupName = "";
		//广告主选择与否
		if (null == paramMap.get("selectedadvertiserId")
					|| "".equals(paramMap.get("selectedadvertiserId"))) {
				advertiserId = null;
				advertiserName = null;
			} else {
				// 如果要查询的是所有广告主则让广告主id为空
				if (-1 == Long.parseLong((String) paramMap
						.get("selectedadvertiserId"))) {
					advertiserId = null;
					advertiserName = null;
				} else {
					advertiserId = Long.parseLong((String) paramMap
							.get("selectedadvertiserId"));
					advertiserName = (String) paramMap.get("selectedadvertiserName");
				}
			}
		
		//订单选择与否
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))) {
			orderId = null;
			orderName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedorderId"))) {
				orderId = null;
				orderName = null;
			} else {
				orderId = Long.parseLong((String) paramMap
						.get("selectedorderId"));
				orderName = (String) paramMap.get("selectedorderName");
			}
		}
		
		//活动选择与否
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))) {
			campaignId = null;
			campaignName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedcampaignId"))) {
				campaignId = null;
				campaignName = null;
			} else {
				campaignId = Long.parseLong((String) paramMap
						.get("selectedcampaignId"));
				campaignName = (String) paramMap.get("selectedcampaignName");
			}
		}
		
		//投放选择与否
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))) {
			adGroupId = null;
			adGroupName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadGroupId"))) {
				adGroupId = null;
				adGroupName = null;
			} else {
				adGroupId = Long.parseLong((String) paramMap
						.get("selectedadGroupId"));
				adGroupName = (String) paramMap.get("selectedadGroupName");
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
		if (null == paramMap.get("dateRangePicker")
					|| "".equals(paramMap.get("dateRangePicker"))) {
			startDate = endDate = sdf.format(new Date((new Date())
						.getTime() - 24 * 60 * 60 * 1000));
		} else {
			String[] choosedDate = ((String) paramMap
						.get("dateRangePicker")).split("to");
			startDate = choosedDate[0].trim();
			endDate = choosedDate[1].trim();
		} 
		//选择维度
		if (null == paramMap.get("selecteddimensionId")
					|| "".equals(paramMap.get("selecteddimensionId"))) {
			dimensionId = null;
		} else {
			// 如果要查询的是所有广告主则让广告主id为空
			if (-1 == Long.parseLong((String) paramMap
						.get("selecteddimensionId"))) {
				dimensionId = null;
			} else {
				dimensionId = Long.parseLong((String) paramMap
								.get("selecteddimensionId"));
			}
		}
		
		paramMap.put("advertiserId", advertiserId);
		paramMap.put("orderId", orderId);
		paramMap.put("campaignId", campaignId);
		paramMap.put("adGroupId",  adGroupId);
		paramMap.put("advertiserName", advertiserName);
		paramMap.put("orderName", orderName);
		paramMap.put("campaignName", campaignName);
		paramMap.put("adGroupName",  adGroupName);
		paramMap.put("dimensionId",  dimensionId);
		paramMap.put("startDate",  startDate);
		paramMap.put("endDate",  endDate);
		
		
		List<DeliverAnalysis> reportList = adReportService.findByTotalReport(paramMap);
		
		if(reportList.size() == 0){
//			List sumList = reportList.get(0).get
			paramMap.put("impressionSum", 0);
			paramMap.put("clickSum", 0);
			paramMap.put("visitSum", 0);
			paramMap.put("conversionSum", 0);
			paramMap.put("consumeSum", 0);
			paramMap.put("eCmpSum", 0);
			paramMap.put("clickRatesum", 0);
			paramMap.put("visitRatesum", 0);
			paramMap.put("conversionRatesum", 0);
		}
		else {
		//数据报表中第一栏 全部  的显示
			paramMap.put("impressionSum", reportList.get(0).getImpressionSum());
			paramMap.put("clickSum", reportList.get(0).getClickSum());
			paramMap.put("visitSum", reportList.get(0).getVisitSum());
			paramMap.put("conversionSum", reportList.get(0).getConversionSum());
			paramMap.put("consumeSum", reportList.get(0).getConsumeSum());
			paramMap.put("eCmpSum", reportList.get(0).geteCmpSum());
			paramMap.put("clickRatesum", reportList.get(0).getClickRatesum());
			paramMap.put("visitRatesum", reportList.get(0).getVisitRatesum());
			paramMap.put("conversionRatesum", reportList.get(0).getConversionRatesum());
		}
		//维度数据匹配导出
		
		
		
		
		
		List<HashMap<String,Object>> dimensionlist = new ArrayList<HashMap<String,Object>>();
		if(dimensionId != null && !"".equals(dimensionId)){
			dimensionlist = getDimensionById(dimensionId);
			if(dimensionlist.size() >0 ){
				String content = "";
				for (int i = 0; i < dimensionlist.size(); i++) {
					content += dimensionlist.get(i).get("dimension")+"-";
				}
				content = content.substring(0,content.length()-1);
				paramMap.put("dimension",content);
				paramMap.put("dimensionTargetlist",dimensionlist);
			}
		}
		
		//显示的列
		paramMap.put("impression", null);//曝光
		paramMap.put("click", null);//点击
		paramMap.put("visit", null);//到达
		paramMap.put("conversion",  null);//转化
		paramMap.put("consume",  null);//花费
		if(null != paramMap.get("checkItems") || !"".equals(paramMap.get("checkItems"))){
			String[] checkItems = paramMap.get("checkItems").toString().split(",");
			for (int i = 0; i < checkItems.length; i++) {
				if(paramMap.containsKey(checkItems[i])){
					paramMap.put(checkItems[i], checkItems[i]);
				}
			}
		}
		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 = 15; 
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        
        
        
        String excelTemplate = templateProcessor.processTemplate(
				"excel/dataRequestReport.ftl",  paramMap);
        try {
			PrintWriter out =response.getWriter();   
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 这里搜索数据的条件都还没有都是默认的
	 * @param request
	 * @param response
	 * @param paramMap 如果是地域报表就必须传递一个location的参数，值是location（这个值可以随便）
	 *其他的类似，依次是系统（system）场景(place)
	 */
	@RequestMapping("/exportOtherReportExcel")
	public void  exportOtherReportExcel(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		
		/**
		 * 这里没有数据线测试没有数据的
		 */
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = null;
		String endDate = null;
		Long advertiserId = null; 
		Long orderId = null; 
		Long campaignId = null; 
		Long adGroupId = null;
		
		String advertiserName = "";
		String orderName = "";
		String campaignName = "";
		String adGroupName = "";
		//广告主选择与否
		if (null == paramMap.get("selectedadvertiserId")
				|| "".equals(paramMap.get("selectedadvertiserId"))) {
			advertiserId = null;
			advertiserName = null;
		} else {
			// 如果要查询的是所有广告主则让广告主id为空
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadvertiserId"))) {
				advertiserId = null;
				advertiserName = null;
			} else {
				advertiserId = Long.parseLong((String) paramMap
						.get("selectedadvertiserId"));
				advertiserName = (String) paramMap.get("selectedadvertiserName");
			}
		}
	
		//订单选择与否
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))) {
			orderId = null;
			orderName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedorderId"))) {
				orderId = null;
				orderName = null;
			} else {
				orderId = Long.parseLong((String) paramMap
						.get("selectedorderId"));
				orderName = (String) paramMap.get("selectedorderName");
			}
		}
		
		//活动选择与否
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))) {
			campaignId = null;
			campaignName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedcampaignId"))) {
				campaignId = null;
				campaignName = null;
			} else {
				campaignId = Long.parseLong((String) paramMap
						.get("selectedcampaignId"));
				campaignName = (String) paramMap.get("selectedcampaignName");
			}
		}
		
		//投放选择与否
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))) {
			adGroupId = null;
			adGroupName = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadGroupId"))) {
				adGroupId = null;
				adGroupName = null;
			} else {
				adGroupId = Long.parseLong((String) paramMap
						.get("selectedadGroupId"));
				adGroupName = (String) paramMap.get("selectedadGroupName");
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 to 分割
		if (null == paramMap.get("dateRangePicker")
					|| "".equals(paramMap.get("dateRangePicker"))) {
			startDate = endDate = sdf.format(new Date((new Date())
						.getTime() - 24 * 60 * 60 * 1000));
		} else {
			String[] choosedDate = ((String) paramMap
						.get("dateRangePicker")).split("to");
			startDate = choosedDate[0].trim();
			endDate = choosedDate[1].trim();
		} 
		
		paramMap.put("advertiserId", advertiserId);
		paramMap.put("orderId", orderId);
		paramMap.put("campaignId", campaignId);
		paramMap.put("adGroupId",  adGroupId);
		paramMap.put("advertiserName", advertiserName);
		paramMap.put("orderName", orderName);
		paramMap.put("campaignName", campaignName);
		paramMap.put("adGroupName",  adGroupName);
		paramMap.put("startDate",  startDate);
		paramMap.put("endDate",  endDate);

		//显示的列
		paramMap.put("impression", null);//曝光
		paramMap.put("click", null);//点击
		paramMap.put("visit", null);//到达
		paramMap.put("conversion",  null);//转化
		paramMap.put("consume",  null);//花费
		if(null != paramMap.get("checkItems") || !"".equals(paramMap.get("checkItems"))){
			String[] checkItems = paramMap.get("checkItems").toString().split(",");
			for (int i = 0; i < checkItems.length; i++) {
				if(paramMap.containsKey(checkItems[i])){
					paramMap.put(checkItems[i], checkItems[i]);
				}
			}
		}		
		List<DeliverAnalysis> reportList = new ArrayList<DeliverAnalysis>();
		/**
		 * 判断一下是哪个报表
		 */
		if(paramMap.containsKey("location")) {
			paramMap.put("location", "location");
			reportList = adReportService.findByLocation(paramMap);
		}
		if(paramMap.containsKey("system")) {
			paramMap.put("system", "system");
			reportList = adReportService.findByOs(paramMap);
		}
		if(paramMap.containsKey("place")) {
			paramMap.put("place", "place");
			reportList = adReportService.findByPlaceName(paramMap);
		}
		paramMap.put("dataList", reportList);
		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 = 11; 
        paramMap.put("dataSize", reportList.size());
        paramMap.put("column", column);
        paramMap.put("startDate", startDate);
        paramMap.put("endDate", endDate);
        String excelTemplate = templateProcessor.processTemplate(
				"excel/otherReport.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 List<HashMap<String,Object>> getDimensionById(
			@RequestParam long dimensionId) {
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		Dimension dimension = dimensionService.findById(dimensionId);
		String content = dimension.getContent();
		if(content != null && !"".equals(content)){
			String[] contentArr = content.split("-");
			for (int i = 0; i < contentArr.length; i++) {
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("dimension", contentArr[i]);
				map.put("dimensionTarget", getDimensionType(contentArr[i]));
				list.add(map);
			}
		}
		return list;
	}
	
	public String getDimensionType(String dimension){
		String type = "";
		if(dimension.equals("广告主")){
			type = "advertiserName";
		}else if(dimension.equals("订单")){
			type = "orderName";
		}else if(dimension.equals("活动")){
			type = "campaignName";
		}else if(dimension.equals("投放")){
			type = "adGroupName";
		}else if(dimension.equals("创意")){
			type = "bannerName";
		}else if(dimension.equals("日期")){
			type = "reportDate";
		}
		return type;
	}
	
	//修改默认值
	@RequestMapping("/updateDimensionDefault")
	public @ResponseBody String updateDimensionDefault(@RequestParam long dimensionId){
		dimensionService.updateDimensionDefault(dimensionId);
		return OK;
	}
	
}
