package com.jeeplus.modules.API.userinfo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.dao.CompanyDao;
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.Company;
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.CompanyService;
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 com.jeeplus.modules.workcompanyinfo.service.CompanyinfoService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.apache.commons.io.IOUtils;
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.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 搜索企业Controller
 * @author zmy
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${frontPath}/userInfo/searchcompany")
public class JoinCompanyController extends BaseController{
	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private UserofficeService userofficeService;
    @Autowired
    private CompanyinfoService companyinfoService;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private  PushinfoService pushinfoService;

    @Autowired
    private CompanyService companyService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    private Lock lock = new ReentrantLock();
	/**
	 * 根据企业名称搜索
	 * @throws UnsupportedEncodingException 
	 */
	@ResponseBody
	@RequestMapping(value = "getUserInfoSearchCompanyList", method=RequestMethod.GET)
	public AjaxJson findCompany (String companyName,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException
	{  
	   AjaxJson j=new AjaxJson();
	   Office company=new Office();
	   company.setName(companyName);
	   company.setType("1");
	   List<Office> companyList=officeDao.findListByCompanyName(company);
	   List<Map<String,Object>> mapList = Lists.newArrayList();
	   for(int i = 0; i < companyList.size(); i++){
		   Map<String,Object> map = Maps.newHashMap();
		   Office com=companyList.get(i);
           if (!com.getId().equals("1")){
               map.put("companyName", com.getName());
               map.put("master", com.getMaster()==null || UserUtils.get(com.getMaster())==null?"":UserUtils.get(com.getMaster()).getName());
               map.put("masterId", com.getMaster()==null ?"":com.getMaster());
               map.put("companyLogo", com.getLogo() == null || com.getLogo().equals("") ? "" : com.getLogo());
               map.put("companyId", com.getId());
               Useroffice useroffice = new Useroffice();
               useroffice.setCompanyId(com.getId());
               useroffice.setStatus("3");
               List<Useroffice> userofficeList=userofficeService.findList(useroffice);
               map.put("count", userofficeList.size());
               mapList.add(map);
           }
	   }
	   j.put("data",mapList);
       j.setErrorCode(ErrorCode.code_1004);
       j.setMsg("获取企业信息成功");
	   return j;
	}

    /**
     * 启动加入公司流程
     * @param
     */
    @Transactional
    @RequestMapping(value = "saveJoinCompany", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson saveJoinCompany(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            lock.lock();
            HashMap<String, String> requestMap = findRequestMap(request);
            Map<String, Object> variables = Maps.newHashMap();
            Useroffice companyinfo = new Useroffice();
            String master = URLDecoder.decode(requestMap.get("master")==null?"":requestMap.get("master"), "UTF-8");
            String reason = URLDecoder.decode(requestMap.get("reason")==null?"":requestMap.get("reason"), "UTF-8");
            String companyId = URLDecoder.decode(requestMap.get("companyId")==null?"":requestMap.get("companyId"), "UTF-8");
            if(UserUtils.getSelectCompany().getId().equals(companyId)){
                logger.error("加入公司流程失败：您是该企业员工");
                ajaxJson.setSuccess(false);
                ajaxJson.setErrorCode(ErrorCode.code_1009);
                ajaxJson.setMsg("您已经是该企业员工,不能重复加入");
                return ajaxJson;
            }
            //该公司下所有的岗位
            List<Role> roleList = systemService.getRoleList("",companyId);
            Role role = new Role();
            if (roleList!=null && roleList.size()!=0){
                for (Role r :roleList){
                    //要的是管理员
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(r.getEnname()) && r.getEnname().equals("gly")){
                        role = r;
                        break;
                    }
                }
            }
            //该公司下拥有管理员岗位的所有员工
            List<User> userList = userDao.findUserByRole(role);
            //该公司下拥有管理员岗位的所有员工
            List<String> assigneeList = new ArrayList<String>();
            if (userList!=null && userList.size()!=0) {
                for (User user : userList) {
                    assigneeList.add(user.getId());
                }
            }

            String delFlag="0";
            variables.put("glyList", assigneeList);
            variables.put("glycount",assigneeList.size());
            companyinfo.setUserId(UserUtils.getUser().getId());//申请人
            companyinfo.setCompanyId(companyId);//这一步必须
            List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
            boolean state = false;
            if (companyinfoList!=null){
                if (companyinfoList.size()==0) {
                    state = true;
                }/*else{
                    for (Useroffice companyinfo1:companyinfoList){
                        if (companyinfo1.getStatus().equals("4")){
                            state = true;
                        }else {
                            state = false;
                            break;
                        }
                    }
                }*/
            }
            if (state){
                companyinfo.setStatus("1");
                companyinfo.setDelFlag(delFlag);
                companyinfo.setRemarks(reason);
                companyinfo.setMaster(master);//
                companyinfoService.save(companyinfo, variables);
                ajaxJson.setSuccess(true);
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setMsg("加入公司申请已经提交");
                ajaxJson.put("id", companyinfo.getId());
                String title = "团队申请";
                String content="您有新的团队申请";
                Map extras = new HashMap();
                Pushinfo pushinfo = new Pushinfo();
                pushinfo.setCurrentUser(UserUtils.getUser());
                Office office = officeService.get(companyId);
                if (reason.length()>16){
                    reason = reason.substring(0,16)+"...";
                }
                reason = UserUtils.getUser().getName()+ "\n"
                        +"申请加入："+office==null || office.getName()==null || office.getName().equals("")?"":office.getName()+ "\n"
                        +"申请理由:"+reason;
                pushinfo.setRemarks(reason);
                pushinfo.setUserId(UserUtils.getUser().getId());
                pushinfo.setType("2002");
                pushinfo.setPushId(companyinfo.getId());
                pushinfo.setTitle(title);
                pushinfo.setContent(content);
                pushinfo.setParentType("singleCompanyNews");
                pushinfo.setCompanyId(companyId);
                pushinfo.setAddcontent("joincompany");
                pushinfo.setMobile("ios,android");
                pushinfo.setStatus("0");
                extras.put("type", "2002");
                extras.put("id", companyinfo.getId());
                extras.put("userId",UserUtils.getUser().getId());
                extras.put("userName",UserUtils.getUser().getName());
                //向所有管理员发送推送
                int num = 0 ;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String str = "申请人:"+UserUtils.getUser().getName()+",申请时间:"+sdf.format(new Date());
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(companyinfo.getId(),
                                null,
                                companyId,
                                title,
                                str,
                                "75",
                                "0",
                                "待审批",
                                ""
                        );
                if(assigneeList!=null && assigneeList.size()>0){
                    for(String alias : assigneeList){
                        if(StringUtils.isNotBlank(alias)){
                            pushinfo.setPushUserId(alias);
                            pushinfo.setId("");
                            pushinfoService.save(pushinfo);
                            boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
                            if(b) num++;
                            workProjectNotify.setUser(new User(alias));
                            workProjectNotify.setId("");
                            workProjectNotify.setNotifyRole("公司管理员审批");
                            workProjectNotifyService
                                    .save(workProjectNotify);
                            UserUtils.pushIm(alias,str);
                        }
                    }
                }

                if (num>0){
                    ajaxJson.setMsg("申请加入公司流程成功!");
                }else {
                    ajaxJson.setMsg("申请加入公司流程成功");
                    ajaxJson.setErrorCode(ErrorCode.code_2006);
                    ajaxJson.setSuccess(false);
                }
            }else{
                logger.error("申请加入公司流程失败：您已申请加入企业");
                ajaxJson.setSuccess(false);
                ajaxJson.setErrorCode(ErrorCode.code_1009);
                ajaxJson.setMsg("您已申请加入企业,不能重复申请加入");
                return ajaxJson;
            }

        } catch (Exception e) {
            logger.error("申请加入公司流程失败：", e);
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("申请加入公司流程失败");
        }finally {
            lock.unlock();
        }

        return ajaxJson;
    }

