package cn.myapps.runtime.mobile.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.util.StringUtil;
import cn.myapps.runtime.mobile.common.controller.BaseController;
import cn.myapps.runtime.mobile.contacts.model.Department;
import cn.myapps.runtime.mobile.contacts.model.Node;
import cn.myapps.runtime.mobile.contacts.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;


@Controller(value="ContactsController")
@RequestMapping(value="/runtime/app/contacts")
@Scope("prototype")
@Api(tags = "通讯录模块")
public class ContactsController extends BaseController{

	/**
	 * 获取通讯录
	 */
	@RequestMapping(value="/tree.action")
	@ResponseBody
	@ApiOperation(value = "获取通讯录", notes = "获取通讯录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "parentId",value = "父级部门id",required = false,paramType = "query",dataType = "string")
	})
	public Map<String, Object> getContactsTree(){
		if (getUserId() == null) {
			return addActionResult(false, "access_token invalid", null);
		}
		try {
			int count = 0;
			List<Node> avatars = new ArrayList<Node>();
			WebUser webUser = getUser();
			ParamsTable params = getParams();
			String parentId = params.getParameterAsString("parentId");
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			if(StringUtil.isBlank(parentId)){
				DepartmentVO dept = process.getRootDepartmentByDomainId(webUser.getDomainid());
				Department d = new Department();
				d.setId(dept.getId());
				d.setName(dept.getName());
				d.setUserCount(userProcess.getCountsByDepartment(dept.getId()));
				avatars.add(d);
				Collection<UserVO> users = userProcess.queryByDepartment(dept.getId(),true);
				count += users.size();
			}else{
				DepartmentVO parent = (DepartmentVO) process.doView(parentId);
				Collection<DepartmentVO> departments = process.getDatasByParent(parentId);
				Collection<UserVO> users = userProcess.queryByDepartment(parentId,true);
				UserVO me = (UserVO) userProcess.doView(webUser.getId());
				count += users.size();
				for(UserVO userVO : users){
					if(userVO.getStatus() == 0 || userVO.getPermissionType().equals(UserVO.PERMISSION_TYPE_PRIVATE))
						continue;
					User u = new User();
					u.setId(userVO.getId());
					u.setName(userVO.getName());
					u.setMobile(userVO.getTelephone());
					u.setMobile2(userVO.getTelephone2());
					u.setEmail(userVO.getEmail());
					if(!StringUtil.isBlank(userVO.getAvatar())){
						String avatar = userVO.getAvatarUri();
						u.setAvatar(avatar+"?accessToken="+getAccess_token());
					}else{
						u.setAvatar("");
					}
					u.setDomain(userVO.getDomain().getName());
					u.setDept(parent.getName());
					if(me.getFavoriteContacts() !=null && me.getFavoriteContacts().indexOf(userVO.getId())>=0){
						u.setFavoriteContact(true);
					}else{
						u.setFavoriteContact(false);
					}
					avatars.add(u);
				}

				for (Iterator<DepartmentVO> iterator = departments.iterator(); iterator.hasNext();) {
					DepartmentVO departmentVO = iterator.next();
					Department d = new Department();
					d.setId(departmentVO.getId());
					d.setName(departmentVO.getName());
					avatars.add(d);
					Collection<UserVO> user = userProcess.queryByDepartment(departmentVO.getId(),true);
					count += user.size();
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("datas", avatars);
			map.put("count", count);
			return addActionResult(true, "ok", map);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 根据联系人姓名,首字母,电话进行模糊查询（联系人）
	 */
	@RequestMapping(value="/getContactsBySearch.action")
	@ResponseBody
	@ApiOperation(value = "模糊搜索联系人", notes = "模糊搜索联系人")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "keyWord",value = "联系人姓名,首字母,电话",required = false,paramType = "query",dataType = "string")
	})
	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());
			UserVO me = (UserVO) userProcess.doView(webUser.getId());
			for(UserVO userVO : user){
				User u = new User();
				u.setId(userVO.getId());
				u.setName(userVO.getName());
				u.setMobile(userVO.getTelephone());
				u.setMobile2(userVO.getTelephone2());
				u.setEmail(userVO.getEmail());
				if(!StringUtil.isBlank(userVO.getAvatar())){
					String avatar = userVO.getAvatarUri();
					u.setAvatar(avatar+"?accessToken="+getAccess_token());
				}else{
					u.setAvatar("");
				}
				u.setDomain(userVO.getDomain().getName());
				DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
				DepartmentVO dept = (DepartmentVO) deptProcess.doView(userVO.getDefaultDepartment());
				u.setDept(dept.getName());
				if(me.getFavoriteContacts() !=null && me.getFavoriteContacts().indexOf(userVO.getId())>=0){
					u.setFavoriteContact(true);
				}else{
					u.setFavoriteContact(false);
				}
				users.add(u);
			}
			return addActionResult(true, "ok", users);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 根据部门名字进行模糊查询（部门）
	 */
	@RequestMapping(value="/getDepartmentsBySearch.action")
	@ResponseBody
	@ApiOperation(value = "模糊搜索部门", notes = "模糊搜索部门")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "keyWord",value = "联系人姓名,首字母,电话",required = false,paramType = "query",dataType = "string")
	})
	public Map<String, Object> getDepartmentsBySearch(){
		List<Node> deptList = new ArrayList<Node>();
		WebUser webUser = getUser();
		ParamsTable params = getParams();

		String keyWord = params.getParameterAsString("keyWord");

		try {
			DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
//				Map<String,Object> sqlParameterMap = new HashMap<String,Object>();
//				String hql = "from "+DepartmentVO.class.getName()+" where domain_id= :domain_id AND (name like :keyWord )  order by orderByNo";
//				sqlParameterMap.put("domain_id", webUser.getDomainid());
//				sqlParameterMap.put("keyWord", "%"+keyWord+"%");
//				List<DepartmentVO> depts = (List<DepartmentVO>)deptProcess.doQueryByHQL(hql,1,Integer.MAX_VALUE,sqlParameterMap);
			List<DepartmentVO> depts = (List<DepartmentVO>)deptProcess.doQueryByDomainLikeName(webUser.getDomainid(), keyWord);

			for(DepartmentVO deptVO : depts){
				Department dept = new Department();
				dept.setId(deptVO.getId());
				dept.setName(deptVO.getName());
				deptList.add(dept);
			}
			return addActionResult(true, "ok", deptList);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 根据联系人姓名,首字母,电话进行模糊查询（联系人）
	 * 根据部门名称进行模糊查询（部门）
	 */
	@RequestMapping(value="/getContactsAndDeptsBySearch.action")
	@ResponseBody
	@ApiOperation(value = "模糊搜索联系人和部门", notes = "模糊搜索联系人和部门")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "keyWord",value = "联系人姓名,首字母,电话",required = false,paramType = "query",dataType = "string")
	})
	public Map<String, Object> getContactsAndDeptsBySearch(){
		List<Node> list = 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.getId());
			UserVO me = (UserVO) userProcess.doView(webUser.getId());
			for(UserVO userVO : user){
				User u = new User();
				u.setId(userVO.getId());
				u.setName(userVO.getName());
				u.setMobile(userVO.getTelephone());
				u.setMobile2(userVO.getTelephone2());
				u.setEmail(userVO.getEmail());
				if(!StringUtil.isBlank(userVO.getAvatar())){
					String avatar = userVO.getAvatarUri();
					u.setAvatar(avatar+"?accessToken="+getAccess_token());
				}else{
					u.setAvatar("");
				}
				u.setDomain(userVO.getDomain().getName());
				DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
				DepartmentVO dept = (DepartmentVO) deptProcess.doView(userVO.getDefaultDepartment());
				u.setDept(dept.getName());
				if(me.getFavoriteContacts() !=null && me.getFavoriteContacts().indexOf(userVO.getId())>=0){
					u.setFavoriteContact(true);
				}else{
					u.setFavoriteContact(false);
				}
				list.add(u);
			}
			DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
