/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:project
 * File Name:OrgController.java
 * Package Name: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.role.Role;
import org.ccpit.base.role.RoleService;
import org.ccpit.base.user.User;
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.PathVariable;
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(OrgController.class);
	@Autowired
	private OrgService orgService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

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

	/**
	 * 
	 * getAllOrgs:(默认查询出所有的机构信息). <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;
	}
	
	/**
	 * 
	 * getAllApproveplans:(查询部门所有角色). <br/>
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/getAllOrgRoles")
    @ResponseBody
    public Object getAllOrgRoles(HttpServletRequest request){
        PageRequest pageRequest = getPage(request);
        String orgId = request.getParameter("orgId");
        Set<Role> msList = new HashSet<Role>();	
        Page<Role> pageMemberBase = new Page<Role>(pageRequest);
        if(null != orgId && !"".equals(orgId) && !"undefined".equals(orgId)){
        	OrgInfo orgInfo = orgService.getOrgById(Long.valueOf(orgId));
        	if(null != orgInfo){
        		msList = orgInfo.getRoles();
        	}
        }
        List<Role> roleList = new ArrayList<Role>(msList);
        pageMemberBase.setTotal(msList.size());
        pageMemberBase.setRows(roleList);
        return roleService.convert(pageMemberBase);
    }

	@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 {
		// }'
		String hql = "from OrgInfo order by orderNumber asc";
		orglist = this.orgService.getOrgInfoList(hql);
		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/>
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping({ "/orgAddUsers" })
	@ResponseBody
	public Object orgAddUsers(HttpServletRequest request,User user){
		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){
			}
		}
		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));
			Set<User> userSet = org.getUsers();
			List<User> userList = new ArrayList<User>(userSet);
			users.setRows(userList);
			users.setTotal(userList.size());
		}
		return userService.convert(users);
	}
	
	@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);
				boolean flag1 = orgService.updateOrg(org);
				if(flag1){
					user.setWhetherDelete(true);
					flag = userService.updateUser(user);
					
				}
			}
		}
		if(flag){
			map.put("flag", flag);
			map.put("info", "数据删除成功！");
		}else {
			map.put("flag", flag);
			map.put("info", "数据删除失败！");
		}
		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 && list.size()>0) {
			if (list.size() > 0) {
				result.put("flag", false);
				result.put("info", "当前菜单存在子菜单，无法进行删除操作！");
			} else {
				result.put("flag", true);
			}
		} else {
			OrgInfo orgInfo = orgService.getOrgById(Integer.valueOf(orgId));
			Set<User> userSet = orgInfo.getUsers();
			if(null != userSet && userSet.size()>0){
				result.put("flag", false);
				result.put("info", "当前部门存在用户，无法进行删除操作！");
			}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){
			OrgInfo orginfo = orgService.get(Long.valueOf(orgId));
			orginfo.setWhetherDelete(true);
			orgService.updateOrg(orginfo);	
			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;
	}
	
	//查询所有部门信息，根据部门名称进行分组
	@RequestMapping("/getOrgList")
	@ResponseBody
	public Object getOrgList(HttpServletRequest request){
		String hql = "from OrgInfo group by name";
		List<OrgInfo> listBo = orgService.getOrgInfoList(hql);
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getId());
				result.put("text", listBo.get(i).getName());
				if(!list.contains(result)){
					list.add(result);
				}
			}
		} 
		return list;
	}
	
	//查询所有部门信息，根据部门名称进行分组
	@RequestMapping("/getDepartmentList")
	@ResponseBody
	public Object getDepartmentList(HttpServletRequest request){
		String hql = "from OrgInfo group by name";
		List<OrgInfo> listBo = orgService.getOrgInfoList();
		List list = new ArrayList();
		if(null != listBo){
			for(OrgInfo orgInfo : listBo){
				Map result = new HashMap();
				if(0 == orgInfo.getParentId()){
					result.put("id", orgInfo.getId());
					result.put("text", orgInfo.getName());
					result.put("children", getChildren(orgInfo.getId(), listBo));
					if(!list.contains(result)){
						list.add(result);
					}
				}
			}
		} 
		return list;
	}
	
	@RequestMapping("/setOrgRoles/{id}")
    @ResponseBody
    public Object saveUserRoles(@PathVariable long id,HttpServletRequest request){
		OrgInfo orgInfo = orgService.getOrgById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        String ids = request.getParameter("ids");
        String[] idses = ids.split(",");
        Long[] longs = new Long[idses.length];
        for (int i=0;i<idses.length;i++){
            longs[i] = Long.parseLong(idses[i].toString());
        }
        boolean flag = orgService.setOrg_roles(orgInfo,longs);
        if (flag){
            map.put("flag", true);
            map.put("info", "部门角色分配成功！");
        }else{
            map.put("flag", false);
            map.put("info", "部门角色分配失败！");
        }

        return map;
    }
}
