package com.cloudcross.ssp.web.back.main.ap;

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

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

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.StringUtils;
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.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
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.common.utils.SqlHelper;
import com.cloudcross.ssp.listener.InitData;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Location;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.PlaceClassInformation;
import com.cloudcross.ssp.model.PlaceOperator;
import com.cloudcross.ssp.model.Wifi;
import com.cloudcross.ssp.model.WifiSum;
import com.cloudcross.ssp.service.ILocationService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IPlaceClassInformationService;
import com.cloudcross.ssp.service.IPlaceOperatorService;
import com.cloudcross.ssp.service.IPlaceService;
import com.cloudcross.ssp.service.IWifiService;
import com.cloudcross.ssp.service.IWifiSumService;

/**
 * 热点管理相关控制器
 * @author chenyou
 *
 */
@Controller("back.apmacController")
@RequestMapping("/back/main/ap/apmac")
public class ApmacController extends SimpleController {
	private static final Logger LOG = Logger.getLogger(ApmacController.class);
	
	@Autowired
	private IWifiService wifiService;
	@Autowired
	private ILogService logService;
	@Autowired
	private ILocationService locationService;
	@Autowired
	private IPlaceOperatorService placeOperatorService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	private IPlaceService placeService;
	@Autowired
	private IOperatorService operatorService;
	@Autowired
	private IPlaceClassInformationService placeClassInformationService;
	@Autowired
	private IWifiSumService wifiSumService;
	/**
	 * 热点详情的列表页
	 * 前端要传递几个参数，分别所选媒体的媒体Id(变量名为selectedOperatorId)，省(变量名为cn)，市(变量名为cnCity)，场景(变量名为place，这个是运营商定义的场景名称，传过来传个场景名称就行)，
	 * 数聚场景id(这个数聚场景是云联自己定义的，变量名为placeId)
	 * 还有一个搜索参数，按mac地址搜索
	 * 注：如果传过来的参数是空值或者空字符串或者没传，则按默认值进行搜索，默认的为全部
	 * @param model
	 * @param paramMap
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model, @RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "1") int page) {
		
		Long operatorId = null;
		String operatorName = null;
		String cn = null;
		String cnCity = null;
		String place = null;
		Long placeClassId = null;
		String placeClassName = null;
		String location = null;
		List<Long> placeIdList = null;
		
		/**
		 * 下面对传递过来的几个参数进行处理
		 */
		if(null != paramMap.get("selectedOperatorId") && !"".equals(paramMap.get("selectedOperatorId"))) {
			operatorId = Long.parseLong(String.valueOf(paramMap.get("selectedOperatorId")));
			if(operatorId == -1){
				operatorId = null;
			}
		}
		
		if(null != paramMap.get("cn") && !"".equals(paramMap.get("cn"))) {
			cn = String.valueOf(paramMap.get("cn"));
		} 
		
		if(null != paramMap.get("cnCity") && !"".equals(paramMap.get("cnCity"))) {
			cnCity = String.valueOf(paramMap.get("cnCity"));
		}
		
		//根据cn和cnCity得到它的location
		if(null != cn || null != cnCity) {
			if(null != cn && null != cnCity) {
				location = InitData.getLocation(cn, cnCity);
			}
			
			//如果cnCity等于空则表明是选择该省下的所有的市
			if(null != cn && null == cnCity) {
				location = InitData.getLocation(cn);
				location = location.substring(0, (location.length() - 2)) + "%";
			}
		}
		
		if(null != paramMap.get("placeId") && !"".equals(paramMap.get("placeId"))) {
			placeClassId = Long.parseLong(String.valueOf(paramMap.get("placeId")));
		} 
		
		//通过数聚场景id得到数聚子场景的id的集合
		if(null != placeClassId) {
			placeIdList = InitData.placeClassMap.get(placeClassId.intValue());
		}
		
		if(null != paramMap.get("place") && !"".equals(paramMap.get("place"))) {
			place = String.valueOf(paramMap.get("place")).trim();
		}
		
		paramMap.put("cnCity", cnCity);
		paramMap.put("operatorId", operatorId);
		paramMap.put("location", location);
		paramMap.put("placeIdList", placeIdList);
		paramMap.put("place", place);

