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

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
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.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.utils.UserUtils;
import com.jeeplus.modules.sysparameter.dao.SysParameterDao;
import com.jeeplus.modules.sysparameter.dao.SysParameterValueDao;
import com.jeeplus.modules.sysparameter.entity.SysParameter;
import com.jeeplus.modules.sysparameter.entity.SysParameterValue;
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.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workcalendar.entity.WorkCalendar;
import com.jeeplus.modules.workcalendar.service.WorkCalendarTaskService;
import com.jeeplus.modules.workcontent.web.WorkContentTypeController;
import com.jeeplus.modules.workjobgrade.dao.WorkJobGradeDao;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlan;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlanThis;
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.dao.WorkRegularScoreDao;
import com.jeeplus.modules.workregularapply.entity.WorkRegularContent;
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 com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
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.workregularapply.entity.WorkRegularApply;
import com.jeeplus.modules.workregularapply.dao.WorkRegularApplyDao;

/**
 * 转正申请Service
 * @author chenyuping
 * @version 2018-07-30
 */
@Service
@Transactional(readOnly = true)
public class WorkRegularApplyService extends CrudService<WorkRegularApplyDao, WorkRegularApply> {
	@Autowired
	private UserDao userDao;
	@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
	private WorkRegularScoreDao workRegularScoreDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private WorkJobGradeDao workJobGradeDao;
	@Autowired
	private WorkRegularContentService workRegularContentService;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private SysParameterValueDao sysParameterValueDao;
	@Autowired
	private SysParameterDao sysParameterDao;
	@Autowired
	private RoleDao roleDao;

	public WorkRegularApply get(String id) {
		return super.get(id);
	}
	
	public List<WorkRegularApply> findList(WorkRegularApply workRegularApply) {

		return super.findList(workRegularApply);
	}

