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

import java.util.*;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.iim.entity.LayGroup;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
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.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
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.workclientinfo.dao.WorkClientAttachmentDao;
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 com.jeeplus.modules.workreimbursement.dao.ReimbursementVATTaxDao;
import com.jeeplus.modules.workreimbursement.dao.WorkAccountDao;
import com.jeeplus.modules.workreimbursement.dao.WorkReimbursementDao;
import com.jeeplus.modules.workresignationtemplate.dao.WorkResignationTemplateDao;
import com.jeeplus.modules.workresignationtemplate.entity.WorkResignationTemplate;
import com.jeeplus.modules.workresignationtemplate.service.WorkResignationTemplateService;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.*;
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.workresignation.entity.WorkResignation;
import com.jeeplus.modules.workresignation.dao.WorkResignationDao;

/**
 * 离职申请Service
 * @author rh
 * @version 2018-08-04
 */
@Service
@Transactional(readOnly = true)
public class WorkResignationService extends CrudService<WorkResignationDao, WorkResignation> {
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private SystemService systemService;
	@Autowired
	private UserDao userDao;

	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkResignationDao workResignationDao;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private LayGroupService layGroupService;

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkResignationTemplateDao workResignationTemplateDao;
	@Autowired
	private CompanyinfoService companyinfoService;

	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkResignationTemplateService workResignationTemplateService;
	@Autowired
	private PushinfoService pushinfoService;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;

	public WorkResignation get(String id) {
		WorkResignation workResignation = super.get(id);
		//获取离职模版
		if(workResignation!=null){
			WorkResignationTemplate workResignationTemplate = new WorkResignationTemplate();
			workResignationTemplate.setResignationId(id);
			List<WorkResignationTemplate> list = workResignationTemplateService.findList(workResignationTemplate);
			workResignation.setTemplateList(list);
		}
		return workResignation;
	}
	
	public List<WorkResignation> findList(WorkResignation workResignation) {
		return super.findList(workResignation);
	}
	public List<WorkResignation> findLists(WorkResignation workResignation) {
		return workResignationDao.findLists(workResignation);
	}
	
