/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:project
 * File Name:OrgController.java
 * Package Name:org.ccpit.base.orgManage
 * Date:2015年9月21日上午8:37:32
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 *
 */

package org.ccpit.base.orgManage;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.user.User;
import org.ccpit.base.user.UserController;
import org.ccpit.base.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName:OrgController <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2015年9月21日 上午8:37:32 <br/>
 * 
 * @author dingwei
 * @version
 * @since JDK 1.6
 * @see
 */
@Controller
@RequestMapping("/admin/org")
public class OrgController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private OrgService orgService;
	@Autowired
	private UserService userService;

	/*
	 * 进入机构管理列表界面
	 */
	@RequestMapping("/goinOrgListPage")
	public Object goinOrgListPage() {
		ModelAndView mv = new ModelAndView("admin/orgManage/orgListPage");
		return mv;
	}

	/**
	 * 
	 * getAllOrgs:(默认查询出所有的机构信息). <br/>
	 * TODO(这里描述这个方法适用条件 – 可选).<br/>
	 * TODO(这里描述这个方法的执行流程 – 可选).<br/>
	 * TODO(这里描述这个方法的使用方法 – 可选).<br/>
	 * TODO(这里描述这个方法的注意事项 – 可选).<br/>
	 *
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/getAllOrgs")
	@ResponseBody
	public Object getAllOrgs(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		PageRequest pageRequest = this.getPage(request);
		Page<OrgInfo> users = orgService.queryPage(pageRequest);
		map.put("total", users.getTotal());
		map.put("rows", users.getRows());
		return map;
	}

	@RequestMapping({ "/getLeftTree" })
	@ResponseBody
	public Object getLeftTree(HttpServletRequest request) {
		String isroot = request.getParameter("isroot");
		// UserBo userBo = (UserBo)
		User user = (User) request.getSession().getAttribute("user_in_session");
		List result = new ArrayList();
		List<OrgInfo> orglist = null;
		// if (("true".equals(isroot)) ||
		// ("superadmin".equals(userBo.getLoginName()))){
		// listBo = this.unitService.findUnitByHierarchy("01");
		// }
		// else {
		// }
		orglist = this.orgService.getOrgInfoList();
		List listBo1 = null;
		if (null != orglist) {
			for (OrgInfo orgInfo : orglist) {
				Map item = new HashMap();
				if (1 == orgInfo.getId()) {
					item.put("id", orgInfo.getId());
					item.put("text", orgInfo.getName());
					item.put("children", getChildren(orgInfo.getId(), orglist));
					result.add(item);
				}
			}
		}
		return result;
	}

	public List<Map<String, Object>> getChildren(long id, List<OrgInfo> orgList) {
		List items = new ArrayList();
		for (OrgInfo boinfo : orgList) {
			if (boinfo.getParentId() == id) {
				OrgInfo gg = (OrgInfo) boinfo;
				Map item = new HashMap();
				item.put("id", gg.getId());
				item.put("text", gg.getName());
				item.put("children", getChildren(gg.getId(), orgList));
				items.add(item);
			}
		}
		return items;
	}

	@RequestMapping("/addOrUpdateOrgInfo")
	public void addOrUpdateOrgInfo(HttpServletRequest request,HttpServletResponse response, OrgInfo orgInfo) {
		String result = "";
		User user = (User) request.getSession().getAttribute("user_in_session");
		String orgId = request.getParameter("orgId");
		String orgName = request.getParameter("orgName");
		String operate = request.getParameter("operate");
		boolean flag = false;
		if (null != orgName) {
			try {
				orgName = java.net.URLDecoder.decode(orgName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if (null != orgId) {
			if ("add".equals(operate)) {
				orgInfo.setParentId(Long.valueOf(orgId));
				orgInfo.setParentName(orgName);
				orgInfo.setCreateDate(new Date());
				orgInfo.setCreateUser(user.getUsername());
				flag = orgService.addOrg(orgInfo);
			}else if("edit".equals(operate)) {
				OrgInfo org = orgService.getOrgById(Long.valueOf(orgId));
				if(null != orgInfo.getName()){
					org.setName(orgInfo.getName());
				}if(null != orgInfo.getOrderNumber()){
					org.setOrderNumber(orgInfo.getOrderNumber());
				}if(null != orgInfo.getDescription()){
					org.setDescription(orgInfo.getDescription());
				}if(null != orgInfo.getParentName()){
					org.setParentName(orgInfo.getParentName());
				}
				flag = orgService.updateOrg(org);
			}
		} 
		if(flag){
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存成功！\" }";
		}else {
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存失败！\" }";
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * orgAddUsers:(机构关联用户). <br/>
	 * TODO(这里描述这个方法适用条件 – 可选).<br/>
	 * TODO(这里描述这个方法的执行流程 – 可选).<br/>
	 * TODO(这里描述这个方法的使用方法 – 可选).<br/>
	 * TODO(这里描述这个方法的注意事项 – 可选).<br/>
	 *
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping({ "/orgAddUsers" })
	@ResponseBody
	public Object orgAddUsers(HttpServletRequest request){
		Map map = new HashMap();
		String orgId = request.getParameter("orgId");
		String userId = request.getParameter("userId");
		boolean flag = false;
		if(null != orgId){
			OrgInfo org = orgService.getOrgById(Long.valueOf(orgId));
			if(null != userId){
				User user = userService.getUser(Long.valueOf(userId));
				org.getUsers().add(user);
			}
			flag = orgService.updateOrg(org);
		}
		return map.put("flag", flag);
	}
	
	@RequestMapping({ "/getOrgUserByOrdId" })
	@ResponseBody
	public Object getOrgUserByOrdId(HttpServletRequest request){
		Map map = new HashMap();
		String orgId = request.getParameter("orgId");
		Set<User> setUser = new HashSet<User>();
		PageRequest pageRequest = this.getPage(request);
		Page<User> users = new Page<User>(pageRequest);
		boolean flag = false;
		if(null != orgId){
			OrgInfo org = orgService.getOrgById(Long.valueOf(orgId));
			setUser = org.getUsers();
			map.put("total", setUser.size());
			map.put("rows", setUser);
		}
		return map;
	}
	
	@RequestMapping({ "/delOrgUserByOrdId" })
	@ResponseBody
	public Object delOrgUserByOrdId(HttpServletRequest request){
		Map map = new HashMap();
		String orgId = request.getParameter("orgId");
		String userId = request.getParameter("userId");
		Set<User> setUser = new HashSet<User>();
		PageRequest pageRequest = this.getPage(request);
		Page<User> users = new Page<User>(pageRequest);
		boolean flag = false;
		if(null != orgId){
			OrgInfo org = orgService.getOrgById(Long.valueOf(orgId));
			setUser = org.getUsers();
			if(null != userId){
				User user = userService.getUser(Long.valueOf(userId));
				if(setUser.contains(user)){
					setUser.remove(user);
				}
				org.setUsers(setUser);
				orgService.updateOrg(org);
			}
			map.put("total", setUser.size());
			map.put("rows", setUser);
		}
		return map;
	}

	@RequestMapping({ "/isExistNext" })
	@ResponseBody
	public Object isExistNext(HttpServletRequest request) {
		String orgId = request.getParameter("orgId");
		Map result = new HashMap();
		List list = orgService.getChildOrgById(Long.valueOf(orgId));
		if (null != list) {
			if (list.size() > 0) {
				result.put("flag", false);
				result.put("info", "当前菜单存在子菜单，无法进行删除！");
			} else {
				result.put("flag", true);
			}
		} else {
			result.put("flag", true);
		}
		return result;
	}
	
	/**
	 * 根据id删除
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteOrg")
	@ResponseBody
	public Object deleteOrg(HttpServletRequest request, HttpServletResponse response){
		Map result = new HashMap();
		String orgId = request.getParameter("ids");
		if(null != orgId){
			boolean flag = orgService.delOrgById(Long.valueOf(orgId));
			result.put("flag", true);
		}else {
			result.put("flag", false);
		}
		return result;
	}

	@RequestMapping("/queryOrgById")
	@ResponseBody
	public Object queryOrgById(HttpServletRequest request,
			HttpServletResponse response) {
		String orgId = request.getParameter("orgId");
		OrgInfo orgInfo = orgService.getOrgById(Long.valueOf(orgId));
		return orgInfo;
	}
}
