/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workofficechange.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
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.SystemService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.dao.UserofficeDao;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workchangejob.entity.WorkChangeJobUser;
import com.jeeplus.modules.workjobgrade.dao.WorkJobGradeDao;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workofficechange.dao.WorkOfficeChangeUserDao;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workregularapply.entity.WorkRegularApply;
import com.jeeplus.modules.workregularapply.entity.WorkRegularScore;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.dao.WorkStaffBasicInfoDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChange;
import com.jeeplus.modules.workofficechange.dao.WorkOfficeChangeDao;

/**
 * 部门调转Service
 * @author chenyuping
 * @version 2018-08-01
 */
@Service
@Transactional(readOnly = true)
public class WorkOfficeChangeService extends CrudService<WorkOfficeChangeDao, WorkOfficeChange> {
	@Autowired
	private UserDao userDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	protected WorkOfficeChangeUserDao workOfficeChangeUserDao;
	@Autowired
	protected WorkStaffBasicInfoDao workStaffBasicInfoDao;
	@Autowired
	protected WorkOfficeChangeUserService workOfficeChangeUserService;
	@Autowired
	protected SystemService systemService;
	@Autowired
	protected UserofficeDao userofficeDao;
	@Autowired
	protected RoleDao roleDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private WorkJobGradeDao workJobGradeDao;
	@Autowired
	private UserService userService;

	public WorkOfficeChange get(String id) {
		return super.get(id);
	}

	/**
	 * 获取列表
	 * @param workOfficeChange
	 * @return
	 */
	public List<WorkOfficeChange> findList(WorkOfficeChange workOfficeChange) {
		return super.findList(workOfficeChange);
	}
	/**
	 *权限范围内的数据
	 * @param workOfficeChange
	 * @return
	 */
	public Page<WorkOfficeChange> findPage(Page<WorkOfficeChange> page, WorkOfficeChange workOfficeChange) {
		workOfficeChange.getSqlMap().put("dsf", dataScopeFilter(workOfficeChange.getCurrentUser(), "o", "u","s", MenuStatusEnum.OFFICE_CHANGE.getValue()));
		int count = dao.queryCount(workOfficeChange);
		page.setCount(count);
		page.setCountFlag(false);
		workOfficeChange.setPage(page);
		page.setList(findList(workOfficeChange));
		return page;
	}

