package com.xt.hb.data.system.ctl;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import com.alibaba.fastjson.JSONObject;
import com.xt.hb.data.system.svc.SystemService;
import com.xt.hb.data.util.IdGenerator;

@Controller
public class SystemCtl implements ServletContextAware {
	@Autowired
	private SystemService systemService;
	@Autowired
	private IdGenerator idGenerator;
	@Autowired
	private EhCacheCacheManager cacheManager;

	@RequestMapping("services")
	@ResponseBody
	public JSONObject services() {
		JSONObject jo = new JSONObject();
		// 港口港区经营人树
		jo.put("gkgqjryTree", "/aqgis/gkgqjryTree");
		// 摄像头树
		jo.put("cameraTree", "/aqgis/cameraTree");
		// 港区
		jo.put("gq", "/aqgis/gq");
		// 码头
		jo.put("mt", "/aqgis/mt");
		// 泊位
		jo.put("bw", "/aqgis/bw");
		// 经营人
		jo.put("jyr", "/aqgis/jyr");
		// 取水口
		jo.put("qsk", "/aqgis/qsk");
		// 危货企业查询
		jo.put("whzysq", "/aqgis/whzysq");
		// 船舶预警
		jo.put("cbyjArea", "/cbyjArea");
		// 泊位作业记录分页
		jo.put("bwPage", "/aqgis/whzysq?bwGisid=");
		// 船名
		jo.put("shipName", "/shipName");
		// token验证
		jo.put("tokenValid", "/system/tokenValid");
		return jo;
	}

	@RequestMapping("system/token")
	@ResponseBody
	public String token(String u) {
		String ticket = idGenerator.generateStringId();
		Cache cache = cacheManager.getCache("tokenCache");
		cache.put(ticket, true);
		return ticket;
	}

	@RequestMapping("system/tokenValid/{id}")
	@ResponseBody
	public boolean tokenValid(@PathVariable String id) {
		Cache cache = cacheManager.getCache("tokenCache");
		ValueWrapper value = cache.get(id);
		if (null != value) {
			Boolean valid = (Boolean) value.get();
			if (valid) {
				cache.put(id, false);
				return true;
			}
		}
		return false;
	}

	/**
	 * 重新加载系统参数
	 * 
	 * @return
	 */
	@RequestMapping("system/reloadParam")
	@ResponseBody
	public String reloadParam() {
		return systemService.reloadParam();
	}

	ServletContext servletContext = null;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
