/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workchangejob.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.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
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.dao.WorkChangeJobUserDao;
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.WorkOfficeChange;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeUserService;
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.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.workchangejob.entity.WorkChangeJob;
import com.jeeplus.modules.workchangejob.dao.WorkChangeJobDao;

/**
 * 职级调整Service
 * @author chenyuping
 * @version 2018-08-02
 */
@Service
@Transactional(readOnly = true)
public class WorkChangeJobService extends CrudService<WorkChangeJobDao, WorkChangeJob> {
	@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 WorkChangeJobUserDao workChangeJobUserDao;
	@Autowired
	protected WorkStaffBasicInfoDao workStaffBasicInfoDao;
	@Autowired
	protected WorkChangeJobUserService workChangeJobUserService;
	@Autowired
	protected WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	protected WorkJobGradeDao workJobGradeDao;

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

	/**
	 * 获取列表
	 * @param workChangeJob
	 * @return
	 */
	public List<WorkChangeJob> findList(WorkChangeJob workChangeJob) {
		return super.findList(workChangeJob);
	}
	/**
	 * 根据业务权限获取分页数据
	 * @param workChangeJob
	 * @return
	 */
	public Page<WorkChangeJob> findPage(Page<WorkChangeJob> page, WorkChangeJob workChangeJob) {
		workChangeJob.getSqlMap().put("dsf", dataScopeFilter(workChangeJob.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CHANGEJOB.getValue()));
		int count = dao.queryCount(workChangeJob);
		page.setCount(count);
		page.setCountFlag(false);
		workChangeJob.setPage(page);
		page.setList(findList(workChangeJob));
		return page;
	}
	/**
	 * 保存
	 * @param workChangeJob
	 * @return
	 */
	@Transactional(readOnly = false)
	public void save(WorkChangeJob workChangeJob) {
		super.save(workChangeJob);
		updateWorkOfficeChangeList(workChangeJob);
	}
	/**
	 * 保存子表数据
	 * @param workChangeJob
	 * @return
	 */
	@Transactional(readOnly = false)
	public void updateWorkOfficeChangeList(WorkChangeJob workChangeJob) {
		if(workChangeJob.getWorkChangeJobUserList()!=null&&workChangeJob.getWorkChangeJobUserList().size()>0){
			for (WorkChangeJobUser workChangeJobUser :workChangeJob.getWorkChangeJobUserList()) {
				if (StringUtils.isBlank(workChangeJobUser.getId()) ) {
					if(StringUtils.isNotBlank(workChangeJobUser.getBasicInfoId())){
						workChangeJobUser.preInsert();
						workChangeJobUser.setChangeId(workChangeJob.getId());
						workChangeJobUser.setOfficeId(workChangeJob.getOfficeId());
						workChangeJobUser.setCompanyId(workChangeJob.getCompanyId());
						workChangeJobUserDao.insert(workChangeJobUser);
					}
				} else {
					if (StringUtils.isNotBlank(workChangeJobUser.getBasicInfoId())) {
						workChangeJobUser.preUpdate();
						workChangeJobUser.setOfficeId(workChangeJob.getOfficeId());
						workChangeJobUser.setChangeId(workChangeJob.getId());
						workChangeJobUser.setCompanyId(workChangeJob.getCompanyId());
						workChangeJobUserDao.update(workChangeJobUser);
					}
				}
				//更新work_staff_basic_info表的职级
				String after_jobGrade = workChangeJobUser.getAfter();
				String userId = workChangeJobUser.getUserId();
				workStaffBasicInfoDao.updateJobGradeByUserId(userId, after_jobGrade);
			}
		}
	}
	/**
	 * 保存并启动流程
	 * @param workChangeJob
	 * @return
	 */
	@Transactional(readOnly = false)
	public String saveChange(WorkChangeJob workChangeJob) {
		if(StringUtils.isBlank(workChangeJob.getNumber())){
			User createBy = workChangeJob.getCreateBy();
			if(createBy != null){
				createBy = UserUtils.get(createBy.getId());
			}else {
				createBy = UserUtils.getUser();
				workChangeJob.setCreateBy(createBy);
			}
			workChangeJob.setNumber(serialNumTplService.genSerialNum(createBy.getCompany(),"20"));
		}
		this.save(workChangeJob);
		return this.startAudit(workChangeJob,workChangeJob.getProcessInstanceId());
	}

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

			List<User> users = new ArrayList<>();
			List<User> rszrList = UserUtils.findRszrList(createUser);
//			List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"23",workChangeJob.getCreateBy());
//			List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"23",workChangeJob.getCreateBy());
			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(),"23",workChangeJob.getCreateBy());
						if (enusers.size()==0){
							workChangeJob.setState("1");
							this.save(workChangeJob);
							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(),"23",workChangeJob.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (rszrList.size()==0 ){
					workChangeJob.setState("1");
					this.save(workChangeJob);
					return "流程审批人不能为空,,请联系管理员！";
				}
				variables.put("bmzrList", rszrList);
				variables.put("bmzrCount",rszrList.size());
				processType = "rankAdjust";
				users.addAll(rszrList);
			}
			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","70");
//				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", "审批单：" +"调整人："+ workChangeJob.getUserName());//设置标题；

			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(rszrList,processInstance.getId(),1,1);