	/**
	 * 保存
	 * @param workOfficeChange
	 */
	@Transactional(readOnly = false)
	public void save(WorkOfficeChange workOfficeChange) {
		super.save(workOfficeChange);
		updateWorkOfficeChangeList(workOfficeChange);
	}
	/**
	 * 保存调整明细
	 * @param workOfficeChange
	 * @return
	 */
	@Transactional(readOnly = false)
	public void updateWorkOfficeChangeList(WorkOfficeChange workOfficeChange) {
		if (workOfficeChange.getWorkOfficeChangeUserList() != null && workOfficeChange.getWorkOfficeChangeUserList().size() > 0) {
			String officeId = workOfficeChange.getChangeOffice();
            for (WorkOfficeChangeUser workOfficeChangeUser : workOfficeChange.getWorkOfficeChangeUserList()) {
				if (StringUtils.isBlank(workOfficeChangeUser.getId())) {
					if (StringUtils.isNotBlank(workOfficeChangeUser.getBasicInfoId())) {
						workOfficeChangeUser.preInsert();
						workOfficeChangeUser.setChangeId(workOfficeChange.getId());
						workOfficeChangeUser.setOfficeId(workOfficeChange.getOfficeId());
						User user = userDao.get(workOfficeChangeUser.getUserId());
						if (user != null) {
							workOfficeChangeUser.setOldOfficeId(user.getOffice().getId());
							workOfficeChangeUser.setOldOfficeName(user.getOffice().getName());
						}
						workOfficeChangeUser.setCompanyId(workOfficeChange.getCompanyId());
						workOfficeChangeUserDao.insert(workOfficeChangeUser);
					}
				} else {
					if (StringUtils.isNotBlank(workOfficeChangeUser.getBasicInfoId())) {
						workOfficeChangeUser.preUpdate();
						workOfficeChangeUser.setOfficeId(workOfficeChange.getOfficeId());
						workOfficeChangeUser.setChangeId(workOfficeChange.getId());
						User user = userDao.get(workOfficeChangeUser.getUserId());
						if (user != null) {
							workOfficeChangeUser.setOldOfficeId(user.getOffice().getId());
							workOfficeChangeUser.setOldOfficeName(user.getOffice().getName());
						}
						workOfficeChangeUser.setCompanyId(workOfficeChange.getCompanyId());
						workOfficeChangeUserDao.update(workOfficeChangeUser);
					}
				}
				//更新新职级和新部门
				String userId = workOfficeChangeUser.getUserId();
				String jobGradeId = workOfficeChangeUser.getJobGrade2().getId();
				workStaffBasicInfoDao.updateJobGradeByUserId(userId,jobGradeId);
                //新岗位
                roleDao.updateRoleByUserId(workOfficeChange.getRoleId(),userId);
				//新部门
				workStaffBasicInfoDao.updateOfficeByUserId(userId,officeId);
				//更新user表的officeId
				User user =  new User();
				user.setId(userId);
                Office office = new Office();
                office.setId(officeId);
                user.setOffice(office);
				userService.updateUser(user);
			}
		}
	}
	/**
	 * 删除
	 * @param workOfficeChange
	 * @return
	 */
	@Transactional(readOnly = false)
	public void delete(WorkOfficeChange workOfficeChange) {
		super.delete(workOfficeChange);
		if(workOfficeChange.getWorkOfficeChangeUserList()!=null&&workOfficeChange.getWorkOfficeChangeUserList().size()>0){
			for(WorkOfficeChangeUser workOfficeChangeUser:workOfficeChange.getWorkOfficeChangeUserList()){
				workOfficeChangeUserDao.delete(workOfficeChangeUser);
			}
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workOfficeChange.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}



	@Transactional(readOnly = false)
	public WorkStaffBasicInfo getWorkStaffBasicInfo(String userId) {
		WorkStaffBasicInfo w=workStaffAchivesDao.getWorkStaffBasicInfo(userId);
		return w;
	}
	/**
	 * 保存并启动流程
	 * @param workOfficeChange
	 * @return
	 */
	@Transactional(readOnly = false)
	public String saveChange(WorkOfficeChange workOfficeChange) {
		if(StringUtils.isBlank(workOfficeChange.getNumber())){
			User createBy = workOfficeChange.getCreateBy();
			if(createBy != null){
				createBy = UserUtils.get(createBy.getId());
			}else {
				createBy = UserUtils.getUser();
				workOfficeChange.setCreateBy(createBy);
			}
//			业务标识20:  -> 默认部门调转编号模板:
			workOfficeChange.setNumber(serialNumTplService.genSerialNum(createBy.getCompany(),"20"));
		}
		this.save(workOfficeChange);
		return this.startAudit(workOfficeChange,workOfficeChange.getProcessInstanceId());
	}

	/**
	 * 启动审批流程
	 */
	@Transactional(readOnly = false)
	public String startAudit(WorkOfficeChange workOfficeChange, String processInstanceId){
		try{
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(workOfficeChange.getCurrentUser().getId());
			User createUser = UserUtils.getUser();
			String contentStr = "转入部门："+ workOfficeChange.getChangeOfficeName()+"，调转日期："+ DateUtils.formatDate(workOfficeChange.getChangeDate());
			String titleStr = "转入部门："+ workOfficeChange.getChangeOfficeName();
			String businessKey = workOfficeChange.getId();
			Office office = UserUtils.getSelectOffice();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("bmdz3125f1f194c87u7ua9miiii750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workOfficeChange.getId(),
							null,
							workOfficeChange.getCompanyId(),
							titleStr,
							contentStr,
							"68",
							"0",
							"待审批",
							""
					);

			List<User> users = new ArrayList<>();
			String oldOfficeId = workOfficeChange.getWorkOfficeChangeUserList().get(0).getOldOfficeId();
			String newOfficeId = workOfficeChange.getChangeOffice();
			List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr",2,oldOfficeId,"24",workOfficeChange.getCreateBy()); //原部门负责人
			List<User> fgldList = UserUtils.getByRoleActivityEnname("bmzr",2,newOfficeId,"24",workOfficeChange.getCreateBy());  //现部门负责人
			List<User> zjlList = UserUtils.findRszrList(createUser); //人事主任
			if (StringUtils.isNotBlank(workActivityMenu.getId())) {
				workProjectNotify.setNotifyRole("");
				workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
				List<Activity> activities = workActivityMenu.getActivities();
				for (Activity a : activities) {
					String encount = a.getEncount();
					String enlist = a.getEnlist();
					if (a.getRole()!=null && StringUtils.isNotBlank(a.getRole().getEnname())){
						List enusers = UserUtils.getByRoleActivityEnnames(a.getRole().getEnname(),office.getId(),"24",workOfficeChange.getCreateBy());
						if (enusers.size()==0){
							workOfficeChange.setState("1");
							this.save(workOfficeChange);
							return "流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！";
						}
						variables.put(enlist, enusers);
						variables.put(encount, enusers.size());
					}
					if (a.getDelFlag().equals("0") && a.getCount() == 1) {
						activity = a;
					}
				}
				buffer.append(activity.getRole().getEnname());
				if (activity != null && StringUtils.isNotBlank(activity.getId())) {
					//角色审批
					if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
						users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),office.getId(),"24",workOfficeChange.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				variables.put("bmzrList", bmzrList);
				if (bmzrList.size()==0 ){
					workOfficeChange.setState("1");
					this.save(workOfficeChange);
					return "流程审批人不能为空,请联系管理员！";
				}
				variables.put("bmzrCount",bmzrList.size());
				processType = "jobChange";
				users.addAll(bmzrList);
			}
			List<String> userIds = new ArrayList<>(users.size());
			for (User u : users){
				userIds.add(u.getId());
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotify.setNotifyRole("现部门主任审核");
				workProjectNotifyService.save(workProjectNotify);
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("procDefKey","68");
				extras.put("id",workProjectNotify.getId());
				UserUtils.pushInfoToApp(titleStr, contentStr,extras,u.getId());
			}
			UserUtils.pushIm(userIds,contentStr);

			variables.put("busId", businessKey);
			variables.put("type", processType);
			variables.put("title", "审批单：" +"转入部门："+workOfficeChange.getChangeOfficeName());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey(processType);
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(3);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.insertAuditsByType(bmzrList,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
				workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),3,0);
			}
			workOfficeChange.setProcessInstanceId(processInstance.getId());
			workOfficeChange.setState("2");
			dao.updateProcessInstanceId(workOfficeChange);
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkOfficeChange workOfficeChange, List<User> auditUsers) {
		String flag = workOfficeChange.getAct().getFlag();
		// 对不同环节的业务逻辑进行操作
		Act act = workOfficeChange.getAct();
		String taskDefKey = act.getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")  ) {
			actTaskService.claim(act.getTaskId(), UserUtils.getUser().getId());
		}else {
			flag = "yes";
			this.save(workOfficeChange);
		}
		String title = "转入部门:"+workOfficeChange.getChangeOfficeName();
		String str =  "转入部门:"+workOfficeChange.getChangeOfficeName();

