package com.jeeplus.modules.API.maillist;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.API.easemob.EasemobController;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.utils.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 邀请同事Controller
 * @author zmy
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${frontPath}/maillist/invite")
public class InviteController extends BaseController {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
    @Autowired
	private UserofficeService userofficeService;

	/**
	 * 获取职位列表
	 */
	@ResponseBody
	@RequestMapping(value = "getMailListRoleList", method=RequestMethod.GET)
	public AjaxJson findRole (String companyId,String officeId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
		AjaxJson j=new AjaxJson(); 
		Role role=new Role();
		Office company = officeService.get(companyId);
		role.setCompany(company);
		role.setOffice(new Office(officeId));
		List<Role> roleList=roleDao.findList(role);
		/*List<Office> officeList = officeDao.findAllListByParentIds(company);
		for (Office office:officeList){
			if (office.getType().equals("1")){
				Role r=new Role();
				r.setCompany(office);
				List<Role> roleLists = roleDao.findList(r);
				roleList.addAll(roleLists);
			}
		}*/
		List<Map<String,Object>> mapList = Lists.newArrayList();
		for(int i = 0; i < roleList.size(); i++){
			Map<String,Object> map = Maps.newHashMap();
			Role r = roleList.get(i);
			map.put("roleName", r.getName());
			map.put("roleId", r.getId());
			mapList.add(map);
		}		
		j.put("data", mapList);
		j.setMsg("获取公司职位列表成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j; 
	}
	
	/**
	 * 获取部门列表
	 */
	@ResponseBody
	@RequestMapping(value = "getMailListOfficeList", method=RequestMethod.GET)
	public AjaxJson findOffice (String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
		AjaxJson j=new AjaxJson();
		try {
			List<Map<String,Object>> mapList = Lists.newArrayList();
			List<Map<String,Object>> maps = Lists.newArrayList();
			Office company = officeService.get(companyId);
			Map<String,Object> map1 = new HashMap<>();
			map1.put("officeId",company.getId());
			map1.put("officeName",company.getTopCompany());
			map1.put("type","2");
			maps.add(map1);
			if (company.getType().equals("1")) {
				company.setParent(new Office(companyId));
				List<Office> officeList = officeDao.findListByParentId(company);
				for (int i = 0; i < officeList.size(); i++) {
					Office e = officeList.get(i);
					if (e.getType().equals("2")) {
						company.setParent(e);
						Integer count = officeDao.findListByParentIdCount(company);
						List<User> userList = systemService.findUserByOffices(e,company);
						Map<String, Object> map = Maps.newHashMap();
						map.put("count", userList.size());
						map.put("officeId", e.getId());
						map.put("type", count == null || count == 0 ? "0" : "1");
						map.put("officeName", e.getTopCompany());
						mapList.add(map);
					} else {
						if (e.getType().equals("1") && !"0,".equals(e.getParentIds())) {
							logger.info("排除子公司数据");
						} else {
							List<User> userList = systemService.findUserByOffices(e, company);
							Map<String, Object> map = Maps.newHashMap();
							map.put("officeId", e.getId());
							map.put("count", userList.size());
							map.put("type", "2");
							map.put("officeName", e.getTopCompany());
							mapList.add(map);
						}
					}
				}
				j.put("data", mapList);
				j.put("parents", maps);
				j.setErrorCode(ErrorCode.code_1004);
				j.setMsg("获取组织架构列表成功");
			}else {
				j.put("data", new HashMap<>());
				j.put("parents", maps);
				j.setErrorCode(ErrorCode.code_1004);
				j.setMsg("获取组织架构失败,公司id错误");
			}
		}catch (Exception e){
			j.setSuccess(false);
			j.put("data", new HashMap<>());
			j.put("parents", new HashMap<>());
			j.setErrorCode(ErrorCode.code_2004);
			j.setMsg("获取组织架构失败");
		}

		return j; 
	}
	
	/**
	 * 获取部门员工列表
	 */
	@ResponseBody
	@RequestMapping(value = "getMailListMembersList", method=RequestMethod.GET)
	public AjaxJson findMembers (String officeId,String type,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
		AjaxJson j=new AjaxJson();
		try{
			List<Map<String, Object>> maps = Lists.newArrayList();
			Office office = officeDao.get(officeId);
			Map<String,Object> map1 = new HashMap<>();
			map1.put("officeId",office.getId());
			map1.put("officeName",office.getTopCompany());
			map1.put("type",office.getType().equals("2")?"1":"2");
			String[] parentIds = office.getParentIds().split(",");
			for (String id:parentIds){
				if (!id.equals("0")) {
					Office o = officeDao.get(id);
					Map<String,Object> map = new HashMap<>();
					map.put("officeId",o.getId());
					map.put("officeName",o.getTopCompany());
					map.put("type",o.getType().equals("2")?"1":"2");
					maps.add(map);
				}
			}
			maps.add(map1);
			if("0".equals(type)) {
				List<User> userList = new ArrayList<>();
				userList = systemService.findUserByOfficeId(officeId);
				List<Map<String, Object>> glymapList = Lists.newArrayList();
				for (int i = 0; i < userList.size(); i++) {
					User user = userList.get(i);
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", user.getId());
					map.put("name", user.getName());
					map.put("photo", user.getPhoto());
					map.put("isgly", 0);
					Role role = new Role();
					role.setUser(user);
					role.setCompany(UserUtils.getSelectCompany());
					List<Role> roleList = roleDao.findList(role);
					for (Role r : roleList) {
						if (org.apache.commons.lang3.StringUtils.isNotBlank(r.getEnname()) && r.getEnname().endsWith("gly") || r.getEnname().equals("system")) {
							map.put("isgly", 1);
						}
					}
					glymapList.add(map);
				}
				j.put("data", glymapList);
				j.setMsg("获取部门下员工列表成功");
			}else {
				List<Map<String,Object>> mapList = Lists.newArrayList();
				Office company = UserUtils.getSelectCompany();
				company.setParent(new Office(officeId));
				List<Office> officeList = officeDao.findListByParentId(company);
				for (int i = 0; i < officeList.size(); i++) {
					Office e = officeList.get(i);
					if (e.getType().equals("2")) {
						company.setParent(e);
						Integer count = officeDao.findListByParentIdCount(company);
						List<User> userList = systemService.findUserByOffices(e,company);
						Map<String, Object> map = Maps.newHashMap();
						map.put("count", userList.size());
						map.put("officeId", e.getId());
						map.put("type", count==null||count==0?"0":"1");
						map.put("officeName", e.getTopCompany());
						mapList.add(map);
					}else {
						if (e.getType().equals("1") && !"0,".equals(e.getParentIds())){
							logger.info("排除子公司数据");
						}else{
							List<User> userList = systemService.findUserByOffices(e,company);
							Map<String, Object> map = Maps.newHashMap();
							map.put("officeId", e.getId());
							map.put("count", userList.size());
							map.put("officeName", e.getTopCompany());
							map.put("type", "2");
							mapList.add(map);
						}
					}
				}
				j.put("data", mapList);
				j.setMsg("获取组织架构列表成功");
			}
			j.put("parents", maps);
			j.setErrorCode(ErrorCode.code_1004);
		}catch (Exception e){
			j.put("data", new HashMap<>());
			j.put("parents",new HashMap<>());
			j.setErrorCode(ErrorCode.code_2004);
			if("0".equals(type)) {
				j.setMsg("获取组织架构列表失败");
			}else{
				j.setMsg("获取部门下员工列表失败");
			}

		}
		return j; 
	}
	
	/**
	 * 添加员工 （加入企业）
	 */
	  @ResponseBody
	  @RequestMapping(value = "addMember",method=RequestMethod.POST)
	  @Transactional
	    public AjaxJson addMember(HttpServletRequest request, HttpServletResponse response) {
		  AjaxJson j=new AjaxJson();
		  try {
			  HashMap<String, String> requestMap = findRequestMap(request);
			  String userId = requestMap.get("userId");
			  String roleId = requestMap.get("roleId");
			  String userName = requestMap.get("userName");
			  String mobile = requestMap.get("mobile");
			  String companyId = requestMap.get("companyId");
			  //String officeId = requestMap.get("officeId");
			  User userLogin = UserUtils.getByLoginName(mobile);
			  if (userLogin == null) {
				  j.setMsg("员工添加失败,该手机号未注册");
				  j.setSuccess(false);
				  j.setErrorCode(ErrorCode.code_1003);
				  return j;
			  }
			  if (StringUtils.isBlank(roleId) ){
				  j.setMsg("员工添加失败,员工岗位或者部门不能为空！");
				  j.setSuccess(false);
				  j.setErrorCode(ErrorCode.code_1003);
				  return j;
			  }

			  Role role = roleDao.get(roleId);
			  String officeId = role.getOffice().getId();
			  //User user = UserUtils.get(userId);
			  List<Office> companyList = UserUtils.getAllCompany(userLogin);
			  EasemobController controller = new EasemobController();
			  controller.SendMessage();
			  for (Office office : companyList) {
				  if (role.getCompany().getId().equals(office.getId())) {
					  j.setMsg("添加失败，该用户已是该企业员工");
					  j.setSuccess(false);
					  j.setErrorCode(ErrorCode.code_1009);
					  return j;
				  }
			  }
			  if (role.getCompany().getId()!=companyId || role.getCompany().getId().equals("1")){
				  j.setMsg("保存用户'" + userLogin.getLoginName() + "'失败,当前公司没有这个岗位！");
				  j.setSuccess(false);
				  j.setErrorCode(ErrorCode.code_1009);
				  return j;
			  }
			  //role.setOffice(new Office(officeId));
			  /*List<Role> roleList =systemService.getRoleList(userLogin.getId(),"");
			  boolean b = true;
			  for (Role r : roleList){
				  Office o = r.getCompany();
				  if (companyId.equals(o.getId())){
					  roleList.remove(r);
					  roleList.add(new Role(roleId));
					  b = false;
					  break;
				  }
			  }
			  if (b){
				  roleList.add(new Role(roleId));
			  }
			  userLogin.setRoleList(roleList);
			  if (roleIdList==null||roleIdList.size()==0){
				  *//*addMessage(redirectAttributes, "保存用户'" + userLogin.getLoginName() + "'失败,岗位不能为空！");
				  return "redirect:" + adminPath + "/sys/company/joinCompany?repage";*//*
			  }*/
			  String name = userLogin.getName();
			  String roleName = requestMap.get("roleName");
			  String officeName = requestMap.get("officeName");
			  String ishide = requestMap.get("ishide");
			  String no = requestMap.get("no");
			  userLogin.setNo(no);
			  userLogin.setIshide(ishide);
			  userLogin.setName(name);
			  userLogin.setRoleName(roleName);
			  userLogin.setOfficeName(officeName);
			  systemService.saveUserInfo(userLogin);
			  systemService.assignUserToRole(role, userLogin,0);
			  Useroffice useroffice = new Useroffice();
			  useroffice.setCompanyId(companyId);
			  useroffice.setOfficeId(officeId);
			  useroffice.setStatus("3");
			  useroffice.setDelFlag("0");
			  useroffice.setRemarks("管理员邀请");
			  useroffice.setMaster(UserUtils.getUser().getId());
			  useroffice.setUserId(userLogin.getId());
			  List<Useroffice> listOffice = userofficeService.findList(useroffice);
			  if(listOffice==null || listOffice.size()==0){
				  userofficeService.save(useroffice);
			  }else {
				  Useroffice oldUseroffice = listOffice.get(0);
				  oldUseroffice.setOfficeId(request.getParameter("office.id"));
				  userofficeService.save(oldUseroffice);
			  }
			  boolean bool = systemService.outUserInRole(new Role("1"), systemService.getUser(userLogin.getId()));
			  if (bool){
				  systemService.saveCurrentCompanyById(userLogin.getId(), companyId, officeId);
			  }
			  for (Office office : companyList) {
				  if (role.getCompany().getId().equals(office.getId())) {
					  //addMessage(redirectAttributes, "添加失败，该用户已是该企业员工");
				  }
			  }
			  j.setMsg("员工添加成功");
		  }catch (Exception e){
			  j.setErrorCode(ErrorCode.code_2004);
			  j.setSuccess(false);
			  j.setMsg("员工添加失败");
		  }
		return j; 
	}	  		
	
}