//				workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
//				workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),3,0);
			}
			workChangeJob.setProcessInstanceId(processInstance.getId());
			workChangeJob.setState("2");
			dao.updateProcessInstanceId(workChangeJob);
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}

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

		if (StringUtils.isBlank(act.getComment())){
			act.setComment(flag.equals("yes")?"同意":"驳回");
		}
		String comment = "";
		if (workChangeJob.getState().equals("4")){
			comment = ("yes".equals(flag)?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(flag)?"[同意] ":"[驳回] ")+act.getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workChangeJob.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(workChangeJob.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(workChangeJob.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("rankAdjust")) {
			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");
						workChangeJob.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)) {
						workChangeJob.setState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("rankAdjust");
			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)) {
						notifyRole = "审批通过";
						//修改职级
						if(workChangeJob.getWorkChangeJobUserList()!=null&&workChangeJob.getWorkChangeJobUserList().size()>0){
							for(WorkChangeJobUser workChangeJobUser:workChangeJob.getWorkChangeJobUserList()){
								WorkStaffBasicInfo workStaffBasicInfo=workStaffAchivesDao.get(workChangeJobUser.getBasicInfoId());
								WorkJobGrade workJobGrade=workJobGradeDao.get(workChangeJobUser.getAfter());
								if(workJobGrade!=null){
									workStaffBasicInfo.setJobGrade(workJobGrade);
									workStaffBasicInfo.setSalary(workJobGrade.getPay());
									workStaffAchivesDao.update(workStaffBasicInfo);
								}

							}
						}
						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)) {
						workChangeJob.setState("3");
					}
					break;
				}
			}
		}
		// 设置意见
		act.setComment(("yes".equals(flag) ? "[同意] " : "[驳回] ") + act.getComment());
		workChangeJob.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(flag) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workChangeJob.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(workChangeJob.getCreateBy());
			if ("yes".equals(flag)) {
				str =  "调整人："+ workChangeJob.getUserName();
				workChangeJob.setState("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workChangeJob.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workChangeJob.getId(),
										workChangeJob.getCreateBy(),
										workChangeJob.getCompanyId(),
										title,
										str,
										"70",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workChangeJob.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workChangeJob.getState()) && !workChangeJob.getState().equals("3")){
					workChangeJob.setState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workChangeJob.getId(),
											workChangeJob.getCreateBy(),
											workChangeJob.getCompanyId(),
											title,
											str,
											"70",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workChangeJob.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("rankAdjust")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workChangeJob.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workChangeJob.getId(),
								new User(),
								workChangeJob.getCompanyId(),
								title,
								str,
								"70",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						flag,
						taskCount,
						workChangeJob.getCreateBy(),
						workChangeJob.getOfficeId(),
						"70");
				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(workChangeJob.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workChangeJob.getId(),
											workChangeJob.getCreateBy(),
											workChangeJob.getCompanyId(),
											title,
											str,
											"70",
											"0",
											"重新申请",
											notifyRole));
					users.add( workChangeJob.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workChangeJob.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workChangeJob.getId(),
										new User(),
										workChangeJob.getCompanyId(),
										title,
										str,
										"70",
										"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","70");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(title,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workChangeJob.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(workChangeJob.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workChangeJob.getId(),
												workChangeJob.getCreateBy(),
												workChangeJob.getCompanyId(),
												title,
												str,
												"70",
												"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(workChangeJob);
		return "保存审核意见成功！";
	}
	/**
	 * 撤回申请
	 * @return
	 */
	@Transactional(readOnly = false)
	public void cancelProcess(String id) throws Exception {
		WorkChangeJob workChangeJob = this.get(id);
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workChangeJob.getProcessInstanceId());
		process.setIsApproval("0");
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workChangeJob.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workChangeJob.getId());
		List<User> userList = workProjectNotifyService.readByNotifyId(notify);
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushIm(u.getId(),"调转人:"+ workChangeJob.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);

			//结束该流程,设为"撤销"状态月
			WorkChangeJob changeJob = new WorkChangeJob();
			changeJob.setId(id);
			changeJob.setState("3");
			changeJob.setProcessInstanceId(workChangeJob.getProcessInstanceId());
			changeJob.preUpdate();
			this.updateStateById(changeJob);
			actTaskService.endProcessInstance(changeJob.getProcessInstanceId(), "调转申请-撤回");
		}
	}
	private void updateStateById(WorkChangeJob workChangeJob) {
		dao.updateProcessInstanceId(workChangeJob);
	}

	@Transactional(readOnly = false)
	public WorkStaffBasicInfo getWorkStaffBasicInfo(String userId) {
		WorkStaffBasicInfo w=workStaffAchivesDao.getWorkStaffBasicInfo(userId);
		return w;
	}
	/**
	 * 删除
	 * @param workChangeJob
	 * @return
	 */
	@Transactional(readOnly = false)
	public void delete(WorkChangeJob workChangeJob) {
		super.delete(workChangeJob);
		if(workChangeJob.getWorkChangeJobUserList()!=null&&workChangeJob.getWorkChangeJobUserList().size()>0){
			for(WorkChangeJobUser workChangeJobUser:workChangeJob.getWorkChangeJobUserList()){
				workChangeJobUserDao.delete(workChangeJobUser);
			}
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workChangeJob.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}
	
	
	
	
}