	public Page<WorkResignation> findPage(Page<WorkResignation> page, WorkResignation workResignation) {
		workResignation.getSqlMap().put("dsf", dataScopeFilter(workResignation.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_RESIGNATION.getValue()));
		workResignation.setPage(page);
		page.setList(findList(workResignation));
		return page;
	}
	public Page<WorkResignation> findPages(Page<WorkResignation> page, WorkResignation workResignation) {
		workResignation.setPage(page);
		page.setList(findLists(workResignation));
		return page;
	}
	@Transactional(readOnly = false)
	public void save(WorkResignation workResignation) {
		super.save(workResignation);
		updateWorkReimbursementInfo(workResignation);
	}
	@Transactional(readOnly = false)
	public void updateWorkReimbursementInfo(WorkResignation workResignation) {
			for (WorkResignationTemplate workResignationTemplate : workResignation.getTemplateList()) {
				if (WorkResignationTemplate.DEL_FLAG_NORMAL.equals(workResignationTemplate.getDelFlag())) {
					workResignationTemplate.setResignationId(workResignation.getId());
					if (StringUtils.isBlank(workResignationTemplate.getId())) {
						workResignationTemplate.preInsert();
						workResignationTemplateDao.insert(workResignationTemplate);
					} else {
						if(workResignationTemplate.getAuditor().equals(UserUtils.getUser().getId())&&workResignationTemplate.getStatus()!=null){
							workResignationTemplate.preUpdate();
							workResignationTemplateDao.update(workResignationTemplate);
						}
					}
				}
			}
	}
	@Transactional(readOnly = false)
	public void delete(WorkResignation workResignation) {
		super.delete(workResignation);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workResignation.getId());
		workProjectNotifyService.readByNotifyId(notify);
	}

	@Transactional(readOnly = false)
	public String save(WorkResignation workResignation, Map<String, Object> variables, String processInstanceId) {
		User user = null;
		Office office =  null;
		String sId = workResignation.getWorkStaffBasicInfo().getId();
		WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(sId);
		if(workStaffBasicInfo!=null){
			String uId = workStaffBasicInfo.getUserId();
			user = UserUtils.get(uId);
			office =  officeService.get(workStaffBasicInfo.getOffice().getId());
			if (user == null){
				workResignation.setStatus("1");
				super.save(workResignation);
				return "未获取到申请人账号数据,请联系管理员！";
			}
			if(office == null){
				workResignation.setStatus("1");
				super.save(workResignation);
				return "未获取到申请人账号部门数据,请联系管理员！";
			}
		}else{
			workResignation.setStatus("1");
			super.save(workResignation);
			return "未获取到申请人账号数据,请联系管理员！";
		}
		super.save(workResignation);
		updateWorkReimbursementInfo(workResignation);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workResignation.getId());
		workProjectNotifyService.readByNotifyId(notify);
		String	str =  "离职类型:"+ DictUtils.getDictLabel(workResignation.getType(),"resignation_type","")+",申请人:"+user.getName()+",所属部门:"+office.getName();
		String title = "离职申请人:"+user.getName();
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workResignation.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194clzsqea9miiii750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workResignation.getId(),
						null,
						workResignation.getCompanyId(),
						title,
						str,
						"71",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"18",workResignation.getCreateBy());
		List<User> fglds = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"18",workResignation.getCreateBy());
		List<User> zjls = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"18",workResignation.getCreateBy());
		List<User> rlzys = UserUtils.getByRoleActivityEnname("rlzy",3,office.getId(),"18",workResignation.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(),"18",workResignation.getCreateBy());
					if (enusers.size()==0){
                       /* workReimbursementDao.delete(workReimbursement);
                        for (WorkAccount workAccount : workReimbursement.getWorkAccountList()){
                            workAccountDao.delete(workAccount);
                        }
                        for (ReimbursementVATTax reimbursementVATTax:workReimbursement.getReimbursementVATTaxes()){
                            reimbursementVATTaxDao.delete(reimbursementVATTax);
                        }
                        for (WorkClientAttachment workClientAttachment : workReimbursement.getWorkAttachments()) {
                            workClientAttachmentDao.delete(workClientAttachment);
                        }*/
						workResignation.setStatus("1");
						super.save(workResignation);
						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(),"18",workResignation.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("bmzrList", bmzrs);
            /*variables.put("fgldList", fglds);
            variables.put("cwList", cws);
            variables.put("zjlList", zjls);
            variables.put("cwzjList", cwzjs);
            variables.put("cnList", cns);*/
			//|| fglds.size()==0 || cws.size()==0 || zjls.size()==0 || cwzjs.size()==0 || cns.size()==0
			if (bmzrs.size()==0 ){
				workResignation.setStatus("1");
				super.save(workResignation);
			}
			if (bmzrs.size()==0){
				return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
			}
           /* if (fglds.size()==0){
                return "流程审批人不能为空,角色分管领导下无用户,请联系管理员！";
            }
            if (cws.size()==0){
                return "流程审批人不能为空,角色财务主管下无用户,请联系管理员！";
            }
            if (zjls.size()==0){
                return "流程审批人不能为空,角色总经理下无用户,请联系管理员！";
            }
            if (cwzjs.size()==0){
                return "流程审批人不能为空,角色财务分管领导下无用户,请联系管理员！";
            }
            if (cns.size()==0){
                return "流程审批人不能为空,角色出纳下无用户,请联系管理员！";
            }*/
			variables.put("bmzrcount",bmzrs.size());
            /*variables.put("fgldcount",fglds.size());
            variables.put("cwcount",cws.size());
            variables.put("zjlcount",zjls.size());
            variables.put("cwzjcount",cwzjs.size());
            variables.put("cncount",cns.size());*/
			processType = "workresignation";
			users.addAll(bmzrs);
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("业务部负责人审批");
			workProjectNotifyService
					.save(workProjectNotify);
               /* List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn:toUserConns) {
                   String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 报销人:" + user.getName() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7001");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","18");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + user.getName());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workResignation.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workResignation.setProcessInstanceId(processInstance.getId());
		workResignationDao.updateProcessInstanceId(workResignation);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workresignation");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(2);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(3);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(4);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),2,0);
			workActivityProcessService.insertAuditsByType(zjls,processInstance.getId(),3,0);
			workActivityProcessService.insertAuditsByType(rlzys,processInstance.getId(),4,0);
		}
		//重新申请置空审核列表状态值
		List<WorkResignationTemplate> tList = workResignation.getTemplateList();
		if(tList!=null && tList.size()>0){
			for (WorkResignationTemplate w:
					tList) {
				if(StringUtils.isNotBlank(w.getStatus())){
					w.setStatus(null);
					w.preUpdate();
					workResignationTemplateDao.update(w);
				}
			}
		}
		logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
				ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}

	@Transactional(readOnly = false)
	public String auditSave(WorkResignation workResignation,List<User> auditUsers) {
		User user = null;
		String userName = null;
		Office office =null;
		String sId = workResignation.getWorkStaffBasicInfo().getId();
		String comId= null;
		WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(sId);
		if(workStaffBasicInfo!=null){
			comId = workStaffBasicInfo.getBranchOffice().getId();
			String uId = workStaffBasicInfo.getUserId();
			user = UserUtils.get(uId);
			if (user == null){
				return "未获取到申请人账号数据,请联系管理员！";
			}else{
				userName = user.getName();
				office = user.getOffice();
				if(office == null){
					return "未获取到申请人账号部门数据,请联系管理员！";
				}
			}
		}
		String	str =  "离职类型:"+ DictUtils.getDictLabel(workResignation.getType(),"resignation_type","")+",申请人:"+userName+",所属部门:"+office.getName();
		String title = "离职申请人:"+userName;
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workResignation.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workResignation.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workResignation.getAct().setFlag("yes");
		}
		String comment = "";
		if (workResignation.getStatus().equals("4")){
			comment = ("yes".equals(workResignation.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workResignation.getAct().getFlag())?"[同意] ":"[驳回] ")+workResignation.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workResignation.setStatus(("yes".equals(workResignation.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		List<Activity> activitieList = activityService.getByProcessInstanceId(workResignation.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(workResignation.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workresignation")) {
			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(workResignation.getAct().getFlag())) {
						workResignation.setStatus("4");
						workActivityProcess.setIsApproval("2");
						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(workResignation.getAct().getFlag())) {
						workResignation.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workresignation");
			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(workResignation.getAct().getFlag())) {
						vars.put("fgldList", auditUsers);
						vars.put("fgldcount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workResignation.getProcessInstanceId(),2,1);
						workActivityProcess.setIsApproval("1");
						notifyRole = "分管领导审核";
						enname = "fgld";

					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}  else if ("fgld".equals(taskDefKey) && count.contains("2")) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(workResignation.getAct().getFlag())) {
						vars.put("zjlList", auditUsers);
						vars.put("zjlcount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workResignation.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(workResignation.getAct().getFlag())) {
						vars.put("r", auditUsers);
						vars.put("c",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workResignation.getProcessInstanceId(),4,1);
						workActivityProcess.setIsApproval("1");
						notifyRole = "人力专员审核";
						enname = "rlzy";
					} else {
						workActivityProcess.setIsApproval("2");
						notifyRole = "调整报销";
					}
					break;
				} else if ("rlzy".equals(taskDefKey) && count.contains("4")) {
					taskCount = "4";
					exp = "pass";
					if ("yes".equals(workResignation.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					taskCount = "0";
					notifyRole = "部门负责人审批";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(workResignation.getAct().getFlag())) {
						workResignation.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		workResignation.getAct().setComment(("yes".equals(workResignation.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workResignation.getAct().getComment());
		workResignation.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workResignation.getAct().getFlag()) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workResignation.getProcessInstanceId(),taskDefKey,"modifyApply",workResignation.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workResignation.getAct().getTaskId(), workResignation.getAct().getProcInsId(), workResignation.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workResignation.getAct().getProcInsId());
		if (!state) {
			users.add(workResignation.getCreateBy());
			if ("yes".equals(workResignation.getAct().getFlag())) {
				workResignation.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workResignation.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workResignation.getId(),
										workResignation.getCreateBy(),
										workResignation.getCompanyId(),
										title,
										str,
										"71",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workResignation.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workResignation.getStatus()) && !workResignation.getStatus().equals("3")){
					workResignation.setStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workResignation.getId(),
											workResignation.getCreateBy(),
											workResignation.getCompanyId(),
											title,
											str,
											"71",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workResignation.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workresignation")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workResignation.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workResignation.getId(),
								new User(),
								workResignation.getCompanyId(),
								title,
								str,
								"71",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workResignation.getAct().getFlag(),
						taskCount,
						workResignation.getCreateBy(),
						office.getId(),
						"18");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService
							.save(workProjectNotify1);
					if (!"modifyApply".equals(taskDefKey)){
						Map<String,Object> extras = new HashMap<>();
							extras.put("type","7001");
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","71");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

					}
				}

			} else {
				if (!"yes".equals(workResignation.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workResignation.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workResignation.getId(),
											workResignation.getCreateBy(),
											workResignation.getCompanyId(),
											title,
											str,
											"71",
											"0",
											"重新申请",
											notifyRole));
					users.add( workResignation.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)&&!"rlzy".equals(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workResignation.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workResignation.getId(),
										new User(),
										workResignation.getCompanyId(),
										title,
										str,
										"71",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setId("");
							workProjectNotify.setUser(user1);
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							if (!"modifyApply".equals(taskDefKey)){
								Map<String,Object> extras = new HashMap<>();
								extras.put("type","7001");
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","71");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}
					}else if (StringUtils.isNotBlank(enname)&&"rlzy".equals(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workResignation.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workResignation.getId(),
										new User(),
										workResignation.getCompanyId(),
										title,
										str,
										"71",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setId("");
							workProjectNotify.setUser(user1);
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							if (!"modifyApply".equals(taskDefKey)){
								Map<String,Object> extras = new HashMap<>();
									extras.put("type","7001");
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","71");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}

						//审核列表
						WorkProjectNotify workProjectNotifys = UtilNotify
								.saveNotify(workResignation.getId(),
										new User(),
										workResignation.getCompanyId(),
										title,
										str,
										"71",
										"0",
										"待审批",
										"各级审批");
						List<WorkResignationTemplate> list = workResignation.getTemplateList();

						List<String> ids = Lists.newArrayList();
						List<User> audits = Lists.newArrayList();
						if(list!=null && list.size()>0){
							for (WorkResignationTemplate w:
									list) {
								if(StringUtils.isNotBlank(w.getAuditor())){
									ids.add(w.getAuditor());
								}
							}
							//去重
							if(ids!=null && ids.size()>0){
								// 创建新集合
								List<String> ids2= new ArrayList();
								// 遍历旧集合,获取得到每一个元素
								Iterator it = ids.iterator();
								while (it.hasNext()) {
									String s = (String) it.next();
									// 拿这个元素到新集合去找，看有没有
									if (!ids2.contains(s)) {
										ids2.add(s);
									}
								}
								if(ids2!=null && ids2.size()>0){
									for (String s:
										 ids2) {
										if(StringUtils.isNotBlank(s)){
											User u = UserUtils.get(s);
											if(u!=null){
												audits.add(u);
											}
										}
									}
								}
							}
							users.addAll(audits);
							for (User user1:audits){
								workProjectNotifys.setUser(user1);
								workProjectNotifys.setId("");
								workProjectNotifys.setIsNewRecord(false);
								workProjectNotifyService
										.save(workProjectNotifys);
								if (!"modifyApply".equals(taskDefKey)){
									Map<String,Object> extras = new HashMap<>();
									extras.put("type","7001");
									extras.put("id",workProjectNotifys.getId());
									extras.put("procDefKey","71");
									UserUtils.pushInfoToApp(title,str,extras,user1.getId());
								}
							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workResignation.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workResignation.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workResignation.getId(),
												workResignation.getCreateBy(),
												workResignation.getCompanyId(),
												title,
												str,
												"71",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}
		if (users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),str);
			}
		}
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}

		workResignationDao.update(workResignation);
		if("5".equals(workResignation.getStatus())){
			//修改档案状态
			if(workStaffBasicInfo!=null){
				if("1".equals(workResignation.getType())){
					workStaffBasicInfo.setStatus("离职");
					workStaffBasicInfo.preUpdate();
					workStaffBasicInfo.setDimissionDate(workResignation.getDate());
					workStaffBasicInfo.setWorkEndDate(workResignation.getEndDate());
					workStaffAchivesDao.update(workStaffBasicInfo);
				}else if("2".equals(workResignation.getType())){
					workStaffBasicInfo.setStatus("退休");
					workStaffBasicInfo.preUpdate();
					workStaffBasicInfo.setDimissionDate(workResignation.getDate());
					workStaffBasicInfo.setWorkEndDate(workResignation.getEndDate());
					workStaffAchivesDao.update(workStaffBasicInfo);
				}
			}
			String strs = this.leave(user.getId(),comId);
			if(StringUtils.isNotBlank(strs)){
				return "保存审核意见成功！但员工退出企业失败"+strs;
			}
		}
		return "保存审核意见成功！";
	}
	@SuppressWarnings("unchecked")
	public WorkResignation getByProcessInstanceId(String processInstanceId) {
		WorkResignation workResignation = workResignationDao.getByProcessInstanceId(processInstanceId);
		return workResignation;
	}

	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkResignation workResignation) {
		String invalidateProcessInstanceId = workResignation.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workResignation.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workResignation.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workResignation.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
					for (WebSocket toUserConn : toUserConns) {
						String message = "{\"to\":\""+u.getId()+"\"," +
								"\"msg\":\"审批信息 离职申请人:"+ user.getName()+"" +"的离职申请强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
						//ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"离职申请人:"+ user.getName()+"" +"的离职申请强制撤销!");
				}
			}
			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.setDelFlag("1");
						p.setIsApproval("-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);
			}

			//结束该流程,设为"撤销"状态
			actTaskService.endProcessInstance(invalidateProcessInstanceId,"强制撤销");
			workResignation.setStatus("3");
			workResignation.preUpdate();
			workResignationDao.update(workResignation);
		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Transactional(readOnly = false)
	public void cancelInvalidates(WorkResignation workResignation) {
		String invalidateProcessInstanceId = workResignation.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"驳回"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workResignation.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workResignation.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workResignation.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			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.setDelFlag("1");
						p.setIsApproval("-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);
			}

			//结束该流程,设为"撤销"状态
			actTaskService.endProcessInstance(invalidateProcessInstanceId,"驳回");
			workResignation.setStatus("4");
			workResignation.preUpdate();
			workResignationDao.update(workResignation);
			User user = null;
			String userName = null;
			Office office =null;
			String sId = workResignation.getWorkStaffBasicInfo().getId();
			WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(sId);
			if(workStaffBasicInfo!=null){
				String uId = workStaffBasicInfo.getUserId();
				user = UserUtils.get(uId);
				userName = user.getName();
				office = user.getOffice();
			}
			String	str =  "离职类型:"+ DictUtils.getDictLabel(workResignation.getType(),"resignation_type","")+",申请人:"+userName+",所属部门:"+office.getName();
			String title = "离职申请人:"+userName;
			workProjectNotifyService
					.save(UtilNotify
							.saveNotify(workResignation.getId(),
									workResignation.getCreateBy(),
									workResignation.getCompanyId(),
									title,
									str,
									"71",
									"0",
									"重新申请",
									"调整"));
			UserUtils.pushIm(workResignation.getCreateBy().getId(),str);
		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	//退出企业
	public String leave(String id,String companyId){
		//获取用户信息
		User user = UserUtils.get(id);
		if(user==null){
			return "未找到用户信息";
		}
		WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
		workStaffBasicInfo.setCompany(new Office(companyId));
		workStaffBasicInfo.setUserId(user.getId());
		Integer count = workStaffBasicInfoService.getByCompany(workStaffBasicInfo);
		if (count == 0){
			Company coms = new Company();
			coms.setUserId(id);
			coms.setCompanyId(companyId);
			List<Role> roleList = companyService.getUserRoleComManager(coms);
			if(roleList != null&&roleList.size() > 0){
				List<String> roleComList = companyService.getUserRoleManager(coms);
				int num = 0;
				for (String role: roleComList) {
					if(roleList.get(0).getId().equals(role)) {
						num++;
						if(num>1){
							break;
						}
					}
				}
				if( num == 1 ){//一个管理员
					return ("公司只有您一位管理员,您不能退出企业");
				}
			}
			//公司信息
			Office com=new Office();
			com.setId(companyId);
			//岗位信息
			Role role=new Role();
			role.setCompany(com);
			role.setUser(user);
			//用户获取公司下岗位信息
			List<Role> roleLista = roleDao.findList(role);
			for(Role r : roleLista){
				//根据用户岗位和用户判断
				systemService.updateUserToRole(r,user);
			}
			if (user.getCompany().getId().equals(companyId)){
				Role role1 = new Role();
				role1.setUser(user);
				List<Role> rolelist=roleDao.findList(role1);
				if (rolelist!=null && rolelist.size()!=0){
					String officeId = rolelist.get(0).getOffice().getId();
					String company = rolelist.get(0).getCompany().getId();
					systemService.saveCurrentCompanyById(id,company,officeId);
				}
				companyService.deleteWorkAppShow(companyId,id);
			}
			Useroffice companyinfo = new Useroffice();
			companyinfo.setCompanyId(companyId);
			companyinfo.setUserId(id);
			List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
			if (companyinfoList!=null && companyinfoList.size()!=0){
				for (Useroffice info:companyinfoList){
					info.setDelFlag("1");
					companyinfoService.save(info);
					Pushinfo pushinfo = new Pushinfo();
					pushinfo.setPushId(info.getId());
					List<Pushinfo> pushinfos = pushinfoService.findList(pushinfo);
					if (pushinfos!=null && pushinfos.size()!=0){
						pushinfoService.updateDelflagByPushId(info.getId(),"1");
					}
				}
			}
			Office office = officeService.get(companyId);
			if (StringUtils.isNotBlank(office.getGroupId())){
				LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
				if (layGroup!=null && !layGroup.getCreateBy().getId().equals(user.getId())){
					layGroupService.deleteGroupUser(layGroup,user.getId());
				}
			}
			//更改状态
			user.setComId("1");
			Office company = new Office();
			company.setId("1");
			Office office1 = new Office();
			office1.setId("1");
			user.setCompany(company);
			user.setOffice(office1);
			user.preUpdate();
			userDao.updateUserState(user);
			/*user.setLoginFlag("0");
			user.preUpdate();
			userDao.updateLoginFlag(user);*/
			UserUtils.clearCache(user);
			systemService.removeSession(user);
			return "";
		}else{
			return "不能退出企业";
		}
	}

}