//			Map<String,Object> sqlParameterMap = new HashMap<String,Object>();
//			String hql = "from "+DepartmentVO.class.getName()+" where domain_id= :domain_id AND (name like :keyWord )  order by orderByNo";
//			sqlParameterMap.put("domain_id", webUser.getDomainid());
//			sqlParameterMap.put("keyWord", "%"+keyWord+"%");
//			List<DepartmentVO> depts = (List<DepartmentVO>)deptProcess.doQueryByHQL(hql,1,Integer.MAX_VALUE,sqlParameterMap);
			List<DepartmentVO> depts = (List<DepartmentVO>)deptProcess.doQueryByDomainLikeName(webUser.getDomainid(), keyWord);
			for(DepartmentVO deptVO : depts){
				Department dept = new Department();
				dept.setId(deptVO.getId());
				dept.setName(deptVO.getName());
				list.add(dept);
			}
			return addActionResult(true, "ok", list);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 获取常用联系人
	 */
	@RequestMapping(value="/getFavoriteContacts.action")
	@ResponseBody
	@ApiOperation(value = "获取常用联系人", notes = "获取常用联系人")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
	})
	public Map<String, Object> getFavoriteContacts(){
		try {
			List<User> list = new ArrayList<User>();
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			WebUser user = getUser();
			UserVO vo = (UserVO) userProcess.doView(user.getId());
			int count = 0;
			if(!StringUtil.isBlank(vo.getFavoriteContacts())){
				String[] ids = vo.getFavoriteContacts().split(";");

				Collection<UserVO> users = (List<UserVO>)userProcess.queryByUserIds(ids, user.getDomainid());

				UserVO me = (UserVO) userProcess.doView(user.getId());
				for(UserVO userVO : users){
					//过滤非有效状态
					if (userVO.getStatus()!=1 || !"public".equals(userVO.getPermissionType())) continue;

					User u = new User();
					u.setId(userVO.getId());
					u.setName(userVO.getName());
					u.setMobile(userVO.getTelephone());
					u.setMobile2(userVO.getTelephone2());
					u.setEmail(userVO.getEmail());
					if(!StringUtil.isBlank(userVO.getAvatar())){
						String avatar = userVO.getAvatarUri();
						u.setAvatar(avatar+"?accessToken="+getAccess_token());
					}else{
						u.setAvatar("");
					}
					u.setDomain(userVO.getDomain().getName());
					DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
					DepartmentVO dept = (DepartmentVO) deptProcess.doView(userVO.getDefaultDepartment());
					u.setDept(dept.getName());
					if(me.getFavoriteContacts() !=null && me.getFavoriteContacts().indexOf(userVO.getId())>=0){
						u.setFavoriteContact(true);
					}else{
						u.setFavoriteContact(false);
					}
					list.add(u);
					count++;
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("datas", list);
			map.put("count", count);
			return addActionResult(true, "ok", map);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 添加常用联系人
	 */
	@RequestMapping(value="/addFavoriteContact.action")
	@ResponseBody
	@ApiOperation(value = "添加常用联系人", notes = "添加常用联系人")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "userId",value = "联系人主键",required = true,paramType = "query",dataType = "string")
	})
	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) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 绉婚櫎甯哥敤鑱旂郴浜�
	 */
	@RequestMapping(value="/removeFavoriteContact.action")
	@ResponseBody
	@ApiOperation(value = " 移除常用联系人", notes = " 移除常用联系人")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "userId",value = "联系人主键",required = true,paramType = "query",dataType = "string")
	})
	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) {
			return addActionResult(false, e.getMessage(), null);
		}
	}
}