		if (StringUtils.isBlank(act.getComment())){
			act.setComment(flag.equals("yes")?"同意":"驳回");
		}
		String comment = "";
		if (workOfficeChange.getState().equals("4")){
			comment = ("yes".equals(flag)?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(flag)?"[同意] ":"[驳回] ")+act.getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workOfficeChange.setState(("yes".equals(flag) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(workOfficeChange.getProcessInstanceId());
		WorkActivityMenu workActivityMenu = new WorkActivityMenu();
		if (activitieList != null && activitieList.size() != 0) {
			workActivityMenu.setProcessType(activitieList.get(0).getProcessKey());
			workActivityMenu.setActivities(activitieList);
		}

		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		WorkActivityProcess selectProcess = new WorkActivityProcess();
		selectProcess.setProcessInstanceId(workOfficeChange.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("jobChange")) {
			key = 1;
			for (int i = 0; i < workActivityProcesses.size(); i++) {
				WorkActivityProcess activityProcess = workActivityProcesses.get(i);
				if (taskDefKey.equals(activityProcess.getActivityTask()) && !taskDefKey.equals("modifyApply")) {
					taskCount = activityProcess.getCount()+"";
					workActivityProcess = activityProcess;
					if (!workActivityProcess.getIsApproval().equals("0")) {
						workActivityProcess.setId("");
					}
					exp = "pass";
					if (!"yes".equals(flag)) {
						workActivityProcess.setIsApproval("2");
						workOfficeChange.setState("4");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}

					} else {
						workActivityProcess.setIsApproval("1");
					}
				}else if(taskDefKey.equals("modifyApply")){
					notifyRole = "调整申请";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(flag)) {
						workOfficeChange.setState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("jobChange");
			for (int i = 0; i < workActivityProcesses.size(); i++) {
				WorkActivityProcess activityProcess = workActivityProcesses.get(i);
				String count = activityProcess.getCount() + "";
				workActivityProcess = activityProcess;
				if (!workActivityProcess.getIsApproval().equals("0")) {
					workActivityProcess.setId("");
				}
				// 审核环节
				if ("bmzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(flag)) {
						vars.put("fgldList", auditUsers);
						vars.put("fgldCount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workOfficeChange.getProcessInstanceId(),2,1);
						notifyRole = "新部门主任审核";
						workActivityProcess.setIsApproval("1");
						enname = "fgld";
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}
				// 审核环节
				else if ("fgld".equals(taskDefKey) && count.contains("2")) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(flag)) {
						vars.put("zjlList", auditUsers);
						vars.put("zjlCount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workOfficeChange.getProcessInstanceId(),3,1);
						notifyRole = "人事主任审核";
						workActivityProcess.setIsApproval("1");
						enname = "zjl";
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("zjl".equals(taskDefKey) && count.contains("3")) {
					taskCount = "3";
					exp = "pass";
					if ("yes".equals(flag)) {
						notifyRole = "审批通过";
						this.changeOffice(workOfficeChange);
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}  else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "现部门主任审核";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(flag)) {
						workOfficeChange.setState("3");
					}
					break;
				}
			}
		}
		// 设置意见
		act.setComment(("yes".equals(flag) ? "[同意] " : "[驳回] ") + act.getComment());
		workOfficeChange.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(flag) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workOfficeChange.getProcessInstanceId(),taskDefKey,"modifyApply",flag,comment, activities);
		// 提交流程任务
		actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
		boolean state = actTaskService.isProcessEnd(act.getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
			users.add(workOfficeChange.getCreateBy());
			if ("yes".equals(flag)) {
				str =  "转入部门:"+workOfficeChange.getChangeOfficeName();
				workOfficeChange.setState("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workOfficeChange.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workOfficeChange.getId(),
										workOfficeChange.getCreateBy(),
										workOfficeChange.getCompanyId(),
										title,
										str,
										"68",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workOfficeChange.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workOfficeChange.getState()) && !workOfficeChange.getState().equals("3")){
					workOfficeChange.setState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workOfficeChange.getId(),
											workOfficeChange.getCreateBy(),
											workOfficeChange.getCompanyId(),
											title,
											str,
											"68",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workOfficeChange.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("jobChange")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workOfficeChange.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workOfficeChange.getId(),
								new User(),
								workOfficeChange.getCompanyId(),
								title,
								str,
								"68",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						flag,
						taskCount,
						workOfficeChange.getCreateBy(),
						workOfficeChange.getOfficeId(),
						"68");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService
							.save(workProjectNotify1);
				}

			} else {
				if (!"yes".equals(flag)) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workOfficeChange.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workOfficeChange.getId(),
											workOfficeChange.getCreateBy(),
											workOfficeChange.getCompanyId(),
											title,
											str,
											"68",
											"0",
											"重新申请",
											notifyRole));
					users.add( workOfficeChange.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workOfficeChange.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workOfficeChange.getId(),
										new User(),
										workOfficeChange.getCompanyId(),
										title,
										str,
										"68",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1 : users) {
							workProjectNotify.setUser(user1);
							workProjectNotify.setId("");
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							Map<String,Object> extras = new HashMap<>();
							extras.put("type","7001");
							extras.put("procDefKey","68");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(title,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workOfficeChange.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(workOfficeChange.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workOfficeChange.getId(),
												workOfficeChange.getCreateBy(),
												workOfficeChange.getCompanyId(),
												title,
												str,
												"68",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}
		if (users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),title);
			}
		}
		if (users!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
		dao.update(workOfficeChange);
		return "保存审核意见成功！";
	}
	/**
	 * 撤回申请
	 * @return
	 */
	@Transactional(readOnly = false)
	public void cancelProcess(String id) throws Exception {
		WorkOfficeChange workOfficeChange = this.get(id);
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workOfficeChange.getProcessInstanceId());
		process.setIsApproval("0");
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workOfficeChange.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workOfficeChange.getId());
		List<User> userList = workProjectNotifyService.readByNotifyId(notify);
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				User user = UserUtils.get(u.getId());
				UserUtils.pushIm(u.getId(),"调转人:"+ workOfficeChange.getUserName() +" 强制撤销!");
			}
		}
		if(processList!=null && processList.size()>0){
			for (int i =0;i<processList.size();i++) {
				WorkActivityProcess p = processList.get(i);
				if(StringUtils.isNotBlank(p.getIsApproval()) && "0".equals(p.getIsApproval())){
					p.setIsApproval("-1");
					p.setDelFlag("1");
					workActivityProcessDao.updateDelFlagAndIsApproval(p);
				}
			}
			WorkActivityProcess pro = new WorkActivityProcess();
			pro.setId("");
			pro.setDelFlag("0");
			pro.preInsert();
			pro.setRemarks("[强制撤销]");
			pro.setProcessKey(processList.get(0).getProcessKey());
			pro.setIsApproval("1");
			pro.setProcessInstanceId(processList.get(0).getProcessInstanceId());
			pro.setCount(0);
			workActivityProcessDao.insert(pro);

			//结束该流程,设为"撤销"状态月
			WorkOfficeChange officeChange = new WorkOfficeChange();
			officeChange.setId(id);
			officeChange.setState("3");
			officeChange.setProcessInstanceId(workOfficeChange.getProcessInstanceId());
			officeChange.preUpdate();
			this.updateStateById(officeChange);
			actTaskService.endProcessInstance(officeChange.getProcessInstanceId(), "调转申请-撤回");
		}
	}
	private void updateStateById(WorkOfficeChange workOfficeChange) {
		dao.updateProcessInstanceId(workOfficeChange);
	}