		int totalRow = 0;
		Pager pager = null;
		pager = new Pager();
		//查询符合条件的总的条数
		totalRow = wifiService.countByParamsBack(paramMap);
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Wifi> wifiList = wifiService.findByParamsBack(paramMap, pager);
		
		for(Wifi w : wifiList) {
			//根据location设置它的省和市
			//注:这里因为如果location是以“00”结尾的话，那它的省份可以确认，但是市的话就不能够直接从内存加载的信息里取
			if(w.getLocation().endsWith("00")) {
				Location l = locationService.findByLocation(w.getLocation());
				w.setCn(l.getCn());
				w.setCnCity(l.getCnCity());
			} else {
				if(null != InitData.locationMap.get(w.getLocation())) {
				w.setCn(InitData.locationMap.get(w.getLocation()).split(",")[0]);
				w.setCnCity(InitData.locationMap.get(w.getLocation()).split(",")[1]);
				}
			}
			
			//根据数聚子场景的id设置数聚场景的名称和数聚子场景的名称
			w.setPlaceName(InitData.placeMap.get(w.getPlaceId().intValue()));
			w.setPlaceClassName(InitData.getPlaceClassName(w.getPlaceId()));
		}
		
		//如果下拉框传的是默认值，则回传一个对应的值给前端
		if(null == operatorId || -1 == operatorId) {
			operatorName = "全部媒体";
		} else {
			operatorName = operatorService.findById(operatorId).getCompanyName();
		}
		
		if(null == cn) {
			cn = "省";
		}
		
		if(null == cnCity) {
			cnCity = "市";
		}
		
		if(null == place) {
			place = "场景";
		}
		
		if(null == placeClassId || -1 == placeClassId) {
			placeClassName = "数聚场景";
		} else {
			placeClassName = placeClassInformationService.findById(placeClassId).getName();
		}
		
		paramMap.put("operatorName", operatorName);
		paramMap.put("cn", cn);
		paramMap.put("cnCity", cnCity);
		paramMap.put("place", place);
		paramMap.put("placeName", placeClassName);
		model.addAttribute("pager",pager);
		model.addAllAttributes(paramMap);
		model.addAttribute("wifiList", wifiList);
		
