 package com.cloudcross.ssp.web.advertiser.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.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.DeliverAnalysis;
import com.cloudcross.ssp.model.Dimension;
import com.cloudcross.ssp.service.IAdGroupService;
import com.cloudcross.ssp.service.IAdReportService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ICampaignService;
import com.cloudcross.ssp.service.IDimensionService;
import com.cloudcross.ssp.service.IOrderService;


@Controller
@RequestMapping("/advertiser/main/ad/report/advertiser-report")
public class AdvertiserReportController extends SimpleController {
	
	@Autowired
	private IAdReportService adReportService;
	@Autowired
	private IDimensionService dimensionService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	private GenericIBatisDao iBatisDao;
	@Autowired
	private IAdvertiserService advertiserService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private ICampaignService campaignService;
	@Autowired 
	private IAdGroupService adGroupService;
	
	@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 = advertiserService.findById(advertiserId).getName();
			}
		}
	
		//订单选择与否
		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 = orderService.findById(orderId).getName();
			}
		}
		
		//活动选择与否
		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 = campaignService.findById(campaignId).getName();
			}
		}
		
		//投放选择与否
		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 = adGroupService.findById(adGroupId).getAdGroupName();
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 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);
		//维度更新表格
		if(dimensionId == null){
			HashMap<String,Object> dimensionmap = dimensionService.selectDimensionIdBydefault(account.getId());
			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);
					paramMap.put("dimensionStr", list.get(list.size()-1).get("dimensionStr"));
			}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);
				paramMap.put("dimensionStr", list.get(list.size()-1).get("dimensionStr"));
			}else{
				model.addAttribute("dimensionLength",null);
				model.addAttribute("dimensionTarget",null);
			}
		}
		int totalRow = adReportService.findCountForDeliverEffectAnalysisAdvertiser(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<DeliverAnalysis> reportList = adReportService.findByTotalReportAdvertiser(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 {
		double impressionSum = 0;
		double clickSum = 0;
		double visitSum = 0;
		double conversionSum = 0;
		double consumeSum = 0;
		double eCmpSum = 0;
		double clickRatesum = 0;
		double visitRatesum = 0;
		double conversionRatesum = 0;
		for(DeliverAnalysis d :reportList){
			impressionSum = impressionSum+d.getImpression();
			clickSum = clickSum + d.getClick();
			visitSum = visitSum + d.getVisit();
			conversionSum = conversionSum + d.getConversion();
			consumeSum = consumeSum + d.getConsume();
			eCmpSum = eCmpSum + d.geteCmp();
			
		}
		clickRatesum = 100*clickSum/impressionSum;
		visitRatesum = 100*visitSum/clickSum;
		conversionRatesum = 100*conversionSum/visitSum;
		
		//数据报表中第一栏 全部  的显示
		HashMap<String,Double> map = new HashMap<String,Double>();
		map.put("impressionSum", impressionSum);
		map.put("clickSum", clickSum);
		map.put("visitSum", visitSum);
		map.put("conversionSum", conversionSum);
		map.put("consumeSum", consumeSum);
		map.put("eCmpSum", eCmpSum);
		map.put("clickRatesum", clickRatesum);
		map.put("visitRatesum", visitRatesum);
		map.put("conversionRatesum", conversionRatesum);
		model.addAttribute("reportMap", map);
		}
		
		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"));
		}
		
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("reportList", reportList);
		return index;
	}
	
	
	// 创意报表
		@RequestMapping("/ideaReport")
		public String idealReport(Model model,
				@RequestParam HashMap<String, Object> paramMap,
				@RequestParam(defaultValue = "1") int page) {
			initParams(paramMap);
			// 查询搜索对应的数据
			int totalRow = adReportService.findCountForBanner(paramMap);
			Pager pager = new Pager();
			pager.setPage(page);
			pager.setTotalRow(totalRow);
			paramMap.put("pager", pager);
			List<DeliverAnalysis> reportList = adReportService.findBannerByConditions(paramMap);
//			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("ideaReport");
		}

		/**
		 * 初始化条件数据
		 * 
		 * @param paramMap
		 */
		private void initParams(HashMap<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 = "全部投放";
			/**
			 * 下面对下拉框中传进来的值进行判断，若是未操作，则为空值，前端设置时默认为全部（-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 = advertiserService.findById(advertiserId).getName();
				}
			}

			// 订单选择与否
			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 = orderService.findById(orderId).getName();
				}
			}

			// 活动选择与否
			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 = campaignService.findById(campaignId).getName();
				}
			}

			// 投放选择与否
			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 = adGroupService.findById(adGroupId).getAdGroupName();
				}
			}

			// 判断日期是否为默认值昨天，日期格式与上面相统一，用 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);
		}

	
	
	
	
	/**
	 * 地域报表控制
	 * 前端要传递过来四个参数，分别是广告主id，变量名为selectedadvertiserId，订单id变量名为selectedorderId
	 * 活动id变量名为selectedcampaignId，投放id变量名为selectedadGroupId
	 * @param model
	 * @param paramMap
	 * @param page
	 * @return
	 */
	@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 agentId = 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")) 
					|| "-1".equals(String.valueOf(paramMap.get("selectedadvertiserId")))) {
				advertiserId = null;
				advertiserName = "全部广告主";
				agentId = getLoginUser().getAgentId();
			} else {
					advertiserId = Long.parseLong(String.valueOf(paramMap
							.get("selectedadvertiserId")));
					advertiserName = advertiserService.findById(advertiserId).getName();
					agentId = null;
			}
		
		//对传递过来的订单id的处理
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))
				|| "-1".equals(String.valueOf(paramMap.get("selectedorderId")))) {
			orderId = null;
			orderName = "全部订单";
		} else {
				orderId = Long.parseLong(String.valueOf(paramMap
						.get("selectedorderId")));
				orderName = orderService.findById(orderId).getName();
		}
		
		
		// 对传递过来的活动id的处理
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))
				|| "-1".equals(String.valueOf(paramMap.get("selectedcampaignId")))) {
			campaignId = null;
			campaignName = "全部订单";
		} else {
			campaignId = Long.parseLong(String.valueOf(paramMap
					.get("selectedcampaignId")));
			campaignName = campaignService.findById(campaignId).getName();
		}
		
		
		
		// 对传递过来的投放id的处理
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))
				|| "-1".equals(String.valueOf(paramMap
						.get("selectedadGroupId")))) {
			adGroupId = null;
			adGroupName = "全部订单";
		} else {
			adGroupId = Long.parseLong(String.valueOf(paramMap
					.get("selectedadGroupId")));
			adGroupName = adGroupService.findById(adGroupId).getAdGroupName();
		}
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 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("agentId", agentId);
		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.findCountForLocationAdvertiser(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
				
		List<DeliverAnalysis> reportList = adReportService.findByLocationAdvertiser(paramMap, pager);
			
		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 = advertiserService.findById(advertiserId).getName();
						}
					}
				
				//订单选择与否
				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 = orderService.findById(orderId).getName();
					}
				}
				
				//活动选择与否
				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 = campaignService.findById(campaignId).getName();
					}
				}
				
				//投放选择与否
				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 = adGroupService.findById(adGroupId).getAdGroupName();
					}
				}		
							
					//判断日期是否为默认值昨天，日期格式与上面相统一，用 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);
				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);
				}
				
				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 = advertiserService.findById(advertiserId).getName();
						}
					}
				
				//订单选择与否
				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 = orderService.findById(orderId).getName();
					}
				}
				
				//活动选择与否
				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 = campaignService.findById(campaignId).getName();
					}
				}
				
				//投放选择与否
				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 = adGroupService.findById(adGroupId).getAdGroupName();
					}
				}		
							
					//判断日期是否为默认值昨天，日期格式与上面相统一，用 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;
			} else {
				// 如果要查询的是所有广告主则让广告主id为空
				if (-1 == Long.parseLong((String) paramMap
						.get("selectedadvertiserId"))) {
					advertiserId = null;
				} else {
					advertiserId = Long.parseLong((String) paramMap
							.get("selectedadvertiserId"));
					advertiserName = advertiserService.findById(advertiserId).getName();
				}
			}
		
		//订单选择与否
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))) {
			orderId = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedorderId"))) {
				orderId = null;
			} else {
				orderId = Long.parseLong((String) paramMap
						.get("selectedorderId"));
				orderName = orderService.findById(orderId).getName();
			}
		}
		
		//活动选择与否
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))) {
			campaignId = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedcampaignId"))) {
				campaignId = null;
			} else {
				campaignId = Long.parseLong((String) paramMap
						.get("selectedcampaignId"));
				campaignName = campaignService.findById(campaignId).getName();
			}
		}
		
		//投放选择与否
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))) {
			adGroupId = null;
		} else {
			if (-1 == Long.parseLong((String) paramMap
					.get("selectedadGroupId"))) {
				adGroupId = null;
			} else {
				adGroupId = Long.parseLong((String) paramMap
						.get("selectedadGroupId"));
				adGroupName = adGroupService.findById(adGroupId).getAdGroupName();
			}
		}		
					
		//判断日期是否为默认值昨天，日期格式与上面相统一，用 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<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("dimensionStr", dimensionlist.get(dimensionlist.size()-1).get("dimensionStr"));
			}
		}
		
		List<DeliverAnalysis> reportList = adReportService.findByTotalForExcelAdvertiser(paramMap);
		if(reportList.size() == 0){
			paramMap.put("impression", 0);
			paramMap.put("click", 0);
			paramMap.put("visit", 0);
			paramMap.put("conversion", 0);
			paramMap.put("consume", 0);
			paramMap.put("eCmp", 0);
			paramMap.put("clickRate", 0);
			paramMap.put("visitRate", 0);
			paramMap.put("conversionRate", 0);
		}else {
			double impressionSum = 0;
			double clickSum = 0;
			double visitSum = 0;
			double conversionSum = 0;
			double consumeSum = 0;
			double eCmpSum = 0;
			double clickRatesum = 0;
			double visitRatesum = 0;
			double conversionRatesum = 0;
			for(DeliverAnalysis d :reportList){
				impressionSum = impressionSum+d.getImpression();
				clickSum = clickSum + d.getClick();
				visitSum = visitSum + d.getVisit();
				conversionSum = conversionSum + d.getConversion();
				consumeSum = consumeSum + d.getConsume();
				eCmpSum = eCmpSum + d.geteCmp();
				
			}
			clickRatesum = 100*clickSum/impressionSum;
			visitRatesum = 100*visitSum/clickSum;
			conversionRatesum = 100*conversionSum/visitSum;
		//数据报表中第一栏 全部  的显示
			paramMap.put("impressionSum",impressionSum);
			paramMap.put("clickSum",clickSum);
			paramMap.put("visitSum",visitSum);
			paramMap.put("conversionSum",conversionSum);
			paramMap.put("consumeSum",consumeSum);
			paramMap.put("eCmpSum",eCmpSum);
			paramMap.put("clickRatesum",clickRatesum);
			paramMap.put("visitRatesum",visitRatesum);
			paramMap.put("conversionRatesum",conversionRatesum);
		}
		
		//显示的列
		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 agentId = 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"))
				|| "-1".equals(String.valueOf(paramMap
						.get("selectedadvertiserId")))) {
			advertiserId = null;
			advertiserName = "全部广告主";
			agentId = getLoginUser().getAgentId();
		} else {
			advertiserId = Long.parseLong(String.valueOf(paramMap
					.get("selectedadvertiserId")));
			advertiserName = advertiserService.findById(advertiserId).getName();
			agentId = null;
		}

		// 对传递过来的订单id的处理
		if (null == paramMap.get("selectedorderId")
				|| "".equals(paramMap.get("selectedorderId"))
				|| "-1".equals(String.valueOf(paramMap.get("selectedorderId")))) {
			orderId = null;
			orderName = "全部订单";
		} else {
			orderId = Long.parseLong(String.valueOf(paramMap
					.get("selectedorderId")));
			orderName = orderService.findById(orderId).getName();
		}

		// 对传递过来的活动id的处理
		if (null == paramMap.get("selectedcampaignId")
				|| "".equals(paramMap.get("selectedcampaignId"))
				|| "-1".equals(String.valueOf(paramMap
						.get("selectedcampaignId")))) {
			campaignId = null;
			campaignName = "全部订单";
		} else {
			campaignId = Long.parseLong(String.valueOf(paramMap
					.get("selectedcampaignId")));
			campaignName = campaignService.findById(campaignId).getName();
		}

		// 对传递过来的投放id的处理
		if (null == paramMap.get("selectedadGroupId")
				|| "".equals(paramMap.get("selectedadGroupId"))
				|| "-1".equals(String.valueOf(paramMap.get("selectedadGroupId")))) {
			adGroupId = null;
			adGroupName = "全部订单";
		} else {
			adGroupId = Long.parseLong(String.valueOf(paramMap
					.get("selectedadGroupId")));
			adGroupName = adGroupService.findById(adGroupId).getAdGroupName();
		}

		// 判断日期是否为默认值昨天，日期格式与上面相统一，用 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("agentId", agentId);
		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("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();
		}
	}
	
	
	
	
	/**
	 * 维度管理
	 */
    //带分页的维度管理list页面	
	@RequestMapping("/dimension")
	public String queryDimensionList(Model model,@RequestParam HashMap<String, Object> paramMap,@RequestParam(defaultValue="1") int page) {
		//将当前登录账户ID放入Map中
		paramMap.put("accountId", getLoginUser().getId());
		//查询满足条件的维度记录总数
		int totalRow = dimensionService.countByParams(paramMap);
		//分页信息
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		//带分页的维度记录
		List<Dimension> dimensionList = dimensionService.findByParams(paramMap, pager);
		
		//model.addAllAttributes(paramMap);
		//将查询结构放入model中，传到前台
		model.addAttribute("pager", pager);
		model.addAttribute("dimensionList", dimensionList);

		return page("dimension");
	}
	
	//增加维度页面
	@RequestMapping("/create")
	public String create(Model model){
		model.addAttribute("accountId", getLoginUser().getId());
		return page("create");
	}
	
	//编辑维度
	@RequestMapping("/edit")
	public String edit(Model model,@RequestParam long id) {
		//根据id查询维度。
		Dimension dimension = dimensionService.findById(id);
		//获取维度方案（以“-”间隔，如“A-B-C”）
		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("accountId", getLoginUser().getId());
		model.addAttribute("dimensionTypeList", list); 
		model.addAttribute("notdimensionTypeList", alllist); 
		model.addAttribute("dimension", dimension); 
		return page("edit");
	}
	
	//判断名称或类型是否存在
	@RequestMapping("/isExist")
	@ResponseBody
	public String isExist(@ModelAttribute("form") Dimension dimension){
		String success = "";
		
		//添加或修改前判断name或content是否已存在
		String name = dimension.getName();
		String content = dimension.getContent();
		Integer accountId = getLoginUser().getId();
		List<Dimension> nameList = queryDimensionByNameAndAccountId(name,accountId);
		List<Dimension> contentList = queryDimensionByContentAndAccountId(content,accountId);
		
		
		//修改后根据ID来更新当前记录
   		//dimensionService.edit(dimension);
		//修改页面和添加页面公用按钮，用ID来区分是添加还是修改
	   	if (dimension.getId() == null){//id在数据库中自增长，新增的时候ID为null还没有生成	
	   		if(nameList.size()>0){//维度名称已存在
	   			success = "YES";
	   			return success;
	   		}
	   		if(contentList.size()>0){//维度方案已存在
	   			success = "YES";
	   			return success;
	   		}
	   		success = "NO";
	   	}else{//修改保存
	   	//修改前的维度记录
			Dimension dimensioned = dimensionService.findById(dimension.getId());
	   		//只修改了name
	   		if(!dimensioned.getName().equals(dimension.getName())&&dimensioned.getContent().equals(dimension.getContent())){
	   			//判断name是否存在
	   			if(nameList.size() > 0){//维度名称已存在
	   				success = "YES";
	   			}else{//存在
	   				success = "NO";//不存在
	   			}
	   		}else if(dimensioned.getName().equals(dimension.getName())&&!dimensioned.getContent().equals(dimension.getContent())){
	   			//只修改了维度方案
	   			//判断维度方案是否存在
	   			if(contentList.size() > 0){
	   				success = "YES";//维度方案已存在
	   			}else{
	   				success = "NO";
	   			}
	   		}else if(!dimensioned.getName().equals(dimension.getName())&&!dimensioned.getContent().equals(dimension.getContent())){
	   			//维度名称，方案都修改
	   			if(nameList.size() > 0){
	   				success = "YES";//维度名称存在
	   				return success;
	   			}
	   			if(contentList.size() > 0){
	   				success = "YES";//维度方案存在
	   				return success;
	   			}
	   			success = "NO";//不存在
	   		}else{//没做任何修改
	   			success = "NO";
	   		}

	   	}
		return success;
	}
	//维度新增或修改页面保存功能
	@RequestMapping("/save")
	public String save(@ModelAttribute("form") Dimension dimension){
		//修改页面和添加页面公用按钮，用ID来区分是添加还是修改
	   	if (dimension.getId() == null){//id在数据库中自增长，新增的时候ID为null还没有生成	
	   			dimensionService.add(dimension);
	   	}else{//修改保存
	   			dimensionService.edit(dimension);
	   	}
		return redirect(page("dimension"));
	}
	
	private List<Dimension> queryDimensionByNameAndAccountId(String name,Integer accountId){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("name", name);
		map.put("accountId", accountId);
		return iBatisDao.getList("dimensionSqlMapper.queryDimensionByNameAndAccountId", map);
	}
	
	private List<Dimension> queryDimensionByContentAndAccountId(String content,Integer accountId){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("content", content);
		map.put("accountId", accountId);
		return iBatisDao.getList("dimensionSqlMapper.queryDimensionByContentAndAccountId", map);
	}
	
	
	//删除
	@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("/dimensionlist")
	public @ResponseBody List<Dimension> dimensionlist(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		Account account = getLoginUser();
		paramMap.put("accountId", account.getId());
		List<Dimension> dimensionList = dimensionService.findByParams(paramMap, null);
		return dimensionList;
	}
	
	
	//修改默认值
	@RequestMapping("/updateDimensionDefault")
	public @ResponseBody String updateDimensionDefault(@RequestParam long dimensionId){
		Dimension dimension = this.dimensionService.findById(dimensionId);
		dimensionService.updateDimensionDefault(dimension);
		return OK;
	}
	
	//维度管理	
		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("-");
				String dimensionStr = "";
				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]));
				    dimensionStr += getDimensionType(contentArr[i])+",";
				    if(i == contentArr.length-1 && dimensionStr != ""){
				        dimensionStr = dimensionStr.substring(0,dimensionStr.length()-1);
				        map.put("dimensionStr", dimensionStr);
				    }
					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;
		}
		
	
}