/*
* 部门调转后更改调转成员相关数据
* */
	private  void changeOffice(WorkOfficeChange workOfficeChange){
		if(workOfficeChange.getWorkOfficeChangeUserList()!=null&&workOfficeChange.getWorkOfficeChangeUserList().size()>0){
			for (WorkOfficeChangeUser workOfficeChangeUser:workOfficeChange.getWorkOfficeChangeUserList()){
				User user=userDao.get(workOfficeChangeUser.getUserId());//修改人员表office
				Office office=officeDao.get(workOfficeChange.getChangeOffice());
				WorkStaffBasicInfo workStaffBasicInfo=	workStaffAchivesDao.get(workOfficeChangeUser.getBasicInfoId());
				if(!workStaffBasicInfo.getOffice().getId().equals(workOfficeChange.getChangeOffice())){//如果该人员已在本部门不做修改
					if(user!=null){
						//清缓存
						systemService.saveCurrentCompanyById(workOfficeChangeUser.getUserId(),user.getCompany().getId(),user.getOffice().getId());
						//判断
						//修改sys_user_office
						Useroffice useroffice=new Useroffice();
						useroffice.setUserId(workOfficeChangeUser.getUserId());
						useroffice.setCompanyId(workStaffBasicInfo.getCompany().getId());
						useroffice.setOfficeId(workOfficeChange.getChangeOffice());
						Useroffice useroffice1=userofficeDao.findOfficeId(useroffice);
						if(useroffice1 != null) {
							if (useroffice1.getOfficeId().equals(user.getOffice().getId())) {
								user.setId(workOfficeChangeUser.getUserId());
								user.setOffice(office);
								userDao.update(user);
							}
						}
						userofficeDao.updateOffice(useroffice);
						//在新部门增加默认岗位
//						Role r=new Role();
//						r.setOffice(office);
//						r.setName("员工");
//						r.setEnname("yg");
//						List<Role> list=new ArrayList<>();
//						Role role=roleDao.getRoleByOfficeId(r);
//						if(role!=null){
//							list.add(role);
//							User uu=new User();
//							uu.setId(workOfficeChangeUser.getUserId());
//							uu.setRoleList(list);
//							//查询是否存在员工岗位
//							List userRole=userDao.findUserRole(workOfficeChangeUser.getUserId(),role.getId());
//							if(userRole==null||list.size() ==0 ){
//								userDao.insertUserRole(uu);
//							}
//						}

					}
					//修改入职登记表office
					workStaffBasicInfo.setId(workOfficeChangeUser.getBasicInfoId());
					workStaffBasicInfo.setOffice(office);
					workStaffAchivesDao.update(workStaffBasicInfo);
				}
				//如果新职级不为空
				if(workOfficeChangeUser.getJobGrade2().getId()!=null&&!"".equals(workOfficeChangeUser.getJobGrade2().getId())){
					WorkJobGrade workJobGrade=workJobGradeDao.get(workOfficeChangeUser.getJobGrade2().getId());
					workStaffBasicInfo.setJobGrade(workJobGrade);
					workStaffBasicInfo.setSalary(workJobGrade.getPay());
					workStaffAchivesDao.update(workStaffBasicInfo);
				}
			}
			String userId = workOfficeChange.getWorkOfficeChangeUserList().get(0).getUserId();
			String roleId = workOfficeChange.getRoleId();
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setUserId(userId);
			workStaffBasicInfo.setRoleId(roleId);
			userService.updateRole(workStaffBasicInfo);
		}

	}
}