package cn.myapps.contacts.controller;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.department.model.DepartmentVO;
import cn.myapps.authtime.department.service.DepartmentProcess;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.data.tree.*;
import cn.myapps.common.model.role.Role;
import cn.myapps.common.util.StringUtil;
import cn.myapps.designtime.role.service.RoleDesignTimeService;
import cn.myapps.runtime.workflow.storage.runtime.ejb.FlowHistoryService;
import cn.myapps.runtime.workflow.storage.runtime.ejb.FlowHistoryServiceImpl;
import cn.myapps.runtime.workflow.storage.runtime.ejb.FlowHistoryVO;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller(value="ContactsAction")
@RequestMapping(value="/api/contacts")
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class ContactsController extends BaseController {
	
	@Autowired  
	protected HttpServletRequest request;

	public ContactsController()  {
		super();
	}
	
	@RequestMapping(value={"/contacts/getAllUser.action","/getAllUser.action"})
	public Map<String, Object> getAllUser(){
		List<Node> users = new ArrayList<Node>();
		WebUser webUser = getUser();
		try {
			UserProcess userPorcess = AuthTimeServiceManager.userRuntimeService();
			String _pageNo = params.getParameterAsString("pageNo");
			int pageNo = StringUtil.isBlank(_pageNo)? 1 : Integer.valueOf(_pageNo);
			int pageCount = 10 ;

			datas = userPorcess.doQueryByDomainAndOrderByNameLetter(webUser.getDomainid(), "nameLetter", pageNo, pageCount);
			Collection<UserVO> user = (Collection<UserVO>) datas.getDatas();
			for(UserVO userVO : user){
					UserNode u = getUser(userVO);
					users.add(u);
			}
			//封装数据
			Map<String,Object> result = new HashMap<String,Object>();
			result.put("datas", users);
			result.put("linesPerPage", datas.getLinesPerPage());
			result.put("pageCount", datas.getPageCount());
			result.put("pageNo", datas.getPageNo());
			result.put("rowCount", datas.getRowCount());
			return addActionResult(true, "", result);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value="/contacts/getContacts.action")
	public Map<String, Object> getContacts(){
		List<Node> avatars = new ArrayList<Node>();
		WebUser webUser = getUser();
		try {
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			UserProcess userPorcess = AuthTimeServiceManager.userRuntimeService();
			Map<String,List<Node>> deptMap = new HashMap<String, List<Node>>();//key 部门id value 子部门集合
			List<DepartmentVO> departments = (List<DepartmentVO>) process.doQueryByDomainOrderLevelDescOrderByNo(webUser.getDomainid());

			Collection<UserVO> users = userPorcess.queryByDomain(webUser.getDomainid());
			
			for (Iterator<DepartmentVO> iterator = departments.iterator(); iterator.hasNext();) {
				DepartmentVO departmentVO = iterator.next();
				DepartmentNode d = new DepartmentNode();
				d.setId(departmentVO.getId());
				d.setName(departmentVO.getName());
				DepartmentVO s = departmentVO.getSuperior();
				
				for(UserVO userVO : users){
					if (userVO.getStatus() == 1 && "public".equals(userVO.getPermissionType()))
						if (userVO.getDefaultDepartment().equals(departmentVO.getId())) {
							UserNode u = new UserNode();
							u.setId(userVO.getId());
							u.setName(userVO.getName());
							if (userVO.isTelephonePublic()) {
								u.setMobile(userVO.getTelephone());
							}
							if (userVO.isTelephonePublic2()) {
								u.setMobile2(userVO.getTelephone2());
							}
							if (userVO.isEmailPublic()) {
								u.setEmail(userVO.getEmail());
							}
							if (!StringUtil.isBlank(userVO.getAvatar())) {
								String avatar = userVO.getAvatarUri();
								u.setAvatar(avatar);
							} else {
								u.setAvatar("");
							}

							u.setDept(d.getName());
							d.addChildren(u);

							// users.remove(userVO);
						}
				}
				
				if(deptMap.get(d.getId()) !=null){
					d.addChildrens(deptMap.get(d.getId()));
				}
				
				if(s !=null){
					List<Node> list = deptMap.get(s.getId());
					if(list == null) {
						list = new ArrayList<Node>();
						deptMap.put(s.getId(), list);
					}
					list.add(d);
				}else{
					avatars.add(d);
				}
				
			}
			return addActionResult(true, "", avatars);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	
	@RequestMapping(value={"/contacts/getApplicationAndRoleContactsTree.action","/getApplicationAndRoleContactsTree.action"})
	public Map<String, Object> getApplicationAndRoleContactsTree(){
		List<Node> avatars = new ArrayList<Node>();
		WebUser webUser = getUser();
		ParamsTable params = getParams();
		try {
			String applictaionId = params.getParameterAsString("applictaionId");
			String roleId = params.getParameterAsString("roleId");
			
			if(StringUtil.isBlank(roleId) && StringUtil.isBlank(applictaionId)){  //初始化界面获取软件
//				DomainProcess process = (DomainProcess)ProcessFactory.createProcess(DomainProcess.class);
				Collection<cn.myapps.common.model.application.Application> apps = webUser.getDomain().getApplications();
				
				ApplicationNode app;
				for(cn.myapps.common.model.application.Application appVO : apps){
					if(appVO.isActivated()){
						app = new ApplicationNode();
						app.setId(appVO.getId());
						app.setName(appVO.getName());
						avatars.add(app);
					}
				}
			}else if (!StringUtil.isBlank(applictaionId) && StringUtil.isBlank(roleId)){ //根据软件获取角色
				RoleDesignTimeService roleService = AuthTimeServiceManager.roleRuntimeService();
				Collection<Role> roles = roleService.getRolesByApplication(applictaionId);
				
				RoleNode role ;
				for(Role roleVO : roles){
					if(roleVO.getStatus() ==  Role.STATUS_VALID){
						role = new RoleNode();
						role.setId(roleVO.getId());
						role.setName(roleVO.getName());
						avatars.add(role);
					}
				}
			}else if(!StringUtil.isBlank(roleId)){  //获取角色下的成员
				UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
                Collection<UserVO> users = userProcess.queryByRoleAndDomain(roleId,webUser.getDomainid());
			
				for(UserVO userVO : users){
					if(userVO.getStatus() == 0)
						continue;
					UserNode u = getUser(userVO);
					avatars.add(u);
			  }
			}
			return addActionResult(true, "", avatars);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value="/contacts/getContactsBySearch.action")
	public Map<String, Object> getContactsBySearch(){
		List<Node> users = new ArrayList<Node>();
		WebUser webUser = getUser();
		ParamsTable params = getParams();
		
		String keyWord = params.getParameterAsString("keyWord");
			
			try {
				UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();

				Collection<UserVO> user = userProcess.queryByFuzzy(keyWord, webUser.getDomainid());
				
				for(UserVO userVO : user){
					if (userVO.getStatus() == 1 && "public".equals(userVO.getPermissionType())){
						UserNode u = getUser(userVO);
						users.add(u);
					}
			}
				return addActionResult(true, "", users);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	/**
	 * 首字母查询联系人
	 * @return
	 */
	@RequestMapping(value="/contacts/getContactsByFirstLetter.action")
	public Map<String, Object> getContactsByFirstLetter(){
		List<Node> users = new ArrayList<Node>();
		WebUser webUser = getUser();
		ParamsTable params = getParams();
		
		String keyWord = params.getParameterAsString("keyWord");
			
			try {
				UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();

				Collection<UserVO> user = userProcess.queryByFirstLetter(keyWord, webUser.getDomainid() );
				
				for(UserVO userVO : user){
					UserNode u = getUser(userVO);
					users.add(u);
			}
				return addActionResult(true, "", users);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value={"/contacts/getContactsTree.action","/getContactsTree.action"})
	public Map<String, Object> getContactsTree(){
		List<Node> avatars = new ArrayList<Node>();
		WebUser webUser = getUser();
		ParamsTable params = getParams();
		try {
			String parentId = params.getParameterAsString("parentId");
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			
			if(StringUtil.isBlank(parentId)){
				DepartmentVO departmentVO = process.getRootDepartmentByDomainId( webUser.getDomainid());
				DepartmentNode d = new DepartmentNode();
				d.setId(departmentVO.getId());
				d.setName(departmentVO.getName());
				avatars.add(d);
			}else{
				DepartmentVO parent = (DepartmentVO) process.doView(parentId);
				Collection<DepartmentVO> departments = (Collection<DepartmentVO>) process.getDatasByParent(parentId);
				//Collection<UserVO> users =parent.getUsers();
				Collection<UserVO> users = userProcess.queryByDepartment(parentId,true);
				
				for(UserVO userVO : users){
					if(userVO.getStatus() == 0 || userVO.getPermissionType().equals(UserVO.PERMISSION_TYPE_PRIVATE))
						continue;
					UserNode u = new UserNode();
					u.setId(userVO.getId());
					u.setName(userVO.getName());
					if(userVO.isTelephonePublic()){
						u.setMobile(userVO.getTelephone());
					}
					if(userVO.isTelephonePublic2()){
						u.setMobile2(userVO.getTelephone2());
					}
					if(userVO.isEmailPublic()){
						u.setEmail(userVO.getEmail());
					}
					if(!StringUtil.isBlank(userVO.getAvatar())){
						String avatar = userVO.getAvatarUri();
						u.setAvatar(avatar);
					}else{
						u.setAvatar("");
					}
					u.setDept(parent.getName());
					
					avatars.add(u);
				}
				
				for (Iterator<DepartmentVO> iterator = departments.iterator(); iterator.hasNext();) {
					DepartmentVO departmentVO = iterator.next();
					DepartmentNode d = new DepartmentNode();
					d.setId(departmentVO.getId());
					d.setName(departmentVO.getName());
					avatars.add(d);
				}
				
				
			}
			return addActionResult(true, "", avatars);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value="/contacts/addFavoriteContact.action")
	public Map<String, Object> addFavoriteContact(){
		try {
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			WebUser user = getUser();
			ParamsTable params = getParams();
			String userId = params.getParameterAsString("userId");
			UserVO userVO = (UserVO) userProcess.doView(user.getId());
			if(StringUtil.isBlank(userVO.getFavoriteContacts())){
				userVO.setFavoriteContacts(userId);
			}else{
				userVO.setFavoriteContacts(userVO.getFavoriteContacts()+";"+userId);
			}
			userProcess.doUpdate(userVO);
			
			return addActionResult(true, "添加成功", null);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value="/contacts/removeFavoriteContact.action")
	public Map<String, Object> removeFavoriteContact(){
		try {
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			WebUser user = getUser();
			ParamsTable params = getParams();
			String userId = params.getParameterAsString("userId");
			UserVO userVO = (UserVO) userProcess.doView(user.getId());
			if(userVO.getFavoriteContacts().indexOf(userId)==0){
				userVO.setFavoriteContacts(userVO.getFavoriteContacts().replace(userId, ""));
			}else{
				userVO.setFavoriteContacts(userVO.getFavoriteContacts().replace(";"+userId, ""));
			}
			
			userProcess.doUpdate(userVO);
			return addActionResult(true, "移除成功", null);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value={"/contacts/getFavoriteContacts.action","/getFavoriteContacts.action"})
	public Map<String, Object> getFavoriteContacts(){
		try {
			List<UserNode> list = new ArrayList<UserNode>();
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			WebUser user = getUser();
			UserVO vo = (UserVO) userProcess.doView(user.getId());
			
			if(!StringUtil.isBlank(vo.getFavoriteContacts())){
				String[] ids = vo.getFavoriteContacts().split(";");
				StringBuilder cdt = new StringBuilder();
				for (int i = 0; i < ids.length; i++) {
					cdt.append("'").append(ids[i]).append("'").append(",");
				}
				cdt.setLength(cdt.length()-1);

				Collection<UserVO> users = userProcess.queryByUserIds(ids,
						user.getDomainid());
				for(UserVO userVO : users){
					if (userVO.getStatus() == 1 && "public".equals(userVO.getPermissionType())){
						UserNode u = getUser(userVO);
						list.add(u);	
					}
				}
			}
			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	@RequestMapping(value="/contacts/isFavoriteContact.action")
	public Map<String, Object> isFavoriteContact(){
		try {
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			WebUser user = getUser();
			ParamsTable params = getParams();
			String userId = params.getParameterAsString("userId");
			UserVO userVO = (UserVO) userProcess.doView(user.getId());
			if(userVO.getFavoriteContacts() !=null && userVO.getFavoriteContacts().indexOf(userId)>=0){
				return addActionResult(true, "", true);
			}else{
				return addActionResult(true, "", false);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	/**
	 * 获取用户头像
	 * @return
	 */
	@RequestMapping(value="/contacts/getAvatar.action")
	public Map<String, Object> getAvatar(){
		try {
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			ParamsTable params = getParams();
			String userId = params.getParameterAsString("id");
			UserVO userVO = (UserVO) userProcess.doView(userId);
			if(userVO != null){
				String avatar = "";
				if(!StringUtil.isBlank(userVO.getAvatar())){
					avatar = userVO.getAvatarUri();
				}
				return addActionResult(true, "", avatar);
			}else{
				return addActionResult(false, "找不到指定用户", null);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	/**
	 * 获取角色下或部门下人数
	 * @return
	 */
	@RequestMapping(value="/contacts/getRoleOrDeptUserCounts.action")
	public Map<String, Object> getRoleOrDeptUserCounts(){
		try {
			ParamsTable params = getParams();
			Integer type = params.getParameterAsInteger("type");        // 数据类型
			String id = params.getParameterAsString("id");              // 查询Id
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			Long userCounts  = null ;
			userCounts  = userProcess.getCountsByDepartment(id);
			if(type == Node.TYPE_DEPT){ // 查询部门下的人数
				userCounts  = userProcess.getCountsByDepartment(id);
			}else if(type == Node.TYPE_ROLE){ // 查询角色下的人数
				userCounts = userProcess.getCountsByRoleAndDomain(id, getUser().getDomainid());
			}
			return addActionResult(true, "", userCounts);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	/*
	 * 自由流程模式回退获取历史处理人
	 */
	@RequestMapping(value="/getHisActors4FreeFlow.action")
	public Map<String, Object> getHisActors4FreeFlow(){
		try {
			ParamsTable params = getParams();
			WebUser webUser = getUser();
			String _userId = webUser.getId();
			String stateId = params.getParameterAsString("stateId");
			String applicationId = params.getParameterAsString("applicationId");

			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			FlowHistoryService hisProcess = new FlowHistoryServiceImpl(applicationId);
			Collection<FlowHistoryVO> list = hisProcess.getFlowHistorysByDocId(stateId);
			
			//去除重复的处理人
			Map<String , UserVO> userMap = new HashMap<String , UserVO>();
			for(FlowHistoryVO his : list){
				String userId = his.getAuditorId();
				if(_userId.equals(userId)){//回退指定审批人不应包含自己
					continue;
				}
				if(!userMap.containsKey(userId)){
					UserVO userVO = (UserVO) userProcess.doView(userId);
					userMap.put(userId, userVO);
				}
			}
			Collection<UserNode> userList = new ArrayList<UserNode>(); 
			for(String key : userMap.keySet()){
				userList.add(getUser(userMap.get(key)));
			}
			return addActionResult(true, "", userList);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, "获取用户失败", "");
		}
	}
	
	private UserNode getUser(UserVO userVO) throws Exception{
		UserNode u = new UserNode();
		u.setId(userVO.getId());
		u.setName(userVO.getName());
		if(userVO.isTelephonePublic()){
			u.setMobile(userVO.getTelephone());
		}
		if(userVO.isTelephonePublic2()){
			u.setMobile2(userVO.getTelephone2());
		}
		if(userVO.isEmailPublic()){
			u.setEmail(userVO.getEmail());
		}
		DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
		DepartmentVO dept = (DepartmentVO) deptProcess.doView(userVO.getDefaultDepartment());
		if(dept!=null){
			u.setDept(dept.getName());
		}else{
			u.setDept("");
		}
		if(!StringUtil.isBlank(userVO.getAvatar())){
			String avatar = userVO.getAvatarUri();
			u.setAvatar(avatar);
		}else{
			u.setAvatar("");
		}
		return u;
	}
}