		return page("list");
	}
	
	/**
	 * 前端传递一个媒体的名称(变量名称为operatorName)，默认为空值
	 * @param model
	 * @param page
	 * @return
	 */
	@RequestMapping("/relationship")
	public String relationship(Model model, @RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "1") int page) {
		String operatorName = null;
		String operatorName1 = null;
		
		/**
		 * 对传入的搜索参数做处理，如果传递的是空值或者空字符串的话就设为空
		 */
		if(null == paramMap.get("operatorName") || "".equals(paramMap.get("operatorName"))) {
			operatorName = null;
		} else {
				operatorName = String.valueOf(paramMap.get("operatorName"));
				operatorName1 = operatorName;
		}
		
		paramMap.put("operatorName", SqlHelper.doLike(operatorName));
		int totalRow = 0;
		Pager pager = null;
		pager = new Pager();
		//查询符合条件的总的条数
		totalRow = placeOperatorService.countByParamsBack(paramMap);
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<PlaceOperator> placeOperatorList = placeOperatorService.findByParamsBack(paramMap, pager);
		
		//回传给前端
		if(null != operatorName) {
			model.addAttribute("operatorName", operatorName1);
		} else {
			model.addAttribute("operatorName", operatorName);
		}
		
		model.addAttribute("placeOperatorList", placeOperatorList);
		model.addAttribute("pager",pager);
		
		return page("relationship");
	}
	
	/**
	 * 查找所有的省
	 * @return
	 */
	@RequestMapping("/cn")
	public @ResponseBody
	Map<String, List<String>> findAllProvince() {
		List<String> provinceList = locationService.findAllProvince();
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put("province", provinceList);
		return map;
	}
	
	/**
	 * 查找该省下的所有城市
	 * @param province
	 * @return
	 */
	@RequestMapping("/city")
	public @ResponseBody
	Map<String, List<String>> findCityByProvince(@RequestParam String province) {
		//这里如果传递过来的参数是空值或者空字符串则返回一个空值
		if(null == province || "".equals(province)) {
			System.out.println("传递的参数出错");
			return null;
		}
		
		try {
			province = new String(province.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		List<String> cityList = locationService.findCityByProvince(province);
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put("city", cityList);
		return map;
	}
	
	/**
	 * 查找所有的场景
	 * @return
	 */
	@RequestMapping("/place")
	public @ResponseBody
	Map<String, List<String>> findPlaceDefinedByOperator() {
		List<String> placeList = placeOperatorService.findAllPlace();
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put("place", placeList);
		return map;
	}
	
	

	/**
	 * 查找所有的数聚场景
	 * @return
	 */
	@RequestMapping("/placeClassName")
	public @ResponseBody
	List<PlaceClassInformation> placeName() {
		List<PlaceClassInformation> placeClassNameList = placeClassInformationService.findPlaceClassByOperatorId();
		return placeClassNameList;
	}
	
	/**
	 * 批量开启热点
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/enable")
	public @ResponseBody
	String enable(HttpServletRequest request,Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到热点名称
			List<String> wifiNameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Wifi wifi = wifiService.findById(id[i]);
				wifiNameList.add(wifi.getName());
			}
			
			//如果开启成功，则增加对应的修改记录
			if(wifiService.updateStatus(LangUtil.array2List(id),
					Status.enable.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是热点模块
					log.setModule("Ap");
					//对应的表名，这里是t_wifi
					log.setTableName("t_wifi");
					//对应的热点的id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("开启");
					//得到该热点的媒体公司名称
					String operatorName = operatorService.findById(wifiService.findById(id[i]).getOperatorId()).getCompanyName();
					//变更详情
					log.setAction("开启了" + operatorName + "中的热点：" + wifiNameList.get(i));
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
		}
		return OK;
	}

	/**
	 * 批量暂停热点
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/disable")
	public @ResponseBody
	String disable(HttpServletRequest request,Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到热点名称
			List<String> wifiNameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Wifi wifi = wifiService.findById(id[i]);
				wifiNameList.add(wifi.getName());
			}
			
			//如果开启成功，则增加对应的修改记录
			if(wifiService.updateStatus(LangUtil.array2List(id),
					Status.disable.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是热点模块
					log.setModule("Ap");
					//对应的表名，这里是t_wifi
					log.setTableName("t_wifi");
					//对应的热点的id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("暂停");
					//得到该热点的媒体公司名称
					String operatorName = operatorService.findById(wifiService.findById(id[i]).getOperatorId()).getCompanyName();
					//变更详情
					log.setAction("暂停了" + operatorName + "中的热点：" + wifiNameList.get(i));
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
		}
		return OK;
	}

	/**
	 * 批量删除时只是把这些选中的行的状态改为-1，并没有把它从表里面删掉
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	public @ResponseBody
	String delete(HttpServletRequest request, Long[] id) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到热点名称
			List<String> wifiNameList = new ArrayList<String>();
			
			for(int i = 0; i < id.length; i++) {
				Wifi wifi = wifiService.findById(id[i]);
				wifiNameList.add(wifi.getName());
			}
			
			//如果开启成功，则增加对应的修改记录
			if(wifiService.updateStatus(LangUtil.array2List(id),
					Status.delete.value)) {
				for(int i = 0; i < id.length; i++) {
					Log log = new Log();
					//对应模块，这里应该是热点模块
					log.setModule("Ap");
					//对应的表名，这里是t_wifi
					log.setTableName("t_wifi");
					//对应的热点的id
					log.setRecordId(id[i]);
					//对应的操作类型
					log.setActionType("删除");
					//得到该热点的媒体公司名称
					String operatorName = operatorService.findById(wifiService.findById(id[i]).getOperatorId()).getCompanyName();
					//变更详情
					log.setAction("删除了" + operatorName + "中的热点：" + wifiNameList.get(i));
					log.setActionTime("100");
					log.setAccountId(new Long(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
		}
		return OK;
	}
	
	/**
	 * 跳转到编辑的页面
	 * @param model
	 * @param paramMap
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(Model model, @RequestParam Long id) {
		Wifi wifi = wifiService.findById(id);
		model.addAttribute("wifi", wifi);
		model.addAttribute("operatorName", operatorService.findById(wifi.getOperatorId()).getCompanyName());
		System.out.println("fish"+wifi);
		return page("edit");
	}
	
	/**
	 * 跳转到创建热点页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/create")
	public String edit(Model model) {
		return page("create");
	}
	
	
	@RequestMapping("/save")
	public String save(HttpServletRequest request,@ModelAttribute("form") Wifi wifi) {
		if(null == wifi.getId()) {
			//创建时保存数据
			//通过得到的省和市的名称得到对应的location
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("cn", wifi.getCn().trim());
			paramMap.put("cnCity", wifi.getCnCity().trim());
			Location location = locationService.findByCnAndCnCity(paramMap);
			wifi.setLocation(location.getLocation());
			//根据运营商命名的场景名称和运营商id得到云联定义的场景名称对应的id
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", wifi.getPlace());
			map.put("operatorId", wifi.getOperatorId());
			Long placeId = placeOperatorService.findByNameAndOperatorId(map);
			wifi.setPlaceId(placeId);
			wifi.setUpdated(new Date());
			
			wifiService.add(wifi);
			
			/**
			 * 创建成功后增加创建的日志
			 */
			Log log = new Log();
			//对应模块，这里应该是热点模块
			log.setModule("Ap");
			//对应的表名，这里是t_wifi
			log.setTableName("t_wifi");
			//对应的热点的id
			log.setRecordId(wifi.getId());
			//对应的操作类型
			log.setActionType("创建");
			log.setActionTime("100");
			log.setAccountId(new Long(getLoginUser().getId()));
			log.setUserIp(Common.toIpAddr(request));
			log.setAccountName(getLoginUser().getAccountName());
			//创建详情
			log.setAction("在媒体" + operatorService.findById(wifi.getOperatorId()).getCompanyName() + "中创建了一个热点，热点名称为" + wifi.getName());
			logService.add(log);
			
			return redirect(page("list"));
		} else {
			//编辑后保存数据
			//先得到编辑前的数据
			Wifi formerWifi = wifiService.findById(wifi.getId());
			
			//通过得到的省和市的名称得到对应的location
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("cn", wifi.getCn().trim());
			paramMap.put("cnCity", wifi.getCnCity().trim());
			Location location = locationService.findByCnAndCnCity(paramMap);
			wifi.setLocation(location.getLocation());
			
			wifi.setPlace(wifi.getPlace().trim());
			//根据运营商命名的场景名称和运营商id得到云联定义的场景名称对应的id
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", wifi.getPlace());
			map.put("operatorId", wifi.getOperatorId());
			Long placeId = placeOperatorService.findByNameAndOperatorId(map);
			wifi.setPlaceId(placeId);
			
			wifiService.edit(wifi);
			
			//得到编辑后的热点对象
			Wifi presentWifi = wifiService.findById(wifi.getId());
			
			/**
			 *	编辑成功后，对比编辑前后的数据，如果发生了改变，则增加修改日志
			 */
			Log log = new Log();
			//对应模块，这里应该是热点模块
			log.setModule("Ap");
			//对应的表名，这里是t_wifi
			log.setTableName("t_wifi");
			//对应的热点的id
			log.setRecordId(wifi.getId());
			//对应的操作类型
			log.setActionType("编辑");
			log.setActionTime("100");
			log.setAccountId(new Long(getLoginUser().getId()));
			log.setUserIp(Common.toIpAddr(request));
			log.setAccountName(getLoginUser().getAccountName());
			
			//记录变更详情
			String action = "对"+ operatorService.findById(formerWifi.getOperatorId()).getCompanyName() +"中的热点" + formerWifi.getName() + "进行了修改: ";
			//变更标志，默认为false表示没有进行修改
			boolean updatedMark = false;
			
			//热点名称的比较
			if(!(formerWifi.getName().equals(presentWifi.getName()))) {
				action = "对热点的名称做了修改，将" + formerWifi.getName() + " ---> " + presentWifi.getName();
				updatedMark = true;
			}
			
			//省、市的比较
			if(!(formerWifi.getLocation().equals(presentWifi.getLocation()))) {
				action = "对热点的省、市进行了修改，将" + formerWifi.getCn() + " 和 " + formerWifi.getCnCity() + "--->"
						+ presentWifi.getCn() + " 和 " + presentWifi.getCnCity();
				updatedMark = true;
			}
			
			//详细地址的比较
			if(!(formerWifi.getAddress().equals(presentWifi.getAddress()))) {
				action = "对热点的详细地址进行了修改，将" + formerWifi.getAddress() + "--->"
						+ presentWifi.getAddress();
				updatedMark = true;
			}
			
			//经纬度的比较
			if(!(formerWifi.getLongitude().equals(presentWifi.getLongitude())) || !(formerWifi.getLatitude().equals(presentWifi.getLatitude()))) {
				action = "对热点的经纬度进行了修改，将经度" + formerWifi.getLongitude() + " 和纬度 " + formerWifi.getLatitude() + "--->"
						+ presentWifi.getLongitude() + " 和 " + presentWifi.getLatitude();
				updatedMark = true;
			}
			
			//场景的比较
			if(!(formerWifi.getPlace().equals(presentWifi.getPlace()))) {
				action = "对热点的场景名称进行了修改，将" + formerWifi.getPlace() + "--->"
						+ presentWifi.getPlace();
				updatedMark = true;
			}
			
			log.setAction(action);
			
			if(updatedMark) {
				logService.add(log);
			}
		}
		return redirect(page("list"));
		
	}
	
	/**
	 * 日志的列表显示的，需要传递一个热点id，变量名为id
	 * @param model
	 * @param paramMap
	 * @param page
	 * @return
	 */
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam Long id,
			@RequestParam(defaultValue = "1") int page) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 查询总行数
		paramMap.put("tableName", "t_wifi");
		paramMap.put("recordId", id);
		int totalRow = logService.countByParamsBack(paramMap);
	
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
		List<Log> logList = logService.findByParamsBack(paramMap, pager);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("id", id);
		return page("update");
	}
	
	
	/**
	 * 导出日志的excel，需要传递一个参数就是导出那个热点的的日志记录
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping("/exportLogExcel")
	public void exportLogExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Long id) {
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		Account account = getLoginUser();
		paramMap.put("operatorName", operatorService.findById(account.getOperatorId()).getCompanyName());
		paramMap.put("tableName", "t_wifi");
		paramMap.put("recordId", id);
		List<Log> logList = logService.findByParamsBack(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 = 6;
		paramMap.put("dataSize", (logList.size() + 100));
		paramMap.put("column", column);

		String excelTemplate = templateProcessor.processTemplate(
				"excel/logReportOperator.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
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping("/exportRelationshipExcel")
	public void exportRelationShipExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) {
		String operatorName = null;
		/**
		 * 对传入的搜索参数做处理，如果传递的是空值或者空字符串的话就设为空
		 */
		if(null == paramMap.get("operatorName") || "".equals(paramMap.get("operatorName"))) {
			operatorName = null;
		} else {
				operatorName = String.valueOf(paramMap.get("operatorName"));
		}
		
		paramMap.put("operatorName", SqlHelper.doLike(operatorName));
		
		List<PlaceOperator> placeOperatorList = placeOperatorService.findByParamsBack(paramMap);
		paramMap.put("dataList", placeOperatorList);
		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 = 6;
		paramMap.put("dataSize", (placeOperatorList.size() + 100));
		paramMap.put("column", column);

		String excelTemplate = templateProcessor.processTemplate(
				"excel/relationshipBack.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
	 * 前端要传递几个参数，分别所选媒体的媒体Id(变量名为selectedOperatorId)，省(变量名为cn)，市(变量名为cnCity)，场景(变量名为place，这个是运营商定义的场景名称，传过来传个场景名称就行)，
	 * 数聚场景id(变量名为placeClassId)
	 * 还有一个搜索参数，按mac地址搜索
	 * 注：如果传过来的参数是空值或者空字符串或者没传，则按默认值进行搜索，默认的为全部
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping("/exportApListExcel")
	public void exportApListExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) {
		Long operatorId = null;
		String operatorName = null;
		String cn = null;
		String cnCity = null;
		String place = null;
		Long placeClassId = null;
		String placeClassName = null;
		String location = null;
		List<Long> placeIdList = null;
		
		/**
		 * 下面对传递过来的几个参数进行处理
		 */
		try{
		if(null != paramMap.get("selectedOperatorId") && !"".equals(paramMap.get("selectedOperatorId")) && paramMap.get("selectedOperatorId") != "-1") {
			operatorId = Long.parseLong(String.valueOf(paramMap.get("selectedOperatorId")));
			operatorName = operatorService.findById(operatorId).getCompanyName();
		} else {
			operatorName = null;
		}
		
		if (null != paramMap.get("cn") && !"".equals(paramMap.get("cn"))) {
			cn = new String(String.valueOf(paramMap.get("cn")).getBytes("ISO-8859-1"),"UTF-8");
			paramMap.put("cnName", cn);
		} else {
			paramMap.put("cnName", "全部");
		}

		if (null != paramMap.get("cnCity")
				&& !"".equals(paramMap.get("cnCity"))) {
			cnCity = new String(String.valueOf(paramMap.get("cnCity")).getBytes("ISO-8859-1"),"UTF-8");
			paramMap.put("cnCityName", cnCity);
		} else {
			paramMap.put("cnCityName", "全部");
		}

			// 根据cn和cnCity得到它的location
			if (null != cn || null != cnCity) {
				if (null != cn && null != cnCity) {
					location = InitData.getLocation(cn, cnCity);
				}
				
				//如果cnCity等于空则表明是选择该省下的所有的市
				if(null != cn) {
					location = InitData.getLocation(cn);
					location = location.substring(0, (location.length() - 2)) + "%";
				}
			}
		
		if (null != paramMap.get("placeClassId")
				&& !"".equals(paramMap.get("placeClassId"))) {
			placeClassId = Long.parseLong(String.valueOf(paramMap.get("placeClassId")));
			placeClassName = placeClassInformationService.findById(placeClassId).getName();
		} else {
			placeClassName = "全部";
		}
		
			// 通过数聚场景id得到数聚子场景的id的集合
			if (null != placeClassId) {
				placeIdList = InitData.placeClassMap.get(placeClassId
						.intValue());
			}
		
		if(null != paramMap.get("place") && !"".equals(paramMap.get("place"))) {
			place = new String(String.valueOf(paramMap.get("place")).trim().getBytes("ISO-8859-1"),"UTF-8");
			paramMap.put("placeNameDefinedByOperator", place);
		} else {
			paramMap.put("placeNameDefinedByOperator", "全部");
		}

		paramMap.put("cnCity", cnCity);
		paramMap.put("operatorId", operatorId);
		paramMap.put("location", location);
		paramMap.put("placeIdList", placeIdList);
		paramMap.put("place", place);
		paramMap.put("placeName", placeClassName);
		paramMap.put("operatorName", operatorName);

		//按mac地址搜索
		if (null != paramMap.get("searchValue")
				&& !"".equals(paramMap.get("searchValue"))) {
			String name = new String(((String) paramMap.get("searchValue")).getBytes("ISO-8859-1"),"UTF-8");
			paramMap.put("searchValue", SqlHelper.doLike(name.trim()));
		} else {
			paramMap.put("searchValue", null);
		}
		
		} catch(Exception e) {
			e.printStackTrace();
		}
		List<Wifi> wifiList = wifiService.findByParamsBack(paramMap);
		
		for(Wifi w : wifiList) {
			//根据location设置它的省和市
			//注:这里因为如果location是以“00”结尾的话，那它的省份可以确认，但是市的话就不能够直接从内存加载的信息里取
			if(w.getLocation().endsWith("00")) {
				Location l = locationService.findByLocation(w.getLocation());
				w.setCn(l.getCn());
				w.setCnCity(l.getCnCity());
			} else {
				if(null != InitData.locationMap.get(w.getLocation())) {
					w.setCn(InitData.locationMap.get(w.getLocation()).split(",")[0]);
					w.setCnCity(InitData.locationMap.get(w.getLocation()).split(",")[1]);
					}
			}
			
			//根据数聚子场景的id设置数聚场景的名称和数聚子场景的名称
			w.setPlaceName(InitData.placeMap.get(w.getPlaceId().intValue()));
			w.setPlaceClassName(InitData.getPlaceClassName(w.getPlaceId()));
		}
		
		paramMap.put("dataList", wifiList);
		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 = 14;
		paramMap.put("dataSize", (wifiList.size() + 100));
		paramMap.put("column", column);

		String excelTemplate = templateProcessor.processTemplate(
				"excel/apList.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * wifi热点分布查询
	 * @param model
	 * @param cn
	 * @param cnCity
	 * @param placeId
	 * @param placeName
	 * @param page
	 * @param searchValue
	 * @return
	 */
	@RequestMapping("/wifisum")
	public String queryWifiSumList(Model model,String cn,String cnCity,Integer placeId,
			String placeName,@RequestParam(defaultValue = "1") int page,String searchValue){
		Map<String,Object>condition = new HashMap<String,Object>();
		if(cn != null && !"".equals(cn)){
			condition.put("cn", cn);
			model.addAttribute("cn", cn);
		}else{
			model.addAttribute("cn", "省");
		}
		if(cnCity != null && !"".equals(cnCity)){
			condition.put("cnCity", cnCity);
			model.addAttribute("cnCity", cnCity);
		}else{
			model.addAttribute("cnCity", "市");
		}
		if(placeId != null && !"".equals(placeId)){
			condition.put("placeId", placeId);
			model.addAttribute("placeId", placeId);
			model.addAttribute("placeName", placeName);
		}else{
			model.addAttribute("placeName", "数据场景");
		}
		if(searchValue != null && !"".equals(searchValue)){
			model.addAttribute("searchValue", searchValue);
			searchValue = "%"+searchValue+"%";
			condition.put("searchValue", searchValue);	
		}
		Integer count = this.wifiSumService.queryWifiSumCountByCondition(condition);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(count);
		condition.put("pager", pager);
		List<WifiSum> wifiSumList = this.wifiSumService.queryWifiSumByCondition(condition);
		model.addAttribute("pager", pager);
		model.addAttribute("wifiSumList", wifiSumList);
		return page("wifiSum");
	}
	
	/**
	 *wifi热点分布导出
	 * 创建人：zhoujun
	 * 创建时间：2015.12.18 11：43
	 * 注意：前端get请求提交，参数要转码  如：String str = new String(str.getBytes("ISO-8859-1"),"UTF-8");
	 * @param response
	 * @param cn
	 * @param cnCity
	 * @param placeId
	 * @param placeName
	 * @param searchValue
	 */
	@RequestMapping("/exportWifiSumExcel")
	public void queryWifiSumExport(HttpServletResponse response,String cn,String cnCity,Integer placeId,
			String placeName,String searchValue){
		Map<String,Object>condition = new HashMap<String,Object>();//存放查询条件
		Map<String,Object>map = new HashMap<String,Object>();//存放导出excel显示的参数
		if(cn != null && !"".equals(cn)){
			try {
				cn = new String(cn.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			condition.put("cn", cn);
			map.put("cn", cn);
		}else{
			map.put("cn", "全部");
		}
		if(cnCity != null && !"".equals(cnCity)){
			try {
				cnCity = new String(cnCity.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			condition.put("cnCity", cnCity);
			map.put("cnCity", cnCity);
		}else{
			map.put("cnCity", "全部");
		}
		if(placeId != null && !"".equals(placeId)){
			condition.put("placeId", placeId);
			try {
				placeName = new String(placeName.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			map.put("placeName", placeName);
		}else{
			map.put("placeName", "全部");
		}
		if(searchValue != null && !"".equals(searchValue)){
			try {
				searchValue = new String(searchValue.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			map.put("searchValue", searchValue);
			searchValue = "%"+searchValue+"%";
			condition.put("searchValue", searchValue);
		}else{
			map.put("searchValue", "请输入查询条件");
		}
		
		List<WifiSum> wifiSumList = this.wifiSumService.queryWifiSumByExport(condition);
		
		map.put("dataList", wifiSumList);
		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 = 4;
		map.put("dataSize", (wifiSumList.size() + 100));
		map.put("column", column);

		String excelTemplate = templateProcessor.processTemplate("excel/wifiSumList.ftl", map);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