    /**
     * 查看我的企业
     * @param
     * @return json数据
     */
    @RequestMapping(value = "getMyOfficeList", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getMyOfficeList(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try{
            String userId = request.getParameter("userId");
            if (userId==null){
                userId = UserUtils.getUser().getId();
            }
            Useroffice companyinfo = new Useroffice();
            companyinfo.setUserId(userId);
            companyinfo.setDelFlag("0");
            List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
            List<Map<String,Object>> mapList = Lists.newArrayList();
            if (companyinfoList!=null && companyinfoList.size()!=0){
                for (Useroffice com :companyinfoList){
                    if (!"3".equals(com.getStatus())){
                        String companyId =com.getCompanyId();
                        String status = com.getStatus();
                        String companyInfoId = com.getId();
                        Office off = officeService.get(companyId);
                        Map<String,Object> map = Maps.newHashMap();
                        map.put("companyName", off.getName());
                        map.put("companyLogo", off.getLogo() == null ? "" : off.getLogo());
                        map.put("companyQrcode", off.getCompanyQrcode()==null?"":off.getCompanyQrcode());
                        map.put("companyId", off.getId());
                        map.put("status", status);
                        map.put("approvalId", companyInfoId);
                        map.put("master", off.getMaster()==null || UserUtils.get(off.getMaster())==null?"":UserUtils.get(off.getMaster()).getName());
                        map.put("masterId", off.getMaster()==null ?"":off.getMaster());
                        Useroffice useroffice = new Useroffice();
                        useroffice.setCompanyId(off.getId());
                        useroffice.setStatus("3");
                        List<Useroffice> userofficeList=userofficeService.findList(useroffice);
                        map.put("count", userofficeList.size());
                        List<Act> list2 = actTaskService.toMyStartedList(com.getProcessInstanceId());
                        if (list2!=null && list2.size()!=0){
                            Act act1 = list2.get(list2.size()-1);
                            map.put("taskId", act1.getTaskId());
                            map.put("taskName",act1.getTaskName());
                            map.put("procInsId", act1.getProcInsId());
                            map.put("procDefId", act1.getProcDefId());
                            map.put("actStatus", act1.getStatus());
                            map.put("taskDefKey", act1.getTaskDefKey());
                            map.put("procDefKey", "joincompany");
                        }
                        map.put("isgly", 0);
                        Role role2=new Role();
                        role2.setCompany(off);
                        role2.setUser(UserUtils.get(userId));
                        List<Role> roleList2=roleDao.findList(role2);
                        for(Role role : roleList2){
                            map.put("officeId", role.getOffice().getId());
                            map.put("officeName", role.getOffice().getName());
                            if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().endsWith("gly")||role.getEnname().equals("system")){
                                map.put("isgly", 1);
                            }
                            if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().endsWith("gly")||role.getEnname().equals("system")){
                                List<User> userList2=userDao.findUserByRole(role);
                                for (int k = 0; k < userList2.size(); k++) {
                                    if(userList2.get(k)!=null ||userList2.get(k).equals("null")){
                                        map.put("glyName", userList2.get(k).getName());
                                    }
                                }
                            }else{
                                map.put("glyName", "");
                            }
                        }
                        mapList.add(map);
                    }

                }
            }
            j.put("maxNum",mapList.size());
            j.put("data",mapList);
            j.setMsg("获取列表成功");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            logger.info("e="+e.getMessage());
            j.setErrorCode(ErrorCode.code_2004);
            j.setMsg("获取列表失败");
            j.put("maxNum",0);
            j.put("data","");
        }
        return j;
    }

	/**
	 * 申请加入企业
	 */
	/*@ResponseBody
	@RequestMapping(value = "joinCompany", method=RequestMethod.GET)
	public AjaxJson joinCompany (String id,String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException
	{  
		AjaxJson j=new AjaxJson();	
		Office company = officeService.get(companyId);//获取公司
		Role comRole = systemService.getRoleByEnname(StringUtils.getPinYinHeadChar(company.getName(),2)+"xyg");//获取公司xyg的岗位
		if(UserUtils.get(id).getId()!=null){
			List<Office> companyList = UserUtils.getAllCompany(UserUtils.get(id));//获取用户所有企业
			for (Office office : companyList) {
				if(comRole.getCompany().getId().equals(office.getId())){
					j.setMsg( "申请失败，你已是该企业成员");
				}
			}
		}
		List<Office> list = officeService.findList(true);//获取当前用户有权限访问的部门

        EasemobInfo easemobImuser = new EasemobInfo();
        for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			if (e.getName().equals(company.getName()+"人力部")){
				UserUtils.getUser().setOffice(e);
                easemobImuser.setUserId(UserUtils.getUser().getId());
                easemobImuser.setGroupId(e.getGroupId());
                easemobImuser.setJoinStatus("2");
                easemobImuser.setGroupName(e.getGroupName());
			}
			if (e.getName().equals(company.getName())){
				UserUtils.getUser().setCompany(e);
                easemobImuser.setUserId(id);
                easemobImuser.setGroupId(e.getGroupId());
                easemobImuser.setJoinStatus("2");
                easemobImuser.setGroupName(e.getGroupName());
			}

		}

        easemobInfoService.save(easemobImuser);

        if(comRole!=null){
            UserUtils.getUser().setComId(comRole.getCompany().getId());
            systemService.assignUserToRole(comRole, UserUtils.getUser());
        }
		systemService.outUserInRole(new Role("1"), UserUtils.getUser());
		j.setMsg("您的申请已提交，请在“我的管理企业”中查看结果");
		return j;				
	}*/
	/**
	 * 申请内容详情
	 */
	@ResponseBody
    @RequestMapping(value = "applicationContent",method=RequestMethod.POST)
	    public AjaxJson applicationContent(String id,HttpServletRequest request, HttpServletResponse response) {
		 String contentStr="";
	      try {         
	    	  InputStream  is = request.getInputStream();         
	         contentStr= IOUtils.toString(is, "utf-8");     
	          } catch (Exception e) {
	                   e.printStackTrace();     
	              }
	      AjaxJson j=new AjaxJson();
	      Map<String,String> requestMap= StringUtils.StringToJson(contentStr);
	      String remarks =requestMap.get("remarks");	
	      User user=new User();
	      user.setId(id);
	      Company company=new Company();
	      company.setCreateBy(user);
	      company.setRemarks(remarks);		
	      company.preInsert();
	      companyDao.insert(company);	      	      	      			
	      j.setMsg("您的申请已提交，请在“我的管理企业”中查看结果");
	      j.setErrorCode(ErrorCode.code_1004);
	      return j; 
	}


	/**
	 * 重新申请内容详情
	 */
	@ResponseBody
	@RequestMapping(value = "againApplicationContent",method=RequestMethod.POST)
	public AjaxJson againApplicationContent(String id,HttpServletRequest request, HttpServletResponse response) {
		String contentStr="";
		try {
			InputStream  is = request.getInputStream();
			contentStr= IOUtils.toString(is, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		AjaxJson j=new AjaxJson();
		Map<String,String> requestMap= StringUtils.StringToJson(contentStr);
		String remarks =requestMap.get("remarks");
		User user=new User();
		user.setId(id);
		Company company=new Company();
		company.setCreateBy(user);
		company.setRemarks(remarks);
		company.preInsert();
		companyDao.insert(company);
		j.setMsg("您的申请已提交，请在“我的管理企业”中查看结果");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
    /**
     * 重新申请加入企业
     *//*
    @ResponseBody
    @RequestMapping(value = "getUserInfoAgainJoinCompanyList", method=RequestMethod.GET)
    public AjaxJson againJoinCompany (String id,String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException
    {
        AjaxJson j=new AjaxJson();
        Office company = officeService.get(companyId);
        Role comRole = systemService.getRoleByEnname(StringUtils.getPinYinHeadChar(company.getName(),2)+"xyg");
        if(UserUtils.get(id).getId()!=null){
            List<Office> companyList = UserUtils.getAllCompany(UserUtils.get(id));
            if(companyList!=null && companyList.size()!=0) {
                for (Office office : companyList) {
                    if (comRole!=null && comRole.getCompany().getId().equals(office.getId())) {
                        j.setMsg("申请失败，你已是该企业成员");
                    }
                }
            }
        }
        List<Office> list = officeService.findList(true);

        EasemobInfo easemobImuser = new EasemobInfo();
        for (int i=0; i<list.size(); i++){
            Office e = list.get(i);
            if (e.getName().equals(company.getName()+"人力部")){
                UserUtils.getUser().setOffice(e);
                easemobImuser.setUserId(id);
                easemobImuser.setGroupId(e.getGroupId());
                easemobImuser.setJoinStatus("2");
                easemobImuser.setGroupName(e.getGroupName());
            }
            if (e.getName().equals(company.getName())){
                UserUtils.getUser().setCompany(e);
                easemobImuser.setUserId(id);
                easemobImuser.setGroupId(e.getGroupId());
                easemobImuser.setJoinStatus("2");
                easemobImuser.setGroupName(e.getGroupName());
            }

        }

        easemobInfoService.save(easemobImuser);
        systemService.assignUserToRole(comRole, UserUtils.getUser());
        systemService.outUserInRole(new Role("1"), UserUtils.getUser());
        j.setMsg("您的申请已提交，请在“我的管理企业”中查看结果");
        return j;
    }*/

    /**
     * 根据推送的id拿到申请加入企业的详情，然后进行审批
     */
    @RequestMapping(value = "getJoinCompanyInfo",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getJoinCompanyInfo(HttpServletRequest request){
        AjaxJson ajaxJson = new AjaxJson();
        try {

            Map<String,String> requestMap = findRequestMap(request);
            String companyinfoId = requestMap.get("companyinfoId");
            Useroffice companyinfo  = companyinfoService.get(companyinfoId);
            LinkedHashMap<String,Object> returnMap = new LinkedHashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(companyinfo==null || StringUtils.isBlank(companyinfo.getId())){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("无指定的审批消息或当前审批消息已过时，请刷新后重试!");
                ajaxJson.setErrorCode(ErrorCode.code_2004);
                return ajaxJson ;
            }else{
                String currentComId = UserUtils.getSelectCompany().getId();
                String comId = StringUtils.isBlank(companyinfo.getCompanyId())?"":companyinfo.getCompanyId();

                //如果是申请人只查看,不做审批
                if(StringUtils.isNotBlank(companyinfo.getUserId()) && companyinfo.getUserId().equals(UserUtils.getUser().getId())){
                    ajaxJson.setSuccess(true);
                    ajaxJson.setErrorCode(ErrorCode.code_1004);
                    ajaxJson.setMsg("获取申请详情成功");
                    returnMap.put("userName",(UserUtils.getByUserId(companyinfo.getUserId())!=null)?UserUtils.getByUserId(companyinfo.getUserId()).getName():"");
                    returnMap.put("companyName",(officeService.get(companyinfo.getCompanyId())!=null)?officeService.get(companyinfo.getCompanyId()).getName():"");
                    returnMap.put("remarks",companyinfo.getRemarks());
                    returnMap.put("officeName",(officeService.get(companyinfo.getOfficeId())!=null)?officeService.get(companyinfo.getOfficeId()).getName():"");
                    returnMap.put("status",companyinfo.getStatus());
                    ajaxJson.setBody(returnMap);
                    return ajaxJson;
                }
            }

            if(companyinfo!=null){
                returnMap.put("companyinfoId",companyinfo.getId());
                returnMap.put("userId",companyinfo.getUserId());
                User user = UserUtils.get(companyinfo.getUserId());
                returnMap.put("userName",user!=null?user.getName():"");
                String companyId = companyinfo.getCompanyId();
                //该公司下所有的岗位
                List<Role> roleList = systemService.getRoleList("",companyId);
                Role role = new Role();
                if (roleList!=null && roleList.size()!=0){
                    for (Role r :roleList){
                        //要的是管理员而
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(r.getEnname()) && r.getEnname().endsWith("gly")){
                            role = r;
                            break;
                        }
                    }
                }
                //该公司下拥有管理员岗位的所有员工
                List<User> userList = userDao.findUserByRole(role);
                //该公司下拥有管理员岗位的所有员工
                StringBuilder builder = new StringBuilder();
                if (userList!=null && userList.size()!=0) {
                    for (User u : userList) {
                       if(StringUtils.isNotBlank(u.getId())){
                           builder.append(",").append(u.getId());
                       }
                    }
                }
                String masterIds = "";
                if(builder.length()>2){
                    masterIds = builder.substring(1).toString();
                }
                returnMap.put("masterIds",masterIds);
                returnMap.put("masterName",UserUtils.get(UserUtils.getUser().getId()).getName());
                returnMap.put("companyId",companyId);
                returnMap.put("companyName",UserUtils.getSelectCompany().getName());
                returnMap.put("remarks",companyinfo.getRemarks());
                returnMap.put("status",companyinfo.getStatus());
                returnMap.put("createBy",companyinfo.getCreateBy()!=null?companyinfo.getCreateBy().getId():"");
                returnMap.put("createDate",companyinfo.getCreateDate()!=null?sdf.format(companyinfo.getCreateDate()):"");
                returnMap.put("updateBy",companyinfo.getUpdateBy()!=null?companyinfo.getUpdateBy().getId():"");
                returnMap.put("updateDate",companyinfo.getUpdateDate()!=null?sdf.format(companyinfo.getUpdateDate()):"");
                Pushinfo pushinfo = new Pushinfo();
                pushinfo.setPushId(companyinfoId);
                List<Pushinfo> pushinfos = pushinfoService.getByPushId(pushinfo);
                if (pushinfos!=null && pushinfos.size()!=0) {
                    Pushinfo push = pushinfos.get(0);
                    if (StringUtils.isNotBlank(push.getStatus())&& push.getStatus().equals("1")){
                        returnMap.put("selectStatus", "1");
                        returnMap.put("officeName", companyinfo.getCreateBy().getOffice().getName());
                        returnMap.put("comment", companyinfo.getRemarks());
                        returnMap.put("actStuatus", companyinfo.getStatus());
                    }else {
                        returnMap.put("selectStatus", "0");
                    }
                }else {
                    logger.error("获取申请详情失败");
                    ajaxJson.setSuccess(false);
                    ajaxJson.setErrorCode(ErrorCode.code_2004);
                    ajaxJson.setMsg("获取申请详情失败,当前申请不存在");
                }
            }
            ajaxJson.setSuccess(true);
            ajaxJson.setErrorCode(ErrorCode.code_1004);
            ajaxJson.setMsg("获取申请详情成功");
            ajaxJson.setBody(returnMap);
            return ajaxJson;
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("获取申请详情失败",e);
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("获取申请详情失败");
        }

        return ajaxJson;
    }

    /**
     * 根据Useroffice的id，查询出待办任务
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "getJoinCompanyAct",method = RequestMethod.GET)
    public AjaxJson getJoinCompanyAct(Act act , HttpServletRequest request){
        AjaxJson ajaxJson = new AjaxJson();
        Map<String,String> requestMap = findRequestMap(request);
        String companyinfoId = requestMap.get("companyinfoId");
        if(StringUtils.isBlank(companyinfoId)){
            logger.error("获取审核流程信息失败");
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("获取审批流程信息失败");
        }
        try {
            Useroffice companyinfo = companyinfoService.get(companyinfoId);
            act.setProcDefKey("joincompany");

            List<Act>  actList = actTaskService.todoList(act);
            if(actList!=null && actList.size()>0){
                for(Act a : actList){
                    if(a!=null && a.getProcInsId().equals(companyinfo.getProcessInstanceId())){
                        companyinfo.setAct(a);
                        break;
                    }
                }
            }

            LinkedHashMap<String,Object> map = new LinkedHashMap<>();

            act = companyinfo.getAct();
            String taskDefKey = act.getTaskDefKey();
            if("apply_end".equals(taskDefKey)) {

                List<Map<String,String>> allDeptsList = new ArrayList<>();
                Office office = officeService.get(companyinfo.getCompanyId());
                List<Office> allDepts = officeService.getAllDepts(office.getId());
                if(allDepts!=null && allDepts.size()>0){
                    for(Office o : allDepts){
                        Map<String,String> officeMap = new HashMap<>();
                        officeMap.put("officeId",o.getId());
                        officeMap.put("officeName",o.getName());
                        allDeptsList.add(officeMap);
                    }
                }
                User master = UserUtils.getUser();//审批人
                companyinfo.setAct(act);
                companyinfo.setMaster(master.getId());
                String companyId = UserUtils.getSelectCompany().getId();
                Role roles = new Role();
                roles.setCompany(new Office(companyId));
                List<Map<String,String>> allRolesList = new ArrayList<>();
                List<Role> allRoles = UserUtils.getRoleListByCompany(roles);
                if(allRoles!=null && allRoles.size()>0){
                    for(Role r : allRoles){
                        Map<String,String> roleMap = new HashMap<>();
                        roleMap.put("roleId",r.getId());
                        roleMap.put("roleName",r.getName());
                        allRolesList.add(roleMap);
                    }
                }
                companyinfoService.save(companyinfo);//更新操作
                map.put("companyinfoId",companyinfoId);
                map.put("masterId",master.getId());//审批人
                map.put("masterName",master.getName());
                map.put("companyId", office.getId());//公司
                map.put("companyName", office.getName());
                map.put("allDeptsList",allDeptsList);
                map.put("allRolesList", allRolesList);
                ajaxJson.setBody(map);
                ajaxJson.setMsg("获取审批流程信息成功");
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setSuccess(true);
            }else{
                ajaxJson.setMsg("没有待审批任务");
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取审批流程信息失败",e);
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("获取审批流程信息失败");
        }
        return ajaxJson;
    }

    /**
     *  保存审核信息
     */
    @Transactional
    @RequestMapping("saveJoinCompanyAct")
    @ResponseBody
    public AjaxJson saveJoinCompanyAct(Act act,HttpServletRequest request){
        AjaxJson ajaxJson = new AjaxJson();
        Map<String,String> requestMap = findRequestMap(request);
        LinkedHashMap<String,Object> map = new LinkedHashMap<>();
        LinkedHashMap returnMap = new LinkedHashMap();
        try {
            lock.lock();
            String companyinfoId = requestMap.get("companyinfoId");

            String roleId = requestMap.get("roleId");
            String flag = requestMap.get("flag");//['同意','拒绝']
            String comment = requestMap.get("comment");
            Useroffice useroffice = companyinfoService.get(companyinfoId);
            act.setProcDefKey("joincompany");
            List<Act>  actList = actTaskService.todoList(act);
            if(actList!=null && actList.size()>0){
                for(Act a : actList){
                    if(a!=null && a.getProcInsId().equals(useroffice.getProcessInstanceId())){
                        a.setFlag(flag);
                        a.setComment(comment);
                        useroffice.setAct(a);
                        break;
                    }
                }
            }
            User master = UserUtils.getUser();
            returnMap.put("flag",flag);
            returnMap.put("joinUserId",useroffice.getUserId());
            returnMap.put("joinUserName",UserUtils.get(useroffice.getUserId()).getName());
            returnMap.put("masterId",master.getId());//审批人
            returnMap.put("masterName",master.getName());
            returnMap.put("comment",comment);
            returnMap.put("status","0");
            if(!"yes".equals(flag)){
                companyinfoService.auditSave(useroffice);
                ajaxJson.setBody(returnMap);
                ajaxJson.setErrorCode("0000");
                ajaxJson.setMsg("审批拒绝");
                ajaxJson.setSuccess(false);
            }else {
                String companyId = useroffice.getCompanyId();
                List<Company> companyList = companyService.getByCompany(companyId);
                Company company = new Company();
                if (companyList != null && companyList.size() != 0) {
                    company = companyList.get(0);
                }
                returnMap.put("companyId",company.getId());
                returnMap.put("companyName",company.getName());
                Role comRole = new Role();
                List<Role> roleList = systemService.getRoleList("",companyId);
                if (StringUtils.isNotBlank(roleId) && roleList!=null && roleList.size()!=0){
                    comRole = systemService.getRole(roleId);
                    if(!roleList.contains(comRole)){
                        comRole = systemService.getRoleByEnname( companyId,comRole.getOffice(),"yg");
                    }
                }else {
                    comRole = systemService.getRoleByEnname( companyId, null,"yg");
                }

                useroffice.setRoleList(roleList);
                Office office = officeService.get(comRole.getOffice());
                returnMap.put("roleId",comRole.getId());
                returnMap.put("roleName",comRole.getName());
                returnMap.put("officeId",office.getId());
                returnMap.put("officeName",office.getName());
                String[] extra = new String[4];
                extra[0] = useroffice.getUserId();
                extra[1] = companyId;
                extra[2] = comRole.getId();//不能直接用roleId
                extra[3] = office.getId();//不能直接用roleId
                companyinfoService.auditSave(useroffice,extra);
                ajaxJson.setBody(returnMap);
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setMsg("审批通过");
                ajaxJson.setSuccess(true);
            }

        }catch (Exception e){
            logger.error("审批失败",e);
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("审批失败");
            ajaxJson.setBody(map);
        }finally {
            lock.unlock();
        }
        return ajaxJson;
    }
}
