package com.iamberry.wechat.handles.admin;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

import com.iamberry.wechat.tools.WeixinUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.loadResultUtil;
import com.iamberry.wechat.utils.StaticCacheMemory;
import com.iamberry.zk.HostInfo;
import com.iamberry.zk.ZookeeperQueue;

/**
 * @author 何秀刚
 * Class Description: 系统设置
 * Create Date:2016年4月25日
 * Update Date:2016年4月25日
 */
@Controller
@RequestMapping("/admin/system")
public class SystemHandler {


	@RequestMapping("/set")
	public void set(HttpServletResponse response) {
		try {
			response.getWriter().write("清空配置成功!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/reSetWechatConfig")
	public void setWechatConfig(HttpServletResponse response) {
		StaticCacheMemory.setAccessToken(null);
		try {
			response.getWriter().write("清空微信配置成功!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/reload")
	public void reload(HttpServletResponse response) {
		try {
			loadResultUtil.load();
			response.getWriter().write("重新读取资源文件成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/addMessageInfo")
	public ModelAndView addUI() {
		ModelAndView mv = new ModelAndView("admin/system/addUI");
		return mv; 
	}
	
	@RequestMapping(value = "/loadMessageInfo", method = RequestMethod.POST)
	public void loadMessageInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// id
		final String tempMessageId = request.getParameter("tempMessageId");
		
		// 消息，分隔符位#s
		String tempMessageInfo = request.getParameter("tempMessageInfo");
		// url 
		final String tempMessageURL = request.getParameter("tempMessageURL");
		// 用户
		String tempMessageUsers = request.getParameter("tempMessageUsers");
		final String[] users = StringUtils.split(tempMessageUsers, "\r\n");
		// format
		String tempMessageFormat = request.getParameter("tempMessageFormat");
		// 发送
		final String message = String.format(tempMessageFormat, StringUtils.split(tempMessageInfo, "#s"));
		if (users.length <= 100) {
			for (String string : users) {
				try {WeixinUtil.sendTemplateMessage(NameUtils.appId, NameUtils.appSecret, string, tempMessageId, message, tempMessageURL);} catch (Exception e) {}
			}
			response.getWriter().print("发送成功!");
		} else {
			int lengthTemp = users.length / 100;
			int count = users.length % 100 == 0 ? lengthTemp : lengthTemp + 1;
			ExecutorService threadPool = Executors.newSingleThreadExecutor();
			for (int i = 1; i < count; i++) {
				final int taskID = i;
				threadPool.execute(new Runnable() {
					public void run() {
						int startNum = taskID * 100;	// 开始
						int stopNum = startNum + 100;	// 结束
						for (;startNum <= stopNum; startNum++) {
							System.out.println("count:" + startNum);
							try {WeixinUtil.sendTemplateMessage(NameUtils.appId, NameUtils.appSecret, users[startNum], tempMessageId, message, tempMessageURL);} catch (Exception e) {}
						}
					}
				});
			}
			threadPool.shutdown();// 任务执行完毕，关闭线程池
			response.getWriter().print("发送成功!");
		}
	}
	
	/**
	 * 系统监听
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	@RequestMapping("/monitor")
	public ModelAndView monitor(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, IOException {
		ModelAndView mv = new ModelAndView("admin/system/listUI");
		
//		mv.addObject("nowDate", DateTimeUtil.format(new Date()));
//		
//		Map<String, Integer> accessMap = new HashMap<String, Integer>();
//		for (Map<String, Integer> map : StaticCacheMemory.lists) {
//			for (Entry<String, Integer> entry : map.entrySet()) {
//				String key = entry.getKey();
//				if (accessMap.containsKey(key)) {
//					int value = accessMap.get(key) + entry.getValue();
//					accessMap.put(key, value);
//				} else {
//					accessMap.put(key, 1);
//				}
//			}
//		}
//
//		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
//		DataSourceManager dataSourceManager = context.getBean(DataSourceManager.class);
//		// 准备数据
//		mv.addObject("list", accessMap);
//		mv.addObject("dataBaseCount", dataSourceManager.getMaxPoolSize());
		
		return mv;
	}
	
	
	@RequestMapping("/host_list")
	public ModelAndView hostListUI() {
		ModelAndView mv = new ModelAndView("admin/system/host_list");
		List<String> hosts =  ZookeeperQueue.listHostInfo();
		if (hosts == null || hosts.size() <= 0) {
			mv.addObject("list", null);
			return mv;
		}
		List<HostInfo> hostInfos = new ArrayList<HostInfo>();
		for (String string : hosts) {
			HostInfo hostInfo = ZookeeperQueue.readNodeData(string);
			hostInfo.setPath(string);
			hostInfos.add(hostInfo);
		}
		mv.addObject("list", hostInfos);
		return mv;
	}
	
	@RequestMapping("/cancal_service/{path}")
	@ResponseBody
	public ResponseJson cancelService(@PathVariable("path") String path) {
		ResponseJson json = new ResponseJson();
		HostInfo hostInfo = ZookeeperQueue.readNodeData(path);
		if (hostInfo == null || hostInfo.getState() == 1) {
			json.setReturnCode(200);
			json.setResultMsg("关闭中!");
			return json;
		}
		hostInfo.setState(1);
		ZookeeperQueue.writeNodeData(path, hostInfo);
		json.setReturnCode(200);
		return json;
	}
}