	/**
	 * 根据业务权限分页查询
	 * @param page 分页对象
	 * @param workRegularApply
	 * @return
	 */
	public Page<WorkRegularApply> findPage(Page<WorkRegularApply> page, WorkRegularApply workRegularApply) {
		workRegularApply.getSqlMap().put("dsf", dataScopeFilter(workRegularApply.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_REGULARAPPLY.getValue()));
		int count = dao.queryCount(workRegularApply);
		page.setCount(count);
		page.setCountFlag(false);
		workRegularApply.setPage(page);
		page.setList(findList(workRegularApply));
		return page;
	}
	/**
	 * 保存转正申请
	 * @param workRegularApply
	 * @return
	 */
	@Transactional(readOnly = false)
	public void save(WorkRegularApply workRegularApply) {
		super.save(workRegularApply);
		updateWorkRegularScore(workRegularApply);
	}
	/**
	 * 删除
	 * @param workRegularApply
	 * @return
	 */
	@Transactional(readOnly = false)
	public void delete(WorkRegularApply workRegularApply) {
		super.delete(workRegularApply);
		if(workRegularApply.getWorkRegularScoreList()!=null&&workRegularApply.getWorkRegularScoreList().size()>0){
			for(WorkRegularScore workRegularScore:workRegularApply.getWorkRegularScoreList()){
				workRegularScoreDao.delete(workRegularScore);
			}
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workRegularApply.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}

	/**
	 * 保存申请评分表
	 * @param workRegularApply
	 * @return
	 */
	@Transactional(readOnly = false)
	public void updateWorkRegularScore(WorkRegularApply workRegularApply) {
		if(workRegularApply.getWorkRegularScoreList()!=null&&workRegularApply.getWorkRegularScoreList().size()>0){
	for (WorkRegularScore workRegularScore : workRegularApply.getWorkRegularScoreList()) {
		if (StringUtils.isBlank(workRegularScore.getId()) ) {
			workRegularScore.preInsert();
			workRegularScore.setRegularApplyId(workRegularApply.getId());
			workRegularScore.setOfficeId(workRegularApply.getOfficeId());
			workRegularScore.setCompanyId(workRegularApply.getCompanyId());
			workRegularScoreDao.insert(workRegularScore);
		} else {
			workRegularScore.preUpdate();
			workRegularScore.setOfficeId(workRegularApply.getOfficeId());
			workRegularScore.setRegularApplyId(workRegularApply.getId());
			workRegularScore.setCompanyId(workRegularApply.getCompanyId());
			workRegularScoreDao.update(workRegularScore);
		}
	}
}

}
	/**
	 * 获取人员档案
	 * @return
	 */
	@Transactional(readOnly = false)
	public WorkStaffBasicInfo getWorkStaffBasicInfo(String id) {
		WorkStaffBasicInfo w=workStaffAchivesDao.getWorkStaffBasicInfo(id);
		return w;
	}
	/**
	 * 保存数据并启动流程
	 * @return
	 */
	@Transactional(readOnly = false)
	public String saveApply(WorkRegularApply workRegularApply) {
		this.save(workRegularApply);
		return this.startAudit(workRegularApply,workRegularApply.getProcessInstanceId());
	}

	/**
	 * 启动审批流程
	 */
	@Transactional(readOnly = false)
	public String startAudit(WorkRegularApply workRegularApply, String processInstanceId){
		try{
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(workRegularApply.getCurrentUser().getId());
			User user = UserUtils.getUser();
			List<User> fgldList = null;
//			User user=userDao.get(workRegularApply.getUserId());
			String contentStr = "转正人:"+ user.getName()+"，转正日期:"+ DateUtils.formatDate(workRegularApply.getApplyDate());
			String titleStr = "转正人:"+user.getName();
			String businessKey = workRegularApply.getId();
			Office applyOffice = officeDao.get(user.getOffice().getId());
			String comId = user.getComId();
			Role rsbzr = new Role();
			Office office = new Office();
			office.setId(comId);
			rsbzr.setEnname("rsbzr");
			rsbzr.setCompany(office);
			Role role = roleDao.getByEnname(rsbzr);
			if(role != null) {
				fgldList = userDao.findUserByRoleId(role.getId(), comId);
			}
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c82bdea9mrlcc750904", applyOffice);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workRegularApply.getId(),
							null,
							workRegularApply.getCompanyId(),
							titleStr,
							contentStr,
							"66",
							"0",
							"待审批",
							""
					);

			List<User> users = new ArrayList<>();
			List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr",2,applyOffice.getId(),"22",user);
//			List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld",2,applyOffice.getId(),"22",user);
//			List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",3,applyOffice.getId(),"22",user);
////			List<User> rlzyList = UserUtils.getByRoleActivityEnname("rlzy",3,applyOffice.getId(),"22",user);
			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(),applyOffice.getId(),"22",user);
						if (enusers.size()==0){
							workRegularApply.setState("1");
							this.save(workRegularApply);
							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(),applyOffice.getId(),"22",user);
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (bmzrList.size()==0 ){
					workRegularApply.setState("1");
					this.save(workRegularApply);
					return "流程审批人不能为空,系统中无该转正人用户,请联系管理员！";
				}
//				processType = "workPositive";
				processType = "workPositive";
				variables.put("bmzrCount",bmzrList.size());
				variables.put("bmzrList",bmzrList);
				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","66");
//				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", "审批单：" +"转正人："+user.getName());//设置标题；

			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);
//				workActivityProcess.setCount(4);
//				workActivityProcessService.insert(workActivityProcess);
//				workActivityProcess.setCount(5);
//				workActivityProcessService.insert(workActivityProcess);
//				workActivityProcessService.insertAuditsByType(zzr,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(bmzrList,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
//				workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),4,0);
//				workActivityProcessService.insertAuditsByType(rlzyList,processInstance.getId(),5,0);

			}
			workRegularApply.setProcessInstanceId(processInstance.getId());
			workRegularApply.setState("2");
			dao.updateProcessInstanceId(workRegularApply);
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}

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

		if (StringUtils.isBlank(act.getComment())){
			act.setComment(flag.equals("yes")?"同意":"驳回");
		}
		String comment = "";
		if (workRegularApply.getState().equals("4")){
			comment = ("yes".equals(flag)?"[同意] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(flag)?"[同意] ":"[驳回] ")+act.getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workRegularApply.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(workRegularApply.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(workRegularApply.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workPositive")) {
			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");
						workRegularApply.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)) {
						workRegularApply.setState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workPositive");
			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(workRegularApply.getAct().getFlag())) {
						vars.put("fgldList", auditUsers);
						vars.put("fgldCount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workRegularApply.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(workRegularApply.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
						workStaffBasicInfoService.updateStatus(workRegularApply.getUserId());
					} 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)) {
						workRegularApply.setState("3");
					}
					break;
				}
			}
		}
		// 设置意见
		act.setComment(("yes".equals(flag) ? "[同意] " : "[驳回] ") + act.getComment());
		workRegularApply.preUpdate();
		// 提交流程任务
        vars.put("applyUserId",UserUtils.getUser().getId());
		vars.put(exp, "yes".equals(flag) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workRegularApply.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) {
//            str = "yes".equals(flag)?"您的报销单审核：已通过":"您的报销单审核：未通过";
			users.add(workRegularApply.getCreateBy());
			if ("yes".equals(flag)) {
				str =  "转正人:"+user.getName();
				workRegularApply.setState("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRegularApply.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workRegularApply.getId(),
										workRegularApply.getCreateBy(),
										workRegularApply.getCompanyId(),
										title,
										str,
										"66",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRegularApply.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workRegularApply.getState()) && !workRegularApply.getState().equals("3")){
					workRegularApply.setState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workRegularApply.getId(),
											workRegularApply.getCreateBy(),
											workRegularApply.getCompanyId(),
											title,
											str,
											"66",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workRegularApply.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workPositive")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRegularApply.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workRegularApply.getId(),
								new User(),
								workRegularApply.getCompanyId(),
								title,
								str,
								"66",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						flag,
						taskCount,
						workRegularApply.getCreateBy(),
						user.getOffice().getId(),
						"66");
				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(workRegularApply.getId());
					workProjectNotifyService.readByNotifyId(notify);
					User zzrUser=userDao.get(workRegularApply.getUserId());
					userList.add(zzrUser);
					//userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workRegularApply.getId(),
											zzrUser,
											zzrUser.getCompany().getId(),
											title,
											str,
											"66",
											"0",
											"重新申请",
											notifyRole));
					users.add(zzrUser);
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRegularApply.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workRegularApply.getId(),
										new User(),
										workRegularApply.getCompanyId(),
										title,
										str,
										"66",
										"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","66");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(title,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRegularApply.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(workRegularApply.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workRegularApply.getId(),
												workRegularApply.getCreateBy(),
												workRegularApply.getCompanyId(),
												title,
												str,
												"66",
												"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(workRegularApply);

		return "保存审核意见成功！";
	}
	/**
	 * 撤回操作
	 * @return
	 */
	@Transactional(readOnly = false)
	public void cancelProcess(String id) throws Exception {
		WorkRegularApply workRegularApply = this.get(id);
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workRegularApply.getProcessInstanceId());
		process.setIsApproval("0");
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workRegularApply.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workRegularApply.getId());
		List<User> userList = workProjectNotifyService.readByNotifyId(notify);
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				User user = UserUtils.get(u.getId());
				User uu=userDao.get(workRegularApply.getUserId());
				UserUtils.pushIm(u.getId(),"转正人:"+ uu.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.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);

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

	//定时任务创建转正申请
	@Transactional(readOnly = false)
	public void saveTask() {
		List<WorkStaffBasicInfo> userInfoList=new ArrayList<>();
		WorkStaffBasicInfo basicInfo=new WorkStaffBasicInfo();
		basicInfo.setStatus("试用");
		List<WorkStaffBasicInfo> basicInfoLists=workStaffAchivesDao.findTaskBranchList(basicInfo);
		if(basicInfoLists!=null&&basicInfoLists.size()>0){
			for(WorkStaffBasicInfo staffBasicInfo:basicInfoLists){
				String getSysParam=this.getSysParam("advance_days",staffBasicInfo.getBranchOffice().getId());
				if(getSysParam!=null&&!"".equals(getSysParam)){
					List<WorkStaffBasicInfo> basicInfoList =workStaffAchivesDao.findTaskUserList(Integer.parseInt(getSysParam),staffBasicInfo.getBranchOffice().getId());
					if(basicInfoList!=null&&basicInfoList.size()>0){
						userInfoList.addAll(basicInfoList);
					}
				}

			}
		}
		HashSet set = new HashSet(userInfoList);
		userInfoList.clear();
		userInfoList.addAll(set);
	    if(userInfoList!=null&&userInfoList.size()>0){
		   for(WorkStaffBasicInfo workStaffBasicInfo:userInfoList){
			  User user=userDao.get(workStaffBasicInfo.getUserId());
			  WorkRegularApply workRegularApply=new WorkRegularApply();
			  workRegularApply.setUserId(workStaffBasicInfo.getUserId());
			  workRegularApply.setBasicInfoId(workStaffBasicInfo.getId());
			  workRegularApply.setCompanyId(user.getCompany().getId());
			  workRegularApply.setOfficeId(user.getOffice().getId());
			  workRegularApply.setState("2");
			  workRegularApply.setApplyDate(new Date());
			  workRegularApply.setCreateDate(new Date());
			  workRegularApply.setUpdateBy(user);
			  workRegularApply.setCreateBy(user);
			  workRegularApply.setCurrentUser(user);
			  workRegularApply.setDelFlag("0");
			  workRegularApply.setCorrectOpinion("1");
			  workRegularApply.setCorrectDate(workStaffBasicInfo.getTryEndTime());
			  workRegularApply.setJobGrade(workStaffBasicInfo.getJobGrade());
			//新增初始化鉴定内容
			WorkRegularContent w=new WorkRegularContent();
			w.setOfficeId(user.getOffice().getId());
			w.setCompanyId(user.getCompany().getId());
			List<WorkRegularScore> workRegularScoreList=new ArrayList<>();
			List<WorkRegularContent> list=workRegularContentService.findListApply(w);
			for(WorkRegularContent workRegularContent:list){
				WorkRegularScore workRegularScore=new WorkRegularScore();
				workRegularScore.setRegularContentId(workRegularContent.getId());
				workRegularScore.setContent(workRegularContent.getContent());
				workRegularScoreList.add(workRegularScore);
			}
			workRegularApply.setWorkRegularScoreList(workRegularScoreList);
			//启动流程
			this.save(workRegularApply);
			String str=this.startTaskAudit(workRegularApply,workRegularApply.getProcessInstanceId());
			System.out.println(str);
		}
	}
}

	/**
	 * 定时启动审批流程
	 */
	@Transactional(readOnly = false)
	public String startTaskAudit(WorkRegularApply workRegularApply, String processInstanceId){
		try{
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(workRegularApply.getCurrentUser().getId());
			//User createUser = userDao.get(workRegularApply.getUserId());
			User user=userDao.get(workRegularApply.getUserId());
			String contentStr = "转正人："+ user.getName()+"，转正日期："+ DateUtils.formatDate(workRegularApply.getApplyDate());
			String titleStr = "转正人："+user.getName();
			List<User> zzr=new ArrayList<>();
			zzr.add(user);
			String businessKey = workRegularApply.getId();
			Office office = officeDao.get(workRegularApply.getOfficeId());
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c82bdea9mrlcc750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workRegularApply.getId(),
							null,
							workRegularApply.getCompanyId(),
							titleStr,
							contentStr,
							"66",
							"0",
							"待审批",
							""
					);

			List<User> users = new ArrayList<>();
			List<User> bmzrList = UserUtils.getByRoleActivityEnnameTask("bmzr",2,office.getId(),"22",workRegularApply.getCreateBy());
			List<User> fgldList = UserUtils.getByRoleActivityEnnameTask("fgld",2,office.getId(),"22",workRegularApply.getCreateBy());
			List<User> zjlList = UserUtils.getByRoleActivityEnnameTask("zjl",3,office.getId(),"22",workRegularApply.getCreateBy());
			List<User> rlzyList = UserUtils.getByRoleActivityEnnameTask("rlzy",3,office.getId(),"22",workRegularApply.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(),"22",workRegularApply.getCreateBy());
						if (enusers.size()==0){
							workRegularApply.setState("1");
							this.delete(workRegularApply);
							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(),"22",workRegularApply.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (zzr.size()==0 ){
					workRegularApply.setState("1");
					this.delete(workRegularApply);
					return "流程审批人不能为空,系统中无该转正人用户,请联系管理员！";
				}
				processType = "workPositive";
				users.addAll(zzr);
			}
			List<String> userIds = new ArrayList<>(users.size());
			for (User u : users){
				userIds.add(u.getId());
				workProjectNotify.setUser(u);
				workProjectNotify.setCreateBy(u);
				workProjectNotify.setUpdateBy(u);
				workProjectNotify.setId("");
				workProjectNotify.setNotifyRole("转正人补充信息");
				workProjectNotifyService.save(workProjectNotify);
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("procDefKey","66");
				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", "审批单：" +"转正人："+user.getName());//设置标题；

			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");
				workActivityProcess.setCreateBy(user);
				workActivityProcess.setUpdateBy(user);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(3);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(4);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(5);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.insertAuditsByType(zzr,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(bmzrList,processInstance.getId(),2,0);
				workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),3,0);
				workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),4,0);
				workActivityProcessService.insertAuditsByType(rlzyList,processInstance.getId(),5,0);

			}
			workRegularApply.setProcessInstanceId(processInstance.getId());
			workRegularApply.setState("2");
			dao.updateProcessInstanceId(workRegularApply);
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			this.delete(workRegularApply);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}

	/**
	 * 获取系统参数
	 * parameter 参数类型
	 * branchOffice 分公司Id 分公司id为空传公司id
	 * @return
	 */
	public  String getSysParam(String parameter,String branchOffice) {
		SysParameter SysParameter=sysParameterDao.findIsforce(parameter);
		if(SysParameter!=null&&"1".equals(SysParameter.getIsForce())){//公司必须自己定义参数
				SysParameterValue sysParameterValue = sysParameterValueDao.findValueByParameter(parameter, branchOffice);
				if (sysParameterValue != null) {
					return sysParameterValue.getValue();
				}
			}else{
			SysParameterValue sysParameterValue = sysParameterValueDao.findValueByParameter(parameter, branchOffice);
			if (sysParameterValue == null) {
				SysParameterValue sysValue = sysParameterValueDao.findSysValue(parameter);
				if(sysValue!=null){
					return sysValue.getValue();
				}
			}
		}
		return "";
	}
}