package com.ag.util;

import com.wb.common.Base;
import com.wb.interact.IDE;
import com.wb.util.WebUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Map.Entry;

/**
 * ??wb????
 */
//@Component
public class WbUtil {

	static String[] iconarr={"fa-home","fa-laptop","fa-book","fa-cogs","fa-bullhorn",
			"fa-envelope","fa-tasks","fa-bar-chart-o","fa-th-list","fa-map-marker","fa-file-text"};
	static String[] sa={"fa-home","fa-laptop","fa-book","fa-cogs","fa-bullhorn",
			"fa-envelope","fa-tasks","fa-bar-chart-o","fa-th-list","fa-map-marker","fa-file-text"};

	private static void getModuleList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
		getBasicsList(request, response, 1);
	}
	public static void getBasicsListsession(HttpServletRequest request,HttpServletResponse response){
		String menuid=request.getParameter("subsId");
		request.getSession().setAttribute("menuid",menuid);
	}

	/**
	 * ?????????????
	 * ?1????2??????3??????
	 */
	public static void getBasicsListA(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String menuid=request.getParameter("subsId");
		request.getSession().setAttribute("menuid",menuid);
		int type=1;
		String userid= (String) request.getSession().getAttribute("sys.user");
		String menuida="";
		if(request.getSession().getAttribute("menuid")!=null) {
			menuida = (String) request.getSession().getAttribute("menuid");
		}
		//String iconarr[]={"fa-laptop","fa-cogs","fa-bullhorn","fa-envelope","fa-bar-chart-o"};
		StringBuilder sb = new StringBuilder();
		String sqlRoleA="SELECT *\n" +
				"            FROM wb_menu\n" +
				"           WHERE menu_id IN\n" +
				"                    (SELECT DISTINCT parent_menu\n" +
				"                       FROM wb_menu wm, wb_role_resource wrr\n" +
				"                      WHERE     wm.menu_id = wrr.menu_id\n" +
				"                            AND wrr.role_id IN (SELECT role_id\n" +
				"                                                  FROM wb_user_role\n" +
				"                                                 WHERE user_id ='"+userid+"'\n" +
				"                            AND wm.parent_menu IN\n" +
				"                                   (SELECT menu_id\n" +
				"                                      FROM wb_menu\n" +
				"                                     WHERE     parent_menu ='"+menuida+"' \n" +
				"                                           AND menu_type = '0')）)\n" +
				"        ORDER BY order_index ";
		ResultSet roles = (ResultSet) com.wb.util.DbUtil.run(request,sqlRoleA);
		int i=0;
		while (roles.next()) {
			String icon="fa-book";
			if(iconarr[i]==null){
				icon="fa-book";
			}else{
				icon=iconarr[i];
			}
			sb.append("<li class=\"menu-list\">");
			sb.append("<a>");
			sb.append("<i class=\"fa "+icon+"\"></i>");
			sb.append("<span>"+roles.getString("MENU_NAME")+"</span>");
			sb.append("</a>");
			String sqlRoleA1 = "SELECT *\n" +
					"            FROM wb_menu\n" +
					"           WHERE     parent_menu ='"+roles.getString("MENU_ID")+"'\n" +
					"                 AND menu_id IN\n" +
					"                        (SELECT menu_id\n" +
					"                           FROM wb_user_role, wb_role_resource\n" +
					"                          WHERE     wb_user_role.role_id = wb_role_resource.role_id\n" +
					"                                AND user_id ='"+userid+"')\n" +
					"        ORDER BY order_index";
			ResultSet roles1 = (ResultSet) com.wb.util.DbUtil.run(request,sqlRoleA1);
			while (roles1.next()) {
				sb.append("<ul class=\"sub-menu-list\">");
				sb.append("<li>");
				sb.append("<a onclick=\"changeurl('" + roles1.getString("MENU_URL") + "','" + roles1.getString("MENU_NAME") + "','',false,'null' )\">"
						+ roles1.getString("MENU_NAME") + "</a>");
				sb.append("</li>");
				sb.append("</ul>");
			}
			sb.append("</li>");
			i++;
		}
		request.getSession().setAttribute("basicsLust", sb.toString());
		WebUtil.send(response, sb.toString());
	}

	/**
	 * ?????????????
	 * @param type ?????????1????2??????3??????
	 */
	private static void getBasicsList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
		//String iconarr[]={"fa-laptop","fa-cogs","fa-bullhorn","fa-envelope","fa-bar-chart-o"};
		//AgCommonService agCommonService = new AgCommonService();
		String username= (String) request.getSession().getAttribute("sys.user");
		String menuida="";
		if(request.getSession().getAttribute("sys.menuid")!=null) {
			menuida = (String) request.getSession().getAttribute("sys.menuid");
		}
		StringBuilder sb = new StringBuilder();
		String sqlRole = "SELECT *\n" +
				"            FROM wb_menu\n" +
				"           WHERE menu_id IN\n" +
				"                    (SELECT DISTINCT parent_menu\n" +
				"                       FROM wb_menu wm, wb_role_resource wrr\n" +
				"                      WHERE     wm.menu_id = wrr.menu_id\n" +
				"                            AND wrr.role_id = '"+username+"'\n" +
				"                            AND wm.parent_menu IN\n" +
				"                                   (SELECT menu_id\n" +
				"                                      FROM wb_menu\n" +
				"                                     WHERE parent_menu ='"+menuida+"' AND menu_type = '0'))\n" +
				"        ORDER BY order_index";
		ResultSet roles = (ResultSet) com.wb.util.DbUtil.run(request,sqlRole);
		int i=0;
		while(roles.next()){
			String icon="fa-book";
			if(iconarr[i]==null){
				icon="fa-book";
			}else{
				icon=iconarr[i];
			}
			sb.append("<li class=\"menu-list\">");
			sb.append("<a>");
			sb.append("<i class=\"fa "+icon+"\"></i>");
			sb.append("<span>"+roles.getString("MENU_NAME")+"</span>");
			sb.append("</a>");
			String sqlRole1 = " select wm.*,role_id from wb_menu wm,wb_role_resource wrr where wm.menu_id=wrr.menu_id\n" +
					"        and wm.parent_menu = '"+roles.getString("MENU_ID")+"' and wrr.role_id='"+username+"'\n" +
					"        order by order_index";
			ResultSet role1 = (ResultSet) com.wb.util.DbUtil.run(request,sqlRole1);
			while(role1.next()){
				sb.append("<ul class=\"sub-menu-list\">");
				sb.append("<li>");
				sb.append("<a onclick=\"changeurl('"+role1.getString("MENU_URL")+"','"+role1.getString("MENU_NAME")+"','',false,'null' )\">"
						+role1.getString("MENU_NAME")+"</a>");
				sb.append("</li>");
				sb.append("</ul>");
			}
			sb.append("</li>");
			i++;
		}
		request.setAttribute("basicsLust", sb.toString());
	}

	public static  String getStringBuffer1(JSONObject o,int i)
	{

		StringBuffer str=new StringBuffer("<li class=\"menu-list\"><a ><i class=\""+sa[i]+"\"></i> " +
				"<span>"+o.get("text")+"</span></a><ul class=\"sub-menu-list\">");
		return str.toString();

	}
	public static  String getStringBuffer2(JSONObject o)
	{
		Object pageLink=null;
		if(!o.isNull("pageLink"))
			pageLink=o.get("pageLink").toString().replace("'", "*");
		StringBuffer str=new StringBuffer("<li><a onclick=\"changeurl('"+o.get("path")+"','"+o.get("text")+"','"+o.get("iconCls")+"',"+o.get("inframe")+"    ,'"+pageLink+"' )\"> "+o.get("text")+"</a></li>");
		return str.toString();

	}


	private static String getModuleListNext(HttpServletRequest request,
											HttpServletResponse response, int type,String path2) throws Exception {
		String path = path2;
		String iconCls, fileName, pageLink, relPath, title;
		File file, base;
		int displayType = (type == 1 ? 1 : 3);
		String[] roles = com.wb.common.Session.getRoles(request);

		if (path == null)
			base = Base.modulePath;
		else {
			base = new File(Base.modulePath, path);
			if (!com.wb.util.FileUtil.isAncestor(Base.modulePath, base))
				com.wb.util.SysUtil.accessDenied();
		}
		path = path + "/";
		ArrayList<Entry<String, Integer>> fileNames = IDE.getSortedFile(base);
		JSONObject content = null, fileObject;
		JSONArray fileArray;
		boolean isFolder;
		StringBuffer str=new StringBuffer("");
		fileArray = new JSONArray();
		for (Entry<String, Integer> entry : fileNames) {
			fileName = entry.getKey();
			file = new File(base, fileName);
			// ??????????????????
			if (!file.exists())
				continue;
			if (!com.wb.common.XwlBuffer.canDisplay(file, roles, displayType))
				continue;
			isFolder = file.isDirectory();
			if (isFolder) {
				if (type != 1 && !hasLoginModule(file))
					continue;
				File configFile = new File(file, "folder.json");
				if (configFile.exists())
					content = com.wb.util.JsonUtil.readObject(configFile);
				else
					content = new JSONObject();
			} else {
				// ?????????????????
				if (type != 1 && !file.getName().endsWith(".xwl"))
					continue;
				content = com.wb.common.XwlBuffer.get(path + fileName, false);
				// ??????????????
				if (type != 1
						&& Boolean.FALSE.equals(content.opt("loginRequired")))
					continue;
			}
			fileObject = new JSONObject();
			title = content.optString("title");
			if (title.startsWith("Str."))
				title = com.wb.common.Str.format(request, title.substring(4));
			fileObject.put("text", com.wb.util.StringUtil.select(title, fileName));
			relPath = com.wb.util.FileUtil.getModulePath(file);
			fileObject.put("path", relPath);
			fileObject.put("fileName", fileName);
			fileObject.put("inframe", Boolean.TRUE.equals(content
					.opt("inframe")));
			if (isFolder) {
				if (!hasChildren(file))
					fileObject.put("children", new JSONArray());

				continue;
			} else {
				pageLink = (String) content.opt("pageLink");
				if (!com.wb.util.StringUtil.isEmpty(pageLink))
					fileObject.put("pageLink", pageLink);

				fileObject.put("leaf", true);
			}
			fileObject.put("cls", "wb_pointer");
			iconCls = content.optString("iconCls");
			//if (!StringUtil.isEmpty(iconCls))
			fileObject.put("iconCls", iconCls);
			if (type == 2 && !isFolder)
				fileObject.put("checked", false);
			str.append(getStringBuffer2(fileObject));


		}
		return str.toString();
	}
	/**
	 * ??????????????????
	 * @param path ?????
	 * @return true??????????false???????????
	 * @throws IOException
	 */
	private static boolean hasLoginModule(File path) throws IOException {
		File[] files = com.wb.util.FileUtil.listFiles(path);

		for (File file : files) {
			if (file.isDirectory()) {
				if (hasLoginModule(file))
					return true;
			} else {
				if (file.getName().endsWith(".xwl")) {
					JSONObject content = com.wb.common.XwlBuffer.get(com.wb.util.FileUtil
							.getModulePath(file), true);
					if (Boolean.TRUE.equals(content.opt("loginRequired")))
						return true;
				}
			}
		}
		return false;
	}

	/**
	 *  ??????
	 */
	public static void initHome(HttpServletRequest request,
								HttpServletResponse response) throws Exception {
		String desktopString = com.wb.common.Resource.getString(request, "desktop", null);
		int treeWidth;
		boolean treeCollapsed, treeHidden;

		if (desktopString == null)
			desktopString = com.wb.common.Resource.getString("sys.home.desktop", null);
		if (desktopString != null) {
			JSONObject desktop = new JSONObject(desktopString);
			treeWidth = desktop.optInt("treeWidth", 200);
			treeCollapsed = desktop.optBoolean("treeCollapsed", false);
			treeHidden = desktop.optBoolean("treeHidden", false);
			JSONArray pages = desktop.optJSONArray("pages");
			if (pages != null) {
				int i, j = pages.length(), activeIndex = desktop.optInt(
						"active", 0);
				String url, title, pageLink, params, rawUrl;
				JSONObject page, module, item;
				JSONArray tabItems = new JSONArray();
				for (i = 0; i < j; i++) {
					page = pages.optJSONObject(i);
					rawUrl = page.optString("url");
					url = com.wb.util.FileUtil.getModuleFile(rawUrl, true);
					module = com.wb.common.XwlBuffer.get(url, true);
					if (module == null) {
						if (i <= activeIndex)
							activeIndex--;
					} else {
						item = new JSONObject();
						item.put("url", rawUrl);
						title = (String) module.opt("title");
						if (title.startsWith("Str."))
							title = com.wb.common.Str.format(request, title.substring(4));
						item.put("title", com.wb.util.StringUtil.select(title, com.wb.util.FileUtil
								.getFilename(url)));
						item.put("iconCls", (String) module.opt("iconCls"));
						item.put("useIFrame", Boolean.TRUE.equals(module
								.opt("inframe")));
						params = page.optString("params");
						if (!com.wb.util.StringUtil.isEmpty(params))
							item.put("params", new JSONObject(params));
						pageLink = (String) module.opt("pageLink");
						if (!com.wb.util.StringUtil.isEmpty(pageLink))
							com.wb.util.JsonUtil.apply(item, new JSONObject(pageLink));
						tabItems.put(item);
					}
				}
				request.setAttribute("activeIndex", activeIndex);
				request.setAttribute("tabItems", com.wb.util.StringUtil.text(tabItems
						.toString()));
			}
			JSONArray portlets = desktop.optJSONArray("portlets");
			if (portlets != null) {
				int i, j = portlets.length(), k, l;
				String url, title, pageLink;
				JSONArray cols;
				JSONObject portlet, module;
				for (i = 0; i < j; i++) {
					cols = portlets.optJSONArray(i);
					l = cols.length();
					for (k = 0; k < l; k++) {
						portlet = cols.optJSONObject(k);
						url = com.wb.util.FileUtil.getModuleFile(portlet.optString("url"),
								true);
						module = com.wb.common.XwlBuffer.get(url, true);
						if (module == null) {
							cols.remove(k);
							k--;
							l--;
							continue;
						}
						title = (String) module.opt("title");
						if (title.startsWith("Str."))
							title = com.wb.common.Str.format(request, title.substring(4));
						portlet.put("title", com.wb.util.StringUtil.select(title, com.wb.util.FileUtil
								.getFilename(url)));
						portlet.put("iconCls", (String) module.opt("iconCls"));
						portlet.put("useIFrame", Boolean.TRUE.equals(module
								.opt("inframe")));
						pageLink = (String) module.opt("pageLink");
						if (!com.wb.util.StringUtil.isEmpty(pageLink))
							com.wb.util.JsonUtil.apply(portlet, new JSONObject(pageLink));
					}
				}
				request.setAttribute("portlets", com.wb.util.StringUtil.text(portlets
						.toString()));
			}
		} else {
			treeWidth = 200;
			treeCollapsed = false;
			treeHidden = false;
		}
		request.setAttribute("treeWidth", treeWidth);
		request.setAttribute("treeCollapsed", treeCollapsed);
		request.setAttribute("treeHidden", treeHidden);
		request.setAttribute("hideSetDefaultDesktop", !com.wb.common.XwlBuffer.canAccess(
				request, "m?xwl=sys/portal/home/save-default-desktop"));
		request.setAttribute("hideSetAllDesktop", !com.wb.common.XwlBuffer.canAccess(request,
				"m?xwl=sys/portal/home/save-all-desktop"));
	}

	/**
	 *  ???????????????
	 */
	public static void getAppList(HttpServletRequest request,HttpServletResponse response) throws Exception {
		getModuleList(request, response, 1);
	}

	/**
	 *  ?????????
	 */
	public static void saveDesktop(HttpServletRequest request,
								   HttpServletResponse response) throws Exception {
		doSaveDesktop(request, 1);
	}

	/**
	 *  ????????????
	 */
	public static void saveAsDefaultDesktop(HttpServletRequest request,
											HttpServletResponse response) throws Exception {
		doSaveDesktop(request, 2);
	}

	/**
	 *  ??????????????
	 */
	public static void saveAsAllDesktop(HttpServletRequest request,
										HttpServletResponse response) throws Exception {
		doSaveDesktop(request, 3);
	}

	/**
	 * ???????
	 * @param request ?????
	 * @param type ?????1???????2?????3????
	 */
	private static void doSaveDesktop(HttpServletRequest request, int type)
			throws Exception {
		JSONObject desktop = new JSONObject();
		desktop.put("treeWidth", Integer.parseInt(request
				.getParameter("treeWidth")));
		desktop.put("treeCollapsed", Boolean.parseBoolean(request
				.getParameter("treeCollapsed")));
		desktop.put("treeHidden", Boolean.parseBoolean(request
				.getParameter("treeHidden")));
		desktop.put("pages", new JSONArray(request.getParameter("pages")));
		desktop
				.put("portlets",
						new JSONArray(request.getParameter("portlets")));
		desktop.put("active", Integer.parseInt(request.getParameter("active")));
		if (type == 1) {
			com.wb.common.Resource.set(request, "desktop", desktop.toString());
		} else {
			if (type == 3)
				com.wb.util.DbUtil
						.run(request,
								"delete from WB_RESOURCE where RES_ID like 'desktop@%'");
			com.wb.common.Resource.set("sys.home.desktop", desktop.toString());
		}
	}

	/**
	 *  ???????????????
	 */
	public static void getPermList(HttpServletRequest request,
								   HttpServletResponse response) throws Exception {
		getModuleList(request, response, 2);
	}

	/**
	 *  ???????????????????
	 */
	public static void getUserPermList(HttpServletRequest request,
									   HttpServletResponse response) throws Exception {
		getModuleList(request, response, 3);
	}

	/**
	 *  ???????????
	 */
	public static void setTheme(HttpServletRequest request,
								HttpServletResponse response) throws Exception {
		String theme = request.getParameter("theme");

		com.wb.common.Value.set(request, "theme", theme);
		WebUtil.setSessionValue(request, "sys.theme", theme);
	}

	/**
	 *  ???????????
	 */
	public static void setTouchTheme(HttpServletRequest request,
									 HttpServletResponse response) throws Exception {
		String theme = request.getParameter("theme");

		com.wb.common.Value.set(request, "touchTheme", theme);
		WebUtil.setSessionValue(request, "sys.touchTheme", theme);
	}

	/**
	 * ???????????????
	 */
	private static void searchModule(HttpServletRequest request,
									 HttpServletResponse response, boolean isPerm) throws Exception {
		JSONArray array = new JSONArray();
		String query = request.getParameter("query").toLowerCase();

		if (query.isEmpty())
			query = ".xwl";
		doSearchFile(request, Base.modulePath, query.toLowerCase(), "", "",
				array, isPerm);
		WebUtil.send(response, new JSONObject().put("rows", array));
	}

	/**
	 * ?????????????????
	 */
	public static void searchAppModule(HttpServletRequest request,
									   HttpServletResponse response) throws Exception {
		searchModule(request, response, false);
	}

	/**
	 * ?????????????????
	 */
	public static void searchPermModule(HttpServletRequest request,
										HttpServletResponse response) throws Exception {
		searchModule(request, response, true);
	}

	/**
	 *
	 * ???????????????????????
	 * @param request ?????
	 * @param folder ???
	 * @param searchName ????????????????????????????
	 * @param parentText ?????????
	 * @param array ?????????
	 * @param isPerm ???????????
	 * @return ?????????????????100?????true?????false?
	 * @throws Exception ??????????
	 */
	private static boolean doSearchFile(HttpServletRequest request,
										File folder, String searchName, String parentText,
										String parentFile, JSONArray array, boolean isPerm)
			throws Exception {
		File files[] = com.wb.util.FileUtil.listFiles(folder);
		String path, title;

		for (File file : files) {
			if (file.isDirectory()) {
				File indexFile = new File(file, "folder.json");
				String folderTitle, folderFile;
				folderFile = file.getName();
				if (indexFile.exists()) {
					JSONObject jo = com.wb.util.JsonUtil.readObject(indexFile);
					if (!isPerm && Boolean.TRUE.equals(jo.opt("hidden")))
						continue;
					folderTitle = jo.optString("title");
					if (folderTitle.isEmpty())
						folderTitle = folderFile;
				} else
					folderTitle = folderFile;
				if (folderTitle.startsWith("Str."))
					folderTitle = com.wb.common.Str.format(request, folderTitle.substring(4));
				// ???????????????
				if (!isPerm) {
					if (folderTitle.toLowerCase().indexOf(searchName) != -1) {
						JSONObject jo = new JSONObject();
						jo.put("path", parentText);
						jo.put("title", folderTitle);
						jo.put("file", folderFile);
						jo.put("parentFile", parentFile);
						array.put(jo);
						if (array.length() > 99)
							return true;
					}
				}
				if (doSearchFile(request, file, searchName, com.wb.util.StringUtil.concat(
						parentText, "/", folderTitle), com.wb.util.StringUtil.concat(
						parentFile, "/", folderFile), array, isPerm))
					return true;
			} else {
				path = com.wb.util.FileUtil.getModulePath(file);
				if (path.endsWith(".xwl")) {
					JSONObject moduleData = com.wb.common.XwlBuffer.get(path, false);
					if (!isPerm
							&& Boolean.TRUE.equals(moduleData.opt("hidden")))
						continue;
					if (isPerm
							&& Boolean.FALSE.equals(moduleData
							.opt("loginRequired")))
						continue;
					title = moduleData.optString("title");
					if (title.isEmpty())
						title = path.substring(path.lastIndexOf('/') + 1);
					if (title.startsWith("Str."))
						title = com.wb.common.Str.format(request, title.substring(4));
					if (title.toLowerCase().indexOf(searchName) != -1) {
						JSONObject jo = new JSONObject();
						jo.put("path", parentText);
						jo.put("title", title);
						jo.put("file", file.getName());
						jo.put("parentFile", parentFile);
						array.put(jo);
						if (array.length() > 99)
							return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * ???????????????
	 *
	 * @param dir ??
	 * @return true?????false?????
	 */
	private static boolean hasChildren(File dir) {
		File files[];
		files = com.wb.util.FileUtil.listFiles(dir);
		if (files == null)
			return false;
		for (File file : files) {
			if (file.isDirectory()) {
				return true;
			} else if (!file.getName().equals("folder.json"))
				return true;
		}
		return false;
	}


	/**
	 * ????????????????Viewport???????????null?
	 * @param
	 * @return Viewport???null?
	 */
	private static JSONObject getViewport(JSONObject rootNode) throws Exception {
		int i, j;
		JSONObject jo;
		JSONArray items;
		JSONObject module = (JSONObject) ((JSONArray) rootNode.opt("children"))
				.opt(0);

		items = (JSONArray) module.opt("children");
		if (items == null)
			return null;
		j = items.length();
		for (i = 0; i < j; i++) {
			jo = ((JSONObject) items.opt(i));
			if ("tviewport".equals(jo.opt("type")))
				return jo;
		}
		return null;
	}
}
//	private static void getModuleList(HttpServletRequest request,
//									  HttpServletResponse response, int type) throws Exception {
//		/**
//		 String path = request.getParameter("path");
//		 String iconCls, fileName, pageLink, relPath, title;
//		 File file, base;
//		 int displayType = (type == 1 ? 1 : 3);
//		 String[] roles = Session.getRoles(request);
//
//		 if (path == null)
//		 base = Base.modulePath;
//		 else {
//		 base = new File(Base.modulePath, path);
//		 if (!FileUtil.isAncestor(Base.modulePath, base))
//		 SysUtil.accessDenied();
//		 }
//		 path = path + "/";
//		 ArrayList<Entry<String, Integer>> fileNames = IDE.getSortedFile(base);
//		 JSONObject content = null, fileObject;
//		 JSONArray fileArray;
//		 boolean isFolder;
//		 StringBuffer str = new StringBuffer("");
//		 fileArray = new JSONArray();
//		 int i = 0;
//		 for (Entry<String, Integer> entry : fileNames) {
//		 fileName = entry.getKey();
//		 file = new File(base, fileName);
//		 // 文件列表取自配置文件，如果不存在返回
//		 if (!file.exists())
//		 continue;
//		 if (!XwlBuffer.canDisplay(file, roles, displayType))
//		 continue;
//		 isFolder = file.isDirectory();
//		 if (isFolder) {
//		 if (type != 1 && !hasLoginModule(file))
//		 continue;
//		 File configFile = new File(file, "folder.json");
//		 if (configFile.exists())
//		 content = JsonUtil.readObject(configFile);
//		 else
//		 content = new JSONObject();
//		 } else {
//		 // 如果设置模块权限且非模块文件则返回
//		 if (type != 1 && !file.getName().endsWith(".xwl"))
//		 continue;
//		 content = XwlBuffer.get(path + fileName, false);
//		 // 无需登录的模块不允许设置权限
//		 if (type != 1
//		 && Boolean.FALSE.equals(content.opt("loginRequired")))
//		 continue;
//		 }
//		 fileObject = new JSONObject();
//		 title = content.optString("title");
//		 if (title.startsWith("Str."))
//		 title = Str.format(request, title.substring(4));
//		 fileObject.put("text", StringUtil.select(title, fileName));
//		 relPath = FileUtil.getModulePath(file);
//		 fileObject.put("path", relPath);
//		 fileObject.put("fileName", fileName);
//		 fileObject.put("inframe", Boolean.TRUE.equals(content
//		 .opt("inframe")));
//		 if (isFolder) {
//		 if (!hasChildren(file))
//		 fileObject.put("children", new JSONArray());
//		 } else {
//		 pageLink = (String) content.opt("pageLink");
//		 if (!StringUtil.isEmpty(pageLink))
//		 fileObject.put("pageLink", pageLink);
//		 fileObject.put("leaf", true);
//		 }
//		 fileObject.put("cls", "wb_pointer");
//
//		 iconCls = content.optString("iconCls");
//		 if (!StringUtil.isEmpty(iconCls))
//		 fileObject.put("iconCls", iconCls);
//		 if (type == 2 && !isFolder)
//		 fileObject.put("checked", false);
//		 fileArray.put(fileObject);
//		 if (str.length() > 0)
//		 str.append("  </ul></li>");
//		 str.append(getStringBuffer1(fileObject, i));
//		 i++;
//		 str.append(getModuleListNext(request, response, type, fileObject.get("fileName").toString()));
//		 }
//		 request.setAttribute("ModuleLust", str.toString());
//		 */
//		String username= (String) request.getSession().getAttribute("sys.user");
//		try {
//			Connection conn = null;
//			Statement st = null;
//			ResultSet rs = null;
//			StringBuilder sb = new StringBuilder();
//			//sb.append("<li class=\"active\"><a href=\"\"><i class=\"fa fa-home\"></i> <span>主页</span></a></li>");
//			try {
//				conn = DbUtil.getConnection();
//				st = conn.createStatement();
//				rs = st.executeQuery("select * from wb_menu \n" +
//						"where menu_id in(\n" +
//						"                 select distinct parent_menu from wb_menu wm,wb_role_resource wrr \n" +
//						"                 where wm.menu_id=wrr.menu_id and wrr.role_id='"+username+"'\n" +
//						"                 and wm.parent_menu in (\n" +
//						"                                        select menu_id from wb_menu where parent_menu='-1'\n" +
//						"                                        )\n" +
//						"                 )\n" +
//						"  order by order_index");
//				while (rs.next()) {
//					sb.append("<li class=\"menu-list\">");
//					sb.append("<a style=\"margin-top:50px;\">");
//					sb.append("<i class=\"fa fa-book\"></i>");
//					sb.append("<span>"+rs.getString("MENU_NAME")+"</span>");
//					sb.append("</a>");
//					Connection connection = null;
//					Statement  statement = null;
//					ResultSet  resultSet = null;
//					try{
//						connection=DbUtil1.getConnection();
//						statement=connection.createStatement();
//						resultSet = statement.executeQuery("select wm.*,role_id from wb_menu wm,wb_role_resource wrr where wm.menu_id=wrr.menu_id "
//								+ "and wm.parent_menu='"+rs.getString("MENU_ID")+ "' and wrr.role_id='"+username+"'");
//						while(resultSet.next()){
//							sb.append("<ul class=\"sub-menu-list\">");
//							sb.append("<li>");
//							sb.append("<a onclick=\"changeurl('"+resultSet.getString("MENU_URL")+"','"+resultSet.getString("MENU_NAME")+"','',false,'null' )\">"
//									+resultSet.getString("MENU_NAME")+"</a>");
//							sb.append("</li>");
//							sb.append("</ul>");
//						}
//					}finally {
//						DbUtil1.close(resultSet);
//						DbUtil1.close(statement);
//						DbUtil1.close(connection);
//					}
//					sb.append("</li>");
//				}
//				request.setAttribute("ModuleLust", sb.toString());
//			} finally {
//				DbUtil.close(rs);
//				DbUtil.close(st);
//				DbUtil.close(conn);
//			}
//		} catch (Throwable e) {
//			throw new RuntimeException(e);
//		}
//
//
//		getSubsList(request, response, 1);
//
////		<li class="menu-list">
////		<a>
////		<i class="fa fa-cogs"></i>
////		<span>学习</span>
////		</a>
////		<ul class="sub-menu-list">
////		<li>
////		<a onclick="changeurl('Teacher/teacher.xwl','老师表','',false    ,'null' )"> 老师表</a>
////		</li>
////		<li>
////		<a onclick="changeurl('Teacher/student.xwl','学生表','',false    ,'null' )"> 学生表</a>
////		</li>
////		</ul>
////		</li>
////		<li class="menu-list">
////		<a>
////		<i class="fa fa-bullhorn"></i>
////		<span>货代业务管理</span>
////		</a>
////		<ul class="sub-menu-list">
////		<li>
////		<a onclick="changeurl('cargoBusinessManage/productSpu.xwl','航线维护','',false,'null' )">航线维护</a>
////		</li>
////		</ul>
////		</li>
//
//
//		//WebUtil.send(response, new JSONObject().put("children", fileArray));
//	}

/**
 * 修改用户中心
 * @param request
 * @param response
 * @param type
 * @throws Exception
 */
//	private static void getUserList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
//		String username= (String) request.getSession().getAttribute("sys.user");
//		try {
//			Connection conn = null;
//			Statement st = null;
//			ResultSet rs = null;
//			StringBuilder sb = new StringBuilder();
//		//	sb.append("<li class=\"active\"><a href=\"\"><i class=\"fa fa-home\"></i> <span>主页</span></a></li>");
//			try {
//				conn = DbUtil.getConnection();
//				st = conn.createStatement();
//				rs = st.executeQuery("select * from wb_menu \n" +
//						"where menu_id in(\n" +
//						"                 select distinct parent_menu from wb_menu wm,wb_role_resource wrr \n" +
//						"                 where wm.menu_id=wrr.menu_id  and wrr.role_id='"+username+"'\n" +
//						"                 and  wm.parent_menu in (\n" +
//						"                      select menu_id from wb_menu  where parent_menu in(\n" +
//						"                            select menu_id from wb_menu where parent_menu='-1' and menu_type='2' and menu_name='用户中心')\n" +
//						"                    )   \n" +
//						"                )          \n" +
//						"order by order_index");
//				while (rs.next()) {
//					sb.append("<li class=\"menu-list\">");
//					sb.append("<a>");
//					sb.append("<i class=\"fa fa-book\"></i>");
//					sb.append("<span>"+rs.getString("MENU_NAME")+"</span>");
//					sb.append("</a>");
//					Connection connection = null;
//					Statement  statement = null;
//					ResultSet  resultSet = null;
//					try{
//						connection=DbUtil1.getConnection();
//						statement=connection.createStatement();
//						resultSet = statement.executeQuery("select wm.*,role_id from wb_menu wm,wb_role_resource wrr where wm.menu_id=wrr.menu_id "
//								+ "and wm.parent_menu='"+rs.getString("MENU_ID")+ "' and wrr.role_id='"+username+"'");
//						while(resultSet.next()){
//							sb.append("<ul class=\"sub-menu-list\">");
//							sb.append("<li>");
//							sb.append("<a onclick=\"changeurl('"+resultSet.getString("MENU_URL")+"','"+resultSet.getString("MENU_NAME")+"','',false,'null' )\">"
//									+resultSet.getString("MENU_NAME")+"</a>");
//							sb.append("</li>");
//							sb.append("</ul>");
//						}
//					}finally {
//						DbUtil1.close(resultSet);
//						DbUtil1.close(statement);
//						DbUtil1.close(connection);
//					}
//					sb.append("</li>");
//				}
//				request.setAttribute("userLust", sb.toString());
//			} finally {
//				DbUtil.close(rs);
//				DbUtil.close(st);
//				DbUtil.close(conn);
//			}
//		} catch (Throwable e) {
//			throw new RuntimeException(e);
//		}
//
//	}
/**
 //	 * 获取模块列表树的节点列表。
 //	 * @param type 数据请求来源类型，1：主页，2：权限模块，3：用户模块。
 //	 */
//	private static void getBasicsList(HttpServletRequest request,HttpServletResponse response, int type) throws Exception {
//		String username= (String) request.getSession().getAttribute("sys.user");
//		try {
//			Connection conn = null;
//			Statement st = null;
//			ResultSet rs = null;
//			StringBuilder sb = new StringBuilder();
//			//sb.append("<li class=\"active\"><a href=\"\"><i class=\"fa fa-home\"></i> <span>主页</span></a></li>");
//			try {
//				conn = DbUtil.getConnection();
//				st = conn.createStatement();
//				rs = st.executeQuery("select * from wb_menu \n" +
//						"where menu_id in(\n" +
//						"                 select distinct parent_menu from wb_menu wm,wb_role_resource wrr \n" +
//						"                 where wm.menu_id=wrr.menu_id and wrr.role_id='"+username+"'\n" +
//						"                 and wm.parent_menu in (\n" +
//						"                                        select menu_id from wb_menu where parent_menu='-1' and menu_type='0' \n" +
//						"                                        )\n" +
//						"                 )\n" +
//						"  order by order_index");
//				while (rs.next()) {
//					sb.append("<li class=\"menu-list\">");
//					sb.append("<a>");
//					sb.append("<i class=\"fa fa-book\"></i>");
//					sb.append("<span>"+rs.getString("MENU_NAME")+"</span>");
//					sb.append("</a>");
//					Connection connection = null;
//					Statement  statement = null;
//					ResultSet  resultSet = null;
//					try{
//						connection=DbUtil1.getConnection();
//						statement=connection.createStatement();
//						resultSet = statement.executeQuery("select wm.*,role_id from wb_menu wm,wb_role_resource wrr where wm.menu_id=wrr.menu_id "
//								+ "and wm.parent_menu='"+rs.getString("MENU_ID")+ "' and wrr.role_id='"+username+"'");
//						while(resultSet.next()){
//							sb.append("<ul class=\"sub-menu-list\">");
//							sb.append("<li>");
//							sb.append("<a onclick=\"changeurl('"+resultSet.getString("MENU_URL")+"','"+resultSet.getString("MENU_NAME")+"','',false,'null' )\">"
//									+resultSet.getString("MENU_NAME")+"</a>");
//							sb.append("</li>");
//							sb.append("</ul>");
//						}
//					}finally {
//						DbUtil1.close(resultSet);
//						DbUtil1.close(statement);
//						DbUtil1.close(connection);
//					}
//					sb.append("</li>");
//				}
//				request.setAttribute("basicsLust", sb.toString());
//			} finally {
//				DbUtil.close(rs);
//				DbUtil.close(st);
//				DbUtil.close(conn);
//			}
//		} catch (Throwable e) {
//			throw new RuntimeException(e);
//		}
//	}