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

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.leaveapply.dao.LeaveCountDao;
import com.jeeplus.modules.leaveapply.dao.LeaveDetailDao;
import com.jeeplus.modules.leaveapply.entity.LeaveCount;
import com.jeeplus.modules.leaveapply.entity.LeaveDetail;
import com.jeeplus.modules.leavetype.dao.LeaveTypeDao;
import com.jeeplus.modules.leavetype.entity.LeaveType;
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.utils.ErrorCode;
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.workattendance.dao.WorkAttendanceInfoDao;
import com.jeeplus.modules.workattendance.entity.WorkAttendanceInfo;
import com.jeeplus.modules.workattendance.entity.WorkAttendanceMonth;
import com.jeeplus.modules.workattendance.entity.WorkAttendanceRule;
import com.jeeplus.modules.workattendance.service.WorkAttendanceInfoService;
import com.jeeplus.modules.workattendance.service.WorkAttendanceRuleService;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workcalendar.service.WorkCalendarService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workitem.entity.WorkItem;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollar;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollarCatalog;
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.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.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.leaveapply.entity.LeaveApply;
import com.jeeplus.modules.leaveapply.dao.LeaveApplyDao;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请假申请Service
 * @author ssrh
 * @version 2018-09-10
 */
@Service
@Transactional(readOnly = true)
public class LeaveApplyService extends CrudService<LeaveApplyDao, LeaveApply> {


    @Autowired
    private WorkStaffAchivesDao workStaffAchivesDao;
    @Autowired
    private LeaveDetailDao leaveDetailDao;
    @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 UserDao userDao;
    @Autowired
    private WorkCalendarService workCalendarService;
    @Autowired
    private OfficeDao officeDao;
    @Autowired
    @Lazy
    private WorkAttendanceInfoService workAttendanceInfoService;
    @Autowired
    @Lazy
    private WorkAttendanceRuleService workAttendanceRuleService;
    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private WorkAttendanceInfoDao workAttendanceInfoDao;
    @Autowired
    private LeaveCountService leaveCountService;
    @Autowired
    private LeaveCountDao leaveCountDao;
    @Autowired
    private LeaveTypeDao leaveTypeDao;

    public LeaveApply get(String id) {
        LeaveApply leaveApply = super.get(id);
        if(leaveApply!=null){
            //附件
            WorkClientAttachment workClientAttachment = new WorkClientAttachment();
            workClientAttachment.setAttachmentId(id);
            workClientAttachment.setAttachmentFlag("114");
            leaveApply.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
        }
        return leaveApply;
    }

    public List<LeaveApply> findList(LeaveApply leaveApply) {
       // leaveApply.setCreateBy(UserUtils.getUser());
        leaveApply.getSqlMap().put("dsf", dataScopeFilter(leaveApply.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_LEAVE.getValue()));
        return super.findList(leaveApply);
    }
    public LeaveApply getByStaffIdAndTime(String staffId, String time) {
        LeaveApply leaveApply = dao.getByStaffIdAndTime(staffId, time);
        return leaveApply;
    }
    public Page<LeaveApply> findPage(Page<LeaveApply> page, LeaveApply leaveApply) {
        leaveApply.setPage(page);
        page.setList(findList(leaveApply));
        return page;
    }

    public List<LeaveApply> getCount() {
        WorkStaffBasicInfo workStaffBasicInfo = this.getBasicInfo();
        LeaveApply leaveApply = new LeaveApply();
        leaveApply.setBasicInfo(workStaffBasicInfo);
        List<LeaveApply> list = dao.getCount(leaveApply);
        return list;
    }

    //当前登录人档案
    public WorkStaffBasicInfo getBasicInfo() {
        WorkStaffBasicInfo w = new WorkStaffBasicInfo();
        w.setUserId(UserUtils.getUser().getId());
        w.setCompany(UserUtils.getSelectCompany());
        WorkStaffBasicInfo workStaffBasicInfo = workStaffAchivesDao.getBasicInfo(w);
        return workStaffBasicInfo;
    }

    //获取最后一次请假结束时间
    public String getMaxTime(String staffId,String id) {
        return dao.getMaxTime(staffId,id);
    }
//请假
    @Transactional(readOnly = false)
    public void save(LeaveApply leaveApply) {
        super.save(leaveApply);
        updateLeaveDetail(leaveApply);
        updateFile(leaveApply);
    }
    //续假
    @Transactional(readOnly = false)
    public void saveExtend(LeaveApply leaveApply) {
        super.save(leaveApply);
        updateExtendDetail(leaveApply);
        updateFile(leaveApply);
    }
    @Transactional(readOnly = false)
    public void updateFile(LeaveApply leaveApply) {
        //附件信息
        for (WorkClientAttachment workClientAttachment : leaveApply.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(leaveApply.getId());
                workClientAttachment.setAttachmentFlag("114");
                workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
                    workClientAttachment.preInsert();
                    workClientAttachmentDao.insert(workClientAttachment);
                } else {
                    workClientAttachment.preUpdate();
                    workClientAttachmentDao.update(workClientAttachment);
                }
            } else {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
    }
    @Transactional(readOnly = false)
    public void updateLeaveDetail(LeaveApply leaveApply) {
        if (leaveApply.getLeaveDetailList() != null && leaveApply.getLeaveDetailList().size() > 0) {
            for (LeaveDetail leaveDetail : leaveApply.getLeaveDetailList()) {
                if (StringUtils.isBlank(leaveDetail.getId())) {
                    leaveDetail.preInsert();
                    leaveDetail.setLeaveId(leaveApply.getId());
                    leaveDetail.setFlat("1");//请假
                    leaveDetail.setState("0");//请假
                    leaveDetail.setIsUse("0");//有效
                    leaveDetail.setRealDays(leaveDetail.getDays());
                    leaveDetail.setRealEndTime(leaveDetail.getEndTime());
                    leaveDetail.setRealEndType(leaveDetail.getEndType());
                    if (StringUtils.isNotBlank(leaveApply.getId())) {
                        leaveDetailDao.insert(leaveDetail);
                    }
                } else {
                    if("1".equals(leaveDetail.getStartType())||"2".equals(leaveDetail.getStartType())){
                        leaveDetail.preUpdate();
                        leaveDetail.setLeaveId(leaveApply.getId());
                        if (StringUtils.isNotBlank(leaveApply.getId())) {
                            leaveDetailDao.update(leaveDetail);
                        }
                    }
                }
            }
        }
    }

    @Transactional(readOnly = false)
    public void updateExtendDetail(LeaveApply leaveApply) {
        if (leaveApply.getLeaveDetailList() != null && leaveApply.getLeaveDetailList().size() > 0) {
            for (LeaveDetail leaveDetail : leaveApply.getLeaveDetailList()) {
                if (StringUtils.isBlank(leaveDetail.getId())) {
                    leaveDetail.preInsert();
                    leaveDetail.setFlat("2");//续假
                    leaveDetail.setState("1");//
                    leaveDetail.setIsUse("0");//有效
                    leaveDetail.setRealDays(leaveDetail.getDays());
                    leaveDetail.setRealEndTime(leaveDetail.getEndTime());
                    leaveDetail.setRealEndType(leaveDetail.getEndType());
                    leaveDetail.setLeaveId(leaveApply.getId());
                    if (StringUtils.isNotBlank(leaveApply.getId())) {
                        leaveDetailDao.insert(leaveDetail);
                    }
                } else {
                    if("1".equals(leaveDetail.getStartType())||"2".equals(leaveDetail.getStartType())){
                        leaveDetail.preUpdate();
                        leaveDetail.setLeaveId(leaveApply.getId());
                        if (StringUtils.isNotBlank(leaveApply.getId())) {
                            leaveDetailDao.update(leaveDetail);
                        }
                    }
                }
            }
        }
    }

    @Transactional(readOnly = false)
    public void delete(LeaveApply leaveApply) {
        super.delete(leaveApply);
        //删除子表数据
        if (leaveApply.getLeaveDetailList() != null && leaveApply.getLeaveDetailList().size() > 0) {
            for (LeaveDetail leaveDetail : leaveApply.getLeaveDetailList()) {
                leaveDetailDao.delete(leaveDetail);
            }
        }
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(leaveApply.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users != null && users.size() != 0) {
            for (User user : users) {
                UserUtils.pushMeIm(user.getId());
            }
        }
    }

    @Transactional(readOnly = false)
    public String saveBorrow(LeaveApply leaveApply) {
        if (StringUtils.isBlank(leaveApply.getNo())) {
            leaveApply.setNo(serialNumTplService.genSerialNum(UserUtils.getUser().getCompany(), "30"));
        }
        if (StringUtils.isBlank(leaveApply.getOfficeId())) {
            leaveApply.setOfficeId(UserUtils.getSelectOffice().getId());
        }
        if (leaveApply.getCompanyId() == null || StringUtils.isBlank(leaveApply.getCompanyId())) {
            leaveApply.setCompanyId(UserUtils.getSelectCompany().getId());
        }
        this.save(leaveApply);
        return this.startAudit(leaveApply, leaveApply.getProcessInstanceId());
    }


    /**
     * 请假启动审批流程
     */
    @Transactional(readOnly = false)
    public String startAudit(LeaveApply leaveApply, String processInstanceId) {
        try {
            Map<String, Object> variables = new HashMap<String, Object>();
            identityService.setAuthenticatedUserId(leaveApply.getCurrentUser().getId());
            User createUser = UserUtils.getUser();
            String contentStr = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
            String titleStr = "请假人：" + userDao.get(leaveApply.getApplyer()).getName();

            String businessKey = leaveApply.getId();
            Office office = UserUtils.getSelectOffice();
            WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c8lz88a9miiii75090455", office);
            // 启动流程
            String processType = workActivityMenu.getProcessType();
            StringBuffer buffer = new StringBuffer();
            Activity activity = new Activity();
            WorkProjectNotify workProjectNotify = UtilNotify
                    .saveNotify(leaveApply.getId(), null, leaveApply.getCompanyId(), titleStr, contentStr, "80", "0", "待审批", "");

            List<User> users = new ArrayList<>();
//            部门责任人
            List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "25", leaveApply.getCreateBy());
//            分管领导
            List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld", 2, office.getId(), "25", leaveApply.getCreateBy());
//            总经理
            List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl", 3, office.getId(), "25", leaveApply.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(), "25", leaveApply.getCreateBy());
                        if (enusers.size() == 0) {
                            leaveApply.setStatus("1");
                            this.save(leaveApply);
                            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(), "25", leaveApply.getCreateBy());
                    }
                    //人员审批
                    if (StringUtils.isNotBlank(activity.getUser().getId())) {
                        users.add(activity.getUser());
                    }
                }
                workProjectNotify.setId("");
            } else {
                variables.put("bmzrList", bmzrList);
                if (bmzrList.size() == 0) {
                    leaveApply.setStatus("1");
                    this.save(leaveApply);
                }
                if (bmzrList.size() == 0) {
                    return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
                }

                variables.put("bmzrCount", bmzrList.size());
                processType = "leaveApply";
                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", "7002");
                extras.put("procDefKey", "80");
                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", "审批单：" + leaveApply.getNo());//设置标题；

            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.setProcessInstanceId(processInstance.getId());
                workActivityProcess.setCount(1);
                workActivityProcess.setIsApproval("0");
                workActivityProcessService.insert(workActivityProcess);
                workActivityProcessService.insertAuditsByType(bmzrList, processInstance.getId(), 1, 1);
                double days=Double.parseDouble(leaveApply.getLongTime());
                if(days>1){
                    workActivityProcess.setCount(2);
                    workActivityProcess.setId("");
                    workActivityProcessService.save(workActivityProcess);
                    workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
                }
                if(days>3){
                    workActivityProcess.setCount(3);
                    workActivityProcess.setId("");
                    workActivityProcessService.save(workActivityProcess);
                    workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),3,0);
                }

            }
            leaveApply.setProcessInstanceId(processInstance.getId());
            leaveApply.setStatus("2");
            this.save(leaveApply);
        } catch (Exception e) {
            logger.error("启动审批流程异常：", e);
            return "启动审批流程异常:" + e.getMessage();
        }
        return "";
    }

    /**
     * 审核流程
     */
    @Transactional(readOnly = false)
    public String auditSave(LeaveApply leaveApply, List<User> auditUsers) {
        double days=Double.parseDouble(leaveApply.getLongTime());//请假天数
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = leaveApply.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(leaveApply.getAct().getTaskId(), UserUtils.getUser().getId());
        } else {
            leaveApply.getAct().setFlag("yes");
            updateLeaveDetail(leaveApply);
            updateFile(leaveApply);
        }
        String comment = "";
        if ("4".equals(leaveApply.getStatus())) {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[重新申请] " : "[已撤销] ");
        } else {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        leaveApply.setStatus(("yes".equals(leaveApply.getAct().getFlag()) ? "2" : "4"));
        Map<String, Object> vars = Maps.newHashMap();
        //业务逻辑对应的条件表达式
        String exp = "";
        String taskCount = "";
        String notifyRole = "";
        int key = 0;
        String enname = "";
        String str = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
        User createUser = userDao.get(leaveApply.getCurrentUser());
        String notifyTitle = "请假人：" + userDao.get(leaveApply.getApplyer()).getName();
        List<Activity> activitieList = activityService.getByProcessInstanceId(leaveApply.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(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("leaveApply")) {
            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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("4");
                        workActivityProcess.setIsApproval("2");
                        String returnBack = "-1";
                        for (Activity activity : activities) {
                            if (activity.getCount() == activityProcess.getCount()) {
                                notifyRole = activity.getName();
                                returnBack = activity.getReturnBack();
                                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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("3");
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("leaveApply");
            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(leaveApply.getAct().getFlag())) {
                        leaveApply.getAct().setFlag("end");
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                        if(days>1){
                            leaveApply.getAct().setFlag("yes");
                            vars.put("fgldList", auditUsers);
                            vars.put("fgldCount",auditUsers.size());
                            workActivityProcessService.insertAuditsByType(auditUsers,leaveApply.getProcessInstanceId(),2,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(leaveApply.getAct().getFlag())) {
                        leaveApply.getAct().setFlag("end");
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                        if(days>3){
                            leaveApply.getAct().setFlag("yes");
                            vars.put("zjlList", auditUsers);
                            vars.put("zjlCount",auditUsers.size());
                            workActivityProcessService.insertAuditsByType(auditUsers,leaveApply.getProcessInstanceId(),3,1);
                            notifyRole = "总经理审核";
                            enname = "zjl";
                        }
                    } else {
                        notifyRole = "调整请假信息";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("zjl".equals(taskDefKey) && count.contains("3")) {
                    taskCount = "3";
                    exp = "pass";
                    if ("yes".equals(leaveApply.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        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";
                    Office office = UserUtils.getSelectOffice();
                    List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "25", leaveApply.getCreateBy());
                    List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld", 2, office.getId(), "25", leaveApply.getCreateBy());
                    List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl", 3, office.getId(), "25", leaveApply.getCreateBy());
                    WorkActivityProcess workActivityProcess1 = new WorkActivityProcess();
                    workActivityProcess1.setProcessKey("leaveApply");
                    workActivityProcess1.setProcessInstanceId(leaveApply.getProcessInstanceId());
                    workActivityProcess1.setCount(1);
                    workActivityProcess1.setIsApproval("0");
                    workActivityProcessService.insert(workActivityProcess1);
                    workActivityProcessService.insertAuditsByType(bmzrList,leaveApply.getProcessInstanceId(), 1, 1);
                    if(days>1){
                        workActivityProcess1.setCount(2);
                        workActivityProcess1.setId("");
                        workActivityProcessService.save(workActivityProcess1);
                        workActivityProcessService.insertAuditsByType(fgldList,leaveApply.getProcessInstanceId(),2,0);
                    }
                    if(days>3){
                        workActivityProcess1.setCount(3);
                        workActivityProcess1.setId("");
                        workActivityProcessService.save(workActivityProcess1);
                        workActivityProcessService.insertAuditsByType(zjlList,leaveApply.getProcessInstanceId(),3,0);
                    }
                    if (!"yes".equals(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("3");
                    }
                    break;
                }

            }
        }
        // 设置意见
        leaveApply.getAct().setComment(("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment());
        leaveApply.preUpdate();
        // 提交流程任务
        vars.put(exp, leaveApply.getAct().getFlag());
        vars.put("passs", true);
        if("end".equals(leaveApply.getAct().getFlag())){
            leaveApply.getAct().setFlag("yes");
        }
        workActivityProcessService.updateProcess(workActivityProcess, workActivityMenu, key, taskCount, leaveApply.getProcessInstanceId(), taskDefKey, "modifyApply", leaveApply.getAct().getFlag(), comment, activities);
        if("no".equals(leaveApply.getAct().getFlag())){
                this.reject(leaveApply);
        }
        // 提交流程任务
        actTaskService.complete(leaveApply.getAct().getTaskId(), leaveApply.getAct().getProcInsId(), leaveApply.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(leaveApply.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if (!state) {
            users.add(leaveApply.getCreateBy());
            if ("yes".equals(leaveApply.getAct().getFlag())||"end".equals(leaveApply.getAct().getFlag())) {
                leaveApply.setStatus("5");
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        leaveApply.getCreateBy(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "80",
                                        "0",
                                        "待通知",
                                        notifyRole));
                LeaveDetail detail=new LeaveDetail();
                detail.setLeaveId(leaveApply.getId());
                List<LeaveDetail> leaveDetails = leaveDetailDao.findList(detail);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Office company = UserUtils.getSelectCompany();
                User user = UserUtils.getByCompanyAndUserId(leaveApply.getApplyer(),company.getId());
                WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
                workStaffBasicInfo.setUserId(leaveApply.getApplyer());
                workStaffBasicInfo.setCompany(company);
                List<WorkStaffBasicInfo> workStaffAchives = workStaffAchivesDao.getByCompanyInfo(workStaffBasicInfo);
                WorkStaffBasicInfo workStaffAchive = new WorkStaffBasicInfo();
                WorkAttendanceRule oaRule = new WorkAttendanceRule();
                if (workStaffAchives!=null && workStaffAchives.size()!=0) {
                    workStaffAchive = workStaffAchives.get(0);
                    //依据公司和规则编号查询规则
                    oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), workStaffAchive.getUserId(), "");
                    if (oaRule == null || StringUtils.isBlank(oaRule.getId())) {
                        oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), "", workStaffAchive.getOffice().getId());
                    }
                    if (oaRule == null) {
                        oaRule = new WorkAttendanceRule();
                        oaRule.setType("3");
                    }
                }
                Boolean status = false;
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                if (StringUtils.isNotBlank(oaRule.getId()) && StringUtils.isNotBlank(workStaffAchive.getId()) && leaveDetails!=null && leaveDetails.size()!=0){
                    for (LeaveDetail leaveDetail :leaveDetails){
                        Date stateTime = leaveDetail.getStartTime();
                        Date endTime = leaveDetail.getEndTime();
                        String startType = leaveDetail.getStartType();
                        String endType = leaveDetail.getEndType();
                        LeaveType leaveType = leaveDetail.getLeaveType();
                      /*  int stateMonth = Integer.parseInt(stateTime.substring(5,7));
                        int endMonth = Integer.parseInt(endTime.substring(5,7));*/
                        List<Date> dates = findDates(stateTime,endTime);
                        for (Date date:dates) {
                            String time = sdf.format(date);
                            int iholidays = workAttendanceInfoService.isHolidays(time);
                            if (iholidays == 0 ||(iholidays != 0 && "1".equals(leaveType.getModel()))) {
                                Integer dateInt = Integer.parseInt(sdf1.format(date));
                                int count = 3;
                                if (sdf.format(date).equals(sdf.format(stateTime))) {
                                    if (startType.equals("2")) {
                                        count = 2;
                                    }
                                }
                                if (sdf.format(date).equals(sdf.format(endTime))) {
                                    if (endType.equals("1")) {
                                        count = 1;
                                    }
                                }
                                if (workStaffAchive.getWorkEndDate() != null) {
                                    String end = sdf1.format(workStaffAchive.getWorkEndDate());
                                    if (Integer.parseInt(end) >= dateInt) {
                                        status = true;
                                    }
                                } else {
                                    status = true;
                                }
                                int holidays = 0;
                                if (status) {
                                    WorkAttendanceInfo workAttendanceInfo1 = new WorkAttendanceInfo();
                                    WorkAttendanceInfo workAttendanceInfo2 = new WorkAttendanceInfo();
                                    WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
                                    workAttendanceInfo.setStaffId(workStaffAchive.getId());
                                    workAttendanceInfo.setAttendanceDate(date);
                                    List<WorkAttendanceInfo> workAttendanceInfos = workAttendanceInfoService.findList(workAttendanceInfo);
                                    if (workAttendanceInfos != null && workAttendanceInfos.size() != 0) {
                                        if (workAttendanceInfos.size() == 1) {
                                            if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                workAttendanceInfo1 = workAttendanceInfos.get(0);
                                            } else {
                                                workAttendanceInfo2 = workAttendanceInfos.get(0);
                                            }
                                        } else {
                                            if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                workAttendanceInfo2 = workAttendanceInfos.get(1);
                                                workAttendanceInfo1 = workAttendanceInfos.get(0);
                                            } else {
                                                workAttendanceInfo1 = workAttendanceInfos.get(1);
                                                workAttendanceInfo2 = workAttendanceInfos.get(0);
                                            }
                                        }
                                    }
                                    workAttendanceInfoService.saveInfo(oaRule, oaRule.getType(), workStaffAchive.getId(), user, date, time, null, "", "", "",
                                            "4", "4", "", holidays, null,
                                            "", leaveType.getIsAttendance(), leaveType.getIsSubsidized(),
                                            "", "", null, "", count, workAttendanceInfo1.getId(), workAttendanceInfo2.getId());
                                }
                            }
                        }
                    }
                }


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

            } else {
                if (!"yes".equals(leaveApply.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(leaveApply.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(leaveApply.getId(),
                                            leaveApply.getCreateBy(),
                                            leaveApply.getCompanyId(),
                                            notifyTitle,
                                            str,
                                            "80",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add(leaveApply.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        new User(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "80",
                                        "0",
                                        "待审批",
                                        notifyRole);
                        users.addAll(auditUsers);
                        for (User user1 : auditUsers) {
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String, Object> extras = new HashMap<>();
                            extras.put("type", "7002");
                            extras.put("procDefKey", "80");
                            extras.put("id", workProjectNotify.getId());
                            UserUtils.pushInfoToApp(notifyTitle, str, extras, user1.getId());
                        }
                    } else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.addAll(userList);
                        users.add(leaveApply.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(leaveApply.getId(),
                                                leaveApply.getCreateBy(),
                                                leaveApply.getCompanyId(),
                                                notifyTitle,
                                                str,
                                                "80",
                                                "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());
            }
        }
        dao.update(leaveApply);
        return "保存审核意见成功！";
    }


    @Transactional(readOnly = false)
    public void cancelProcess(String id) throws Exception {
        LeaveApply leaveApply = this.get(id);
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(leaveApply.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(leaveApply.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList != null && userList.size() != 0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                UserUtils.pushIm(u.getId(), "请假人:" + user.getName() + ",请假编号:" + leaveApply.getNo() + " 强制撤销!");
            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            LeaveApply leave = new LeaveApply();
            leave.setId(id);
            leave.setStatus("3");
            leave.setProcessInstanceId(leaveApply.getProcessInstanceId());
            leave.preUpdate();
            this.updateStateById(leave);
            actTaskService.endProcessInstance(leaveApply.getProcessInstanceId(), "请假申请-撤回");
        }
    }

    private void updateStateById(LeaveApply leaveApply) {
        dao.updateProcessIdAndStatus(leaveApply);
    }

    @Transactional(readOnly = false)
    public String saveBack(LeaveApply leaveApply) {
        this.save(leaveApply);
        return this.startBack(leaveApply, leaveApply.getProcessInstanceId());
    }

    @Transactional(readOnly = false)
    public String extendSave(LeaveApply leaveApply) {
        this.saveExtend(leaveApply);
        return this.extendSave(leaveApply, leaveApply.getProcessInstanceId());
    }

    /**
     * 启动审批流程
     */
    @Transactional(readOnly = false)
    public String startBack(LeaveApply leaveApply, String processInstanceId) {
        try {
            Map<String, Object> variables = new HashMap<String, Object>();
            identityService.setAuthenticatedUserId(leaveApply.getCurrentUser().getId());
            User createUser = UserUtils.getUser();
            String contentStr = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
            userDao.get(leaveApply.getApplyer()).getName();
            String titleStr = "销假人：" + userDao.get(leaveApply.getApplyer()).getName();

            String businessKey = leaveApply.getId();
            Office office = UserUtils.getSelectOffice();
            WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c8lz88a9miiii75090477", office);
            // 启动流程
            String processType = workActivityMenu.getProcessType();
            StringBuffer buffer = new StringBuffer();
            Activity activity = new Activity();
            WorkProjectNotify workProjectNotify = UtilNotify
                    .saveNotify(leaveApply.getId(), null, leaveApply.getCompanyId(), titleStr, contentStr, "81", "0", "待审批", ""
                    );

            List<User> users = new ArrayList<>();
            List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "25", leaveApply.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(), "25", leaveApply.getCreateBy());
                        if (enusers.size() == 0) {
                            leaveApply.setStatus("5");
                            this.save(leaveApply);
                            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(), "25", leaveApply.getCreateBy());
                    }
                    //人员审批
                    if (StringUtils.isNotBlank(activity.getUser().getId())) {
                        users.add(activity.getUser());
                    }
                }
                workProjectNotify.setId("");
            } else {
                variables.put("bmzrList", bmzrList);
                if (bmzrList.size() == 0) {
                    leaveApply.setStatus("5");
                    this.save(leaveApply);
                }
                if (bmzrList.size() == 0) {
                    return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
                }

                variables.put("bmzrCount", bmzrList.size());
                processType = "leaveBack";
                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", "7002");
                extras.put("procDefKey", "81");
                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", "审批单：" + leaveApply.getNo());//设置标题；

            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);
                WorkActivityProcess pro = new WorkActivityProcess();
                pro.setId("");
                pro.setDelFlag("0");
                pro.preInsert();
                pro.setRemarks("销假申请");
                pro.setProcessKey("leaveBack");
                pro.setIsApproval("1");
                pro.setProcessInstanceId(processInstance.getId());
                pro.setCount(0);
                workActivityProcessDao.insert(pro);
            }
            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.setProcessInstanceId(processInstance.getId());
                workActivityProcess.setCount(1);
                workActivityProcess.setIsApproval("0");
                workActivityProcessService.insert(workActivityProcess);
                workActivityProcessService.insertAuditsByType(bmzrList, processInstance.getId(), 1, 1);
            }
            leaveApply.setProcessInstanceId(processInstance.getId());
            leaveApply.setStatus("6");
            this.save(leaveApply);
            workActivityProcessService.updateType(processInstance.getId(), "leaveBack");
        } catch (Exception e) {
            logger.error("启动审批流程异常：", e);
            return "启动审批流程异常:" + e.getMessage();
        }
        return "";
    }

    /**
     * 销假审核流程
     */
    @Transactional(readOnly = false)
    public String auditBackSave(LeaveApply leaveApply, List<User> auditUsers) {
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = leaveApply.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(leaveApply.getAct().getTaskId(), UserUtils.getUser().getId());
        } else {
            leaveApply.getAct().setFlag("yes");
        }
        String comment = "";
        if ("9".equals(leaveApply.getStatus())) {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[重新申请] " : "[已撤销] ");
        } else {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        leaveApply.setStatus(("yes".equals(leaveApply.getAct().getFlag()) ? "6" : "9"));
        Map<String, Object> vars = Maps.newHashMap();
        //业务逻辑对应的条件表达式
        String exp = "";
        String taskCount = "";
        String notifyRole = "";
        int key = 0;
        String enname = "";
        String str = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
        User createUser = userDao.get(leaveApply.getCurrentUser());
        String notifyTitle = "销假人：" + userDao.get(leaveApply.getApplyer()).getName();
        List<Activity> activitieList = activityService.getByProcessInstanceId(leaveApply.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(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("leaveBack")) {
            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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("9");
                        workActivityProcess.setIsApproval("2");
                        String returnBack = "-1";
                        for (Activity activity : activities) {
                            if (activity.getCount() == activityProcess.getCount()) {
                                notifyRole = activity.getName();
                                returnBack = activity.getReturnBack();
                                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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("7");
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("leaveBack");
            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(leaveApply.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                    } else {
                        notifyRole = "调整请假信息";
                        workActivityProcess.setIsApproval("2");
                        dao.updateBack(leaveApply);
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey) && count.contains("0")) {
                    notifyRole = "业务部负责人审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "bmzr";
                    if (!"yes".equals(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("7");
                    }
                    break;
                }

            }
        }
        // 设置意见
        leaveApply.getAct().setComment(("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment());
        leaveApply.preUpdate();
        // 提交流程任务
        vars.put(exp, "yes".equals(leaveApply.getAct().getFlag()) ? true : false);
        vars.put("passs", true);
        workActivityProcessService.updateProcess(workActivityProcess, workActivityMenu, key, taskCount, leaveApply.getProcessInstanceId(), taskDefKey, "modifyApply", leaveApply.getAct().getFlag(), comment, activities);
        // 提交流程任务
        actTaskService.complete(leaveApply.getAct().getTaskId(), leaveApply.getAct().getProcInsId(), leaveApply.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(leaveApply.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if (!state) {
            users.add(leaveApply.getCreateBy());
            if ("yes".equals(leaveApply.getAct().getFlag())) {
                leaveApply.setStatus("8");
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        leaveApply.getCreateBy(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "81",
                                        "0",
                                        "待通知",
                                        notifyRole));
                LeaveDetail detail=new LeaveDetail();
                detail.setLeaveId(leaveApply.getId());
                List<LeaveDetail> leaveDetails = leaveDetailDao.findList(detail);
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                double back = Integer.parseInt(sdf1.format(leaveApply.getBackTime()));
                if("2".equals(leaveApply.getBackStartType())){
                    back=back+0.5;
                }

                for (LeaveDetail leaveDetail : leaveDetails) {
                    Date stateTime = leaveDetail.getStartTime();
                    double start=Integer.parseInt(sdf1.format(stateTime));
                    Date endTime = leaveDetail.getEndTime();
                    double end=Integer.parseInt(sdf1.format(endTime));
                    String startType = leaveDetail.getStartType();
                    String endType = leaveDetail.getEndType();
                    if("2".equals(startType)){
                        start=start+0.5;
                    }
                     if("2".equals(endType)){
                        end=end+0.5;
                    }
                    if(back<=end&&back>=start){
                        //修改实际请假结束时间及請假時常
                        double d=0;
                        if("2".equals(leaveDetail.getLeaveType().getModel())){//工作日
                            d=this.holidays(sdf.format(leaveDetail.getStartTime()),
                                    sdf.format(leaveApply.getBackTime()),
                                    leaveDetail.getStartType(),
                                    leaveApply.getBackStartType());
                        }else{
                           d=getDay(leaveDetail.getStartTime(),leaveApply.getBackTime(), leaveDetail.getStartType(),leaveApply.getBackStartType());
                        }
                        leaveDetailDao.updateRealEndDate(leaveDetail.getId(),sdf.format(leaveApply.getBackTime()),leaveApply.getBackStartType(),String.valueOf(d));
                        leaveDetail.setRealEndTime(leaveApply.getBackTime());
                        this.saveLeaveCount(leaveDetail,d,leaveApply.getBasicInfo().getId());
                    }else if(back<start){
                        //修改是否有效
                        leaveDetailDao.updateIsUse(leaveDetail.getId());
                    }else{
                        this.saveLeaveCount(leaveDetail,Double.parseDouble(leaveDetail.getDays()),leaveApply.getBasicInfo().getId());
                    }
                }
                Office company = UserUtils.getSelectCompany();
                User user = UserUtils.getByCompanyAndUserId(leaveApply.getApplyer(),company.getId());
                WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
                workStaffBasicInfo.setUserId(leaveApply.getApplyer());
                workStaffBasicInfo.setCompany(company);
                List<WorkStaffBasicInfo> workStaffAchives = workStaffAchivesDao.getByCompanyInfo(workStaffBasicInfo);
                WorkStaffBasicInfo workStaffAchive = new WorkStaffBasicInfo();
                WorkAttendanceRule oaRule = new WorkAttendanceRule();
                if (workStaffAchives!=null && workStaffAchives.size()!=0) {
                    workStaffAchive = workStaffAchives.get(0);
                    //依据公司和规则编号查询规则
                    oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), workStaffAchive.getUserId(), "");
                    if (oaRule == null || StringUtils.isBlank(oaRule.getId())) {
                        oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), "", workStaffAchive.getOffice().getId());
                    }
                    if (oaRule == null) {
                        oaRule = new WorkAttendanceRule();
                        oaRule.setType("3");
                    }
                }
                Boolean status = false;

                Integer backTime = Integer.parseInt(sdf1.format(leaveApply.getBackTime()));
                if (StringUtils.isNotBlank(oaRule.getId()) && StringUtils.isNotBlank(workStaffAchive.getId()) && leaveDetails!=null && leaveDetails.size()!=0) {
                    for (LeaveDetail leaveDetail : leaveDetails) {
                        Date stateTime = leaveDetail.getStartTime();
                        Date endTime = leaveDetail.getEndTime();
                        String startType = leaveDetail.getStartType();
                        String endType = leaveDetail.getEndType();
                        LeaveType leaveType = leaveDetail.getLeaveType();
                      /*  int stateMonth = Integer.parseInt(stateTime.substring(5,7));
                        int endMonth = Integer.parseInt(endTime.substring(5,7));*/
                        List<Date> dates = findDates(stateTime, endTime);
                        for (Date date : dates) {
                            String time = sdf.format(date);
                            int iholidays = workAttendanceInfoService.isHolidays(time);
                            Integer dateInt = Integer.parseInt(sdf1.format(date));
                            if (iholidays == 0 || (iholidays != 0 && "1".equals(leaveType.getModel()))) {
                                int count = 3;
                                if (sdf.format(date).equals(sdf.format(stateTime))) {
                                    if (startType.equals("2")) {
                                        count = 2;
                                    }
                                }
                                if (sdf.format(date).equals(sdf.format(endTime))) {
                                    if (endType.equals("1")) {
                                        count = 1;
                                    }
                                }
                                if (workStaffAchive.getWorkEndDate() != null) {
                                    String end = sdf1.format(workStaffAchive.getWorkEndDate());
                                    if (Integer.parseInt(end) >= dateInt) {
                                        status = true;
                                    }
                                } else {
                                    status = true;
                                }
                                int holidays = 0;
                                if (status) {
                                    WorkAttendanceInfo workAttendanceInfo1 = new WorkAttendanceInfo();
                                    WorkAttendanceInfo workAttendanceInfo2 = new WorkAttendanceInfo();
                                    WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
                                    workAttendanceInfo.setStaffId(workStaffAchive.getId());
                                    workAttendanceInfo.setAttendanceDate(date);
                                    List<WorkAttendanceInfo> workAttendanceInfos = workAttendanceInfoService.findList(workAttendanceInfo);
                                    if (workAttendanceInfos != null && workAttendanceInfos.size() != 0) {
                                        if (workAttendanceInfos.size() == 1) {
                                            if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                workAttendanceInfo1 = workAttendanceInfos.get(0);
                                            } else {
                                                workAttendanceInfo2 = workAttendanceInfos.get(0);
                                            }
                                        } else {
                                            if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                workAttendanceInfo2 = workAttendanceInfos.get(1);
                                                workAttendanceInfo1 = workAttendanceInfos.get(0);
                                            } else {
                                                workAttendanceInfo1 = workAttendanceInfos.get(1);
                                                workAttendanceInfo2 = workAttendanceInfos.get(0);
                                            }
                                        }
                                    }
                                    if (dateInt>=backTime){
                                        workAttendanceInfoService.saveInfo(oaRule, oaRule.getType(), workStaffAchive.getId(), user, date, time, null, "", "", "",
                                                "4", "4", "", holidays, null,
                                                "", leaveType.getIsAttendance(), leaveType.getIsSubsidized(),
                                                "", "", null, "", count, workAttendanceInfo1.getId(), workAttendanceInfo2.getId());
                                    }else {
                                        workAttendanceInfoService.saveInfo(oaRule, oaRule.getType(), workStaffAchive.getId(), user, date, time, null, "", "", "",
                                                "4", "4", "", holidays, null,
                                                "", leaveType.getIsAttendance(), leaveType.getIsSubsidized(),
                                                "", "", null, "", count, workAttendanceInfo1.getId(), workAttendanceInfo2.getId());
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                if (!"7".equals(leaveApply.getStatus())) {
                    leaveApply.setStatus("9");
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(leaveApply.getId(),
                                            leaveApply.getCreateBy(),
                                            leaveApply.getCompanyId(),
                                            notifyTitle,
                                            str,
                                            "81",
                                            "0",
                                            "待通知",
                                            notifyRole));
                }
            }
            workActivityProcessService.deleteProcessIdAuditUsers(leaveApply.getProcessInstanceId());
        } else {
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("leaveBack")) {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                //users.addAll(userList);
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(leaveApply.getId(),
                                new User(),
                                leaveApply.getCompanyId(),
                                notifyTitle,
                                str,
                                "81",
                                "0",
                                "待审批",
                                notifyRole);
                List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
                        activities,
                        workProjectNotify,
                        taskDefKey,
                        leaveApply.getAct().getFlag(),
                        taskCount,
                        leaveApply.getCreateBy(),
                        leaveApply.getOfficeId(),
                        "81");
                for (WorkProjectNotify workProjectNotify1 : workProjectNotifys) {
                    users.add(workProjectNotify1.getUser());
                    workProjectNotify1.setId("");
                    workProjectNotify1.setIsNewRecord(false);
                    workProjectNotifyService
                            .save(workProjectNotify1);
                }

            } else {
                if (!"yes".equals(leaveApply.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(leaveApply.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(leaveApply.getId(),
                                            leaveApply.getCreateBy(),
                                            leaveApply.getCompanyId(),
                                            notifyTitle,
                                            str,
                                            "81",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add(leaveApply.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        new User(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "81",
                                        "0",
                                        "待审批",
                                        notifyRole);
                        users.addAll(auditUsers);
                        for (User user1 : auditUsers) {
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String, Object> extras = new HashMap<>();
                            extras.put("type", "7002");
                            extras.put("procDefKey", "81");
                            extras.put("id", workProjectNotify.getId());
                            UserUtils.pushInfoToApp(notifyTitle, str, extras, user1.getId());
                        }
                    } else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.addAll(userList);
                        users.add(leaveApply.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(leaveApply.getId(),
                                                leaveApply.getCreateBy(),
                                                leaveApply.getCompanyId(),
                                                notifyTitle,
                                                str,
                                                "81",
                                                "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());
            }
        }
        dao.update(leaveApply);
        return "保存审核意见成功！";
    }

    @Transactional(readOnly = false)
    public void cancelProcessBack(String id) throws Exception {
        LeaveApply leaveApply = this.get(id);
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(leaveApply.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(leaveApply.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList != null && userList.size() != 0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                UserUtils.pushIm(u.getId(), "销假人:" + user.getName() + ",请假编号:" + leaveApply.getNo() + " 强制撤销!");
            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            LeaveApply leave = new LeaveApply();
            leave.setId(id);
            leave.setStatus("7");
            leave.setProcessInstanceId(leaveApply.getProcessInstanceId());
            leave.preUpdate();
            this.updateStateById(leave);
            actTaskService.endProcessInstance(leaveApply.getProcessInstanceId(), "销假申请-撤回");
            dao.updateBack(leaveApply);
        }
    }
    @Transactional(readOnly = false)
    public void cancelProcessExtend(String id) throws Exception {
        LeaveApply leaveApply = this.get(id);
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(leaveApply.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(leaveApply.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList != null && userList.size() != 0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                UserUtils.pushIm(u.getId(), "请假人:" + user.getName() + ",请假编号:" + leaveApply.getNo() + " 强制撤销!");
            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            LeaveApply leave = new LeaveApply();
            leave.setId(id);
            leave.setStatus("11");
            leave.setProcessInstanceId(leaveApply.getProcessInstanceId());
            leave.preUpdate();
            this.updateStateById(leave);
            actTaskService.endProcessInstance(leaveApply.getProcessInstanceId(), "请假申请-撤回");
            dao.updateLongTime(leaveApply);
            dao.deleteDetail(leaveApply);
        }
    }
    @Transactional(readOnly = false)
    public void reject(LeaveApply leaveApply){
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        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())&&! "modifyApply".equals(p.getActivityTask())) {
                    workActivityProcessDao.delete(p);
                }
            }
        }
        workActivityProcessService.deleteProcessIdAuditUsers(leaveApply.getProcessInstanceId());
    }
    /**
     * 启动审批流程
     */
    @Transactional(readOnly = false)
    public String extendSave(LeaveApply leaveApply, String processInstanceId) {
        try {
            double days=Double.parseDouble(leaveApply.getLongTime());//请假天数
            Map<String, Object> variables = new HashMap<String, Object>();
            identityService.setAuthenticatedUserId(leaveApply.getCurrentUser().getId());
            User createUser = UserUtils.getUser();
            String contentStr = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
            userDao.get(leaveApply.getApplyer()).getName();
            String titleStr = "请假人：" + userDao.get(leaveApply.getApplyer()).getName();

            String businessKey = leaveApply.getId();
            Office office = UserUtils.getSelectOffice();
            WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c8lz88a9miiii75090499", office);
            // 启动流程
            String processType = workActivityMenu.getProcessType();
            StringBuffer buffer = new StringBuffer();
            Activity activity = new Activity();
            WorkProjectNotify workProjectNotify = UtilNotify
                    .saveNotify(leaveApply.getId(), null, leaveApply.getCompanyId(), titleStr, contentStr, "82", "0", "待审批", ""
                    );

            List<User> users = new ArrayList<>();
            List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "25", leaveApply.getCreateBy());
            List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld", 2, office.getId(), "25", leaveApply.getCreateBy());
            List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl", 3, office.getId(), "25", leaveApply.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(), "25", leaveApply.getCreateBy());
                        if (enusers.size() == 0) {
                            leaveApply.setStatus("5");
                            this.saveExtend(leaveApply);
                            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(), "25", leaveApply.getCreateBy());
                    }
                    //人员审批
                    if (StringUtils.isNotBlank(activity.getUser().getId())) {
                        users.add(activity.getUser());
                    }
                }
                workProjectNotify.setId("");
            } else {
                variables.put("bmzrList", bmzrList);
                if (bmzrList.size() == 0) {
                    leaveApply.setStatus("5");
                    this.saveExtend(leaveApply);
                }
                if (bmzrList.size() == 0) {
                    return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
                }

                variables.put("bmzrCount", bmzrList.size());
                processType = "leaveExtend";
                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", "7002");
                extras.put("procDefKey", "82");
                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", "审批单：" + leaveApply.getNo());//设置标题；

            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);
                WorkActivityProcess pro = new WorkActivityProcess();
                pro.setId("");
                pro.setDelFlag("0");
                pro.preInsert();
                pro.setRemarks("续假申请");
                pro.setProcessKey("leaveExtend");
                pro.setIsApproval("1");
                pro.setProcessInstanceId(processInstance.getId());
                pro.setCount(0);
                workActivityProcessDao.insert(pro);
            }
            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.setProcessInstanceId(processInstance.getId());
                workActivityProcess.setCount(1);
                workActivityProcess.setIsApproval("0");
                workActivityProcessService.insert(workActivityProcess);
                workActivityProcessService.insertAuditsByType(bmzrList, processInstance.getId(), 1, 1);
                if(days>1){
                    workActivityProcess.setCount(2);
                    workActivityProcess.setId("");
                    workActivityProcessService.save(workActivityProcess);
                    workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
                }
                if(days>3){
                    workActivityProcess.setCount(3);
                    workActivityProcess.setId("");
                    workActivityProcessService.save(workActivityProcess);
                    workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),3,0);
                }
            }
            leaveApply.setProcessInstanceId(processInstance.getId());
            leaveApply.setStatus("10");
            this.saveExtend(leaveApply);
            workActivityProcessService.updateType(processInstance.getId(), "leaveExtend");
        } catch (Exception e) {
            logger.error("启动审批流程异常：", e);
            return "启动审批流程异常:" + e.getMessage();
        }
        return "";
    }

    /**
     * 销假审核流程
     */
    @Transactional(readOnly = false)
    public String auditExtendSave(LeaveApply leaveApply, List<User> auditUsers) {
        // 对不同环节的业务逻辑进行操作
        double days=Double.parseDouble(leaveApply.getLongTime());//请假天数
        String taskDefKey = leaveApply.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(leaveApply.getAct().getTaskId(), UserUtils.getUser().getId());
        } else {
            leaveApply.getAct().setFlag("yes");
            updateExtendDetail(leaveApply);
            updateFile(leaveApply);
        }
        String comment = "";
        if ("12".equals(leaveApply.getStatus())) {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[重新申请] " : "[已撤销] ");
        } else {
            comment = ("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        leaveApply.setStatus(("yes".equals(leaveApply.getAct().getFlag()) ? "10" : "12"));
        Map<String, Object> vars = Maps.newHashMap();
        //业务逻辑对应的条件表达式
        String exp = "";
        String taskCount = "";
        String notifyRole = "";
        int key = 0;
        String enname = "";
        String str = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
        User createUser = userDao.get(leaveApply.getCurrentUser());
        String notifyTitle = "请假人：" + userDao.get(leaveApply.getApplyer()).getName();
        List<Activity> activitieList = activityService.getByProcessInstanceId(leaveApply.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(leaveApply.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("leaveExtend")) {
            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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("12");
                        workActivityProcess.setIsApproval("2");
                        String returnBack = "-1";
                        for (Activity activity : activities) {
                            if (activity.getCount() == activityProcess.getCount()) {
                                notifyRole = activity.getName();
                                returnBack = activity.getReturnBack();
                                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(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("11");
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("leaveExtend");
            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(leaveApply.getAct().getFlag())) {
                        leaveApply.getAct().setFlag("end");
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                        if(days>1){
                            leaveApply.getAct().setFlag("yes");
                            vars.put("fgldList", auditUsers);
                            vars.put("fgldCount",auditUsers.size());
                            workActivityProcessService.insertAuditsByType(auditUsers,leaveApply.getProcessInstanceId(),2,1);
                            notifyRole = "分管领导审核";
                            enname = "fgld";
                        }
                    } else {
                        notifyRole = "调整请假信息";
                        workActivityProcess.setIsApproval("2");
                        dao.updateLongTime(leaveApply);
                        dao.deleteDetail(leaveApply);
                    }
                    break;
                }  else if ("fgld".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(leaveApply.getAct().getFlag())) {
                        leaveApply.getAct().setFlag("end");
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                        if(days>3){
                            leaveApply.getAct().setFlag("yes");
                            vars.put("zjlList", auditUsers);
                            vars.put("zjlCount",auditUsers.size());
                            workActivityProcessService.insertAuditsByType(auditUsers,leaveApply.getProcessInstanceId(),3,1);
                            notifyRole = "总经理审核";
                            enname = "zjl";
                        }
                    } else {
                        notifyRole = "调整请假信息";
                        workActivityProcess.setIsApproval("2");
                        dao.updateLongTime(leaveApply);
                        dao.deleteDetail(leaveApply);
                    }
                    break;
                } else if ("zjl".equals(taskDefKey) && count.contains("3")) {
                    taskCount = "3";
                    exp = "pass";
                    if ("yes".equals(leaveApply.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                    } else {
                        notifyRole = "调整请假信息";
                        workActivityProcess.setIsApproval("2");
                        dao.updateLongTime(leaveApply);
                        dao.deleteDetail(leaveApply);
                    }
                    break;
                }else if ("modifyApply".equals(taskDefKey) && count.contains("0")) {
                    notifyRole = "业务部负责人审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "bmzr";
                    Office office = UserUtils.getSelectOffice();
                    List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "25", leaveApply.getCreateBy());
                    List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld", 2, office.getId(), "25", leaveApply.getCreateBy());
                    List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl", 3, office.getId(), "25", leaveApply.getCreateBy());
                    WorkActivityProcess workActivityProcess1 = new WorkActivityProcess();
                    workActivityProcess1.setProcessKey("leaveApply");
                    workActivityProcess1.setProcessInstanceId(leaveApply.getProcessInstanceId());
                    workActivityProcess1.setCount(1);
                    workActivityProcess1.setIsApproval("0");
                    workActivityProcessService.insert(workActivityProcess1);
                    workActivityProcessService.insertAuditsByType(bmzrList,leaveApply.getProcessInstanceId(), 1, 1);
                    if(days>1){
                        workActivityProcess1.setCount(2);
                        workActivityProcess1.setId("");
                        workActivityProcessService.save(workActivityProcess1);
                        workActivityProcessService.insertAuditsByType(fgldList,leaveApply.getProcessInstanceId(),2,0);
                    }
                    if(days>3){
                        workActivityProcess1.setCount(3);
                        workActivityProcess1.setId("");
                        workActivityProcessService.save(workActivityProcess1);
                        workActivityProcessService.insertAuditsByType(zjlList,leaveApply.getProcessInstanceId(),3,0);
                    }
                    if (!"yes".equals(leaveApply.getAct().getFlag())) {
                        leaveApply.setStatus("11");
                    }
                    break;
                }

            }
        }
        // 设置意见
        leaveApply.getAct().setComment(("yes".equals(leaveApply.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leaveApply.getAct().getComment());
        leaveApply.preUpdate();
        // 提交流程任务
        vars.put(exp, leaveApply.getAct().getFlag());
        vars.put("passs", true);
        if("end".equals(leaveApply.getAct().getFlag())){
            leaveApply.getAct().setFlag("yes");
        }
        workActivityProcessService.updateProcess(workActivityProcess, workActivityMenu, key, taskCount, leaveApply.getProcessInstanceId(), taskDefKey, "modifyApply", leaveApply.getAct().getFlag(), comment, activities);
        // 提交流程任务
        if("no".equals(leaveApply.getAct().getFlag())){
            this.reject(leaveApply);
        }
        actTaskService.complete(leaveApply.getAct().getTaskId(), leaveApply.getAct().getProcInsId(), leaveApply.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(leaveApply.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if (!state) {
            users.add(leaveApply.getCreateBy());
            if ("yes".equals(leaveApply.getAct().getFlag())||"end".equals(leaveApply.getAct().getFlag())) {
                leaveApply.setStatus("5");
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        leaveApply.getCreateBy(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "82",
                                        "0",
                                        "待通知",
                                        notifyRole));
                LeaveDetail detail=new LeaveDetail();
                detail.setLeaveId(leaveApply.getId());
                List<LeaveDetail> leaveDetails = leaveDetailDao.findList(detail);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Office company = UserUtils.getSelectCompany();
                User user = UserUtils.getByCompanyAndUserId(leaveApply.getApplyer(),company.getId());
                WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
                workStaffBasicInfo.setUserId(leaveApply.getApplyer());
                workStaffBasicInfo.setCompany(company);
                List<WorkStaffBasicInfo> workStaffAchives = workStaffAchivesDao.getByCompanyInfo(workStaffBasicInfo);
                WorkStaffBasicInfo workStaffAchive = new WorkStaffBasicInfo();
                WorkAttendanceRule oaRule = new WorkAttendanceRule();
                if (workStaffAchives!=null && workStaffAchives.size()!=0) {
                    workStaffAchive = workStaffAchives.get(0);
                    //依据公司和规则编号查询规则
                    oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), workStaffAchive.getUserId(), "");
                    if (oaRule == null || StringUtils.isBlank(oaRule.getId())) {
                        oaRule = workAttendanceRuleService.findAttendanceRuleByCompany(workStaffAchive.getCompany().getId(), "", workStaffAchive.getOffice().getId());
                    }
                    if (oaRule == null) {
                        oaRule = new WorkAttendanceRule();
                        oaRule.setType("3");
                    }
                }
                Boolean status = false;
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                if (StringUtils.isNotBlank(oaRule.getId()) && StringUtils.isNotBlank(workStaffAchive.getId()) && leaveDetails!=null && leaveDetails.size()!=0) {
                    for (LeaveDetail leaveDetail : leaveDetails) {
                        if (leaveDetail.getFlat().equals("2")) {
                            Date stateTime = leaveDetail.getStartTime();
                            Date endTime = leaveDetail.getEndTime();
                            String startType = leaveDetail.getStartType();
                            String endType = leaveDetail.getEndType();
                            LeaveType leaveType = leaveDetail.getLeaveType();
                      /*  int stateMonth = Integer.parseInt(stateTime.substring(5,7));
                        int endMonth = Integer.parseInt(endTime.substring(5,7));*/
                            List<Date> dates = findDates(stateTime, endTime);
                            for (Date date : dates) {
                                String time = sdf.format(date);
                                int iholidays = workAttendanceInfoService.isHolidays(time);
                                if (iholidays == 0 || (iholidays != 0 && "1".equals(leaveType.getModel()))) {
                                    Integer dateInt = Integer.parseInt(sdf1.format(date));
                                    int count = 3;
                                    if (sdf.format(date).equals(sdf.format(stateTime))) {
                                        if (startType.equals("2")) {
                                            count = 2;
                                        }
                                    }
                                    if (sdf.format(date).equals(sdf.format(endTime))) {
                                        if (endType.equals("1")) {
                                            count = 1;
                                        }
                                    }
                                    if (workStaffAchive.getWorkEndDate() != null) {
                                        String end = sdf1.format(workStaffAchive.getWorkEndDate());
                                        if (Integer.parseInt(end) >= dateInt) {
                                            status = true;
                                        }
                                    } else {
                                        status = true;
                                    }
                                    int holidays = 0;
                                    if (status) {
                                        WorkAttendanceInfo workAttendanceInfo1 = new WorkAttendanceInfo();
                                        WorkAttendanceInfo workAttendanceInfo2 = new WorkAttendanceInfo();
                                        WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
                                        workAttendanceInfo.setStaffId(workStaffAchive.getId());
                                        workAttendanceInfo.setAttendanceDate(date);
                                        List<WorkAttendanceInfo> workAttendanceInfos = workAttendanceInfoService.findList(workAttendanceInfo);
                                        if (workAttendanceInfos != null && workAttendanceInfos.size() != 0) {
                                            if (workAttendanceInfos.size() == 1) {
                                                if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                    workAttendanceInfo1 = workAttendanceInfos.get(0);
                                                } else {
                                                    workAttendanceInfo2 = workAttendanceInfos.get(0);
                                                }
                                            } else {
                                                if (workAttendanceInfos.get(0).getMorningAfternoon().equals("1")) {
                                                    workAttendanceInfo2 = workAttendanceInfos.get(1);
                                                    workAttendanceInfo1 = workAttendanceInfos.get(0);
                                                } else {
                                                    workAttendanceInfo1 = workAttendanceInfos.get(1);
                                                    workAttendanceInfo2 = workAttendanceInfos.get(0);
                                                }
                                            }
                                        }
                                        workAttendanceInfoService.saveInfo(oaRule, oaRule.getType(), workStaffAchive.getId(), user, date, time, null, "", "", "",
                                                "4", "4", "", holidays, null,
                                                "", leaveType.getIsAttendance(), leaveType.getIsSubsidized(),
                                                "", "", null, "", count, workAttendanceInfo1.getId(), workAttendanceInfo2.getId());
                                    }
                                }
                            }
                        }
                    }
                }

                //修改明细flat
                dao.updateDetailFlat(leaveApply);
            } else {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                if (!"11".equals(leaveApply.getStatus())) {
                    leaveApply.setStatus("12");
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(leaveApply.getId(),
                                            leaveApply.getCreateBy(),
                                            leaveApply.getCompanyId(),
                                            notifyTitle,
                                            str,
                                            "82",
                                            "0",
                                            "待通知",
                                            notifyRole));
                }
            }
            workActivityProcessService.deleteProcessIdAuditUsers(leaveApply.getProcessInstanceId());
        } else {
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("leaveExtend")) {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(leaveApply.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                //users.addAll(userList);
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(leaveApply.getId(),
                                new User(),
                                leaveApply.getCompanyId(),
                                notifyTitle,
                                str,
                                "82",
                                "0",
                                "待审批",
                                notifyRole);
                List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
                        activities,
                        workProjectNotify,
                        taskDefKey,
                        leaveApply.getAct().getFlag(),
                        taskCount,
                        leaveApply.getCreateBy(),
                        leaveApply.getOfficeId(),
                        "82");
                for (WorkProjectNotify workProjectNotify1 : workProjectNotifys) {
                    users.add(workProjectNotify1.getUser());
                    workProjectNotify1.setId("");
                    workProjectNotify1.setIsNewRecord(false);
                    workProjectNotifyService
                            .save(workProjectNotify1);
                }

            } else {
                if (!"yes".equals(leaveApply.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(leaveApply.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(leaveApply.getId(),
                                            leaveApply.getCreateBy(),
                                            leaveApply.getCompanyId(),
                                            notifyTitle,
                                            str,
                                            "82",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add(leaveApply.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(leaveApply.getId(),
                                        new User(),
                                        leaveApply.getCompanyId(),
                                        notifyTitle,
                                        str,
                                        "82",
                                        "0",
                                        "待审批",
                                        notifyRole);
                        users.addAll(auditUsers);
                        for (User user1 : auditUsers) {
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String, Object> extras = new HashMap<>();
                            extras.put("type", "7002");
                            extras.put("procDefKey", "82");
                            extras.put("id", workProjectNotify.getId());
                            UserUtils.pushInfoToApp(notifyTitle, str, extras, user1.getId());
                        }
                    } else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(leaveApply.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.addAll(userList);
                        users.add(leaveApply.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(leaveApply.getId(),
                                                leaveApply.getCreateBy(),
                                                leaveApply.getCompanyId(),
                                                notifyTitle,
                                                str,
                                                "82",
                                                "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());
            }
        }
        this.saveExtend(leaveApply);
        dao.update(leaveApply);
        return "保存审核意见成功！";
    }

    @Transactional(readOnly = false)
    public int startMonthTask(String firstDay, String lastDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        Date dBegin = null;
        Date dEnd=null;
        String year=lastDay.substring(0,4);
        AjaxJson ajaxJson = new AjaxJson();
        workCalendarService.queryHoliday(year, ajaxJson);
        Map<String, String> map = ajaxJson.getBody();
        String holidays = map.get("holidays");
        if(holidays==null||"".equals(holidays)){
            return -1;//未发布法定节假日
        }
        String workdays = map.get("workdays");
        int count = 0;
        try {
            dBegin = sdf.parse(firstDay);
            dEnd = sdf.parse(lastDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Date> lDate = findDates(dBegin, dEnd);
        for (Date d : lDate) {
            System.out.println(sf.format(d));
            if (holidays.contains(sf.format(d))) {
                continue;
            } else if (workdays.contains(sf.format(d))) {
                count++;
            } else if (!this.isWeek(sf.format(d))) {
                count++;
            }
        }
        return count;
    }
    public static Boolean isWeek(String day) {
        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyyMMdd");
        Date date= null;//取时间
        try {
            date = sdfDay.parse(day);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            int week  =  calendar.get(Calendar.DAY_OF_WEEK)-1;
            if (week==0 || week==6){
                return true;
            }else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }
    public int findHisTime(LeaveApply leaveApply){
        return dao.findHisTime(leaveApply);
    }
    public int findHisDate(LeaveApply leaveApply){
        return dao.findHisDate(leaveApply);
    }


    public Page<LeaveApply> getMangePage(Page<LeaveApply> page, LeaveApply leaveApply) {
        leaveApply.setPage(page);
        List newList=new ArrayList();
        List<LeaveApply> list=dao.getMange(leaveApply);
        if(list!=null&&list.size()>0){
            for(LeaveApply leaveApply1:list){
                LeaveApply leaveApply2=dao.getSumDays(leaveApply1.getStaffId());
                    leaveApply1.setSumDays(leaveApply2.getSumDays());
                    int count=dao.getResetState(leaveApply1.getStaffId());
                    if(count==0){
                        leaveApply1.setState("1");
                    }else{
                        leaveApply1.setState("0");//0未重置，1已重置
                    }
                    newList.add(leaveApply1);
            }
        }
        page.setList(newList);
        return page;
    }

    @Transactional(readOnly = false)
    public void reset(String basicInfoId) {
        LeaveCount leaveCount=new LeaveCount();
        leaveCount.setStaffId(basicInfoId);
        List<LeaveCount> list= leaveCountDao.findList(leaveCount);
       if(list!=null&&list.size()>0){
           for(LeaveCount leaveCount1:list){
               if("1".equals(leaveCount1.getLeaveType().getMethod())){
                   leaveCountDao.updateReset(leaveCount1.getId());
               }else{
                   leaveCountDao.delete(leaveCount1);
               }
           }
       }
    }

    //时间验证
    @Transactional(readOnly = false)
    public String validate(LeaveApply leaveApply){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        WorkStaffBasicInfo workStaffBasicInfo=this.getBasicInfo();
        List<LeaveDetail> leaveDetails=leaveDetailDao.findHisList(workStaffBasicInfo.getId());
        if(leaveApply.getLeaveDetailList()!=null&&leaveApply.getLeaveDetailList().size()>0){
            List<LeaveDetail> list=leaveApply.getLeaveDetailList();
            leaveDetails.addAll(list);
            for(int j=0;j<list.size();j++){
                LeaveDetail leaveDetail=list.get(j);
                if(leaveDetail.getLeaveType()!=null&&!"1".equals(leaveDetail.getDelFlag())){
                    leaveDetail.setRealEndTime(leaveDetail.getEndTime());
                    leaveDetail.setRealEndType(leaveDetail.getEndType());
                    Date stateTime = leaveDetail.getStartTime();
                    double start=Integer.parseInt(sdf1.format(stateTime));
                    Date realEndTime = leaveDetail.getRealEndTime();
                    double realEnd=Integer.parseInt(sdf1.format(realEndTime));
                    String startType = leaveDetail.getStartType();
                    String realEndType = leaveDetail.getRealEndType();
                    if("2".equals(startType)){
                        start=start+0.5;
                    }
                    if("2".equals(realEndType)){
                        realEnd=realEnd+0.5;
                    }
                    for(int i=0;i<leaveDetails.size();i++){
                        LeaveDetail detail=leaveDetails.get(i);
                        if(detail.getLeaveType()!=null&&!"1".equals(detail.getDelFlag())){
                            Date stateTime1 = detail.getStartTime();
                            double start1=Integer.parseInt(sdf1.format(stateTime1));
                            Date realEndTime1 = detail.getRealEndTime();
                            if(realEndTime1==null){
                                realEndTime1=detail.getEndTime();
                            }
                            double realEnd1=Integer.parseInt(sdf1.format(realEndTime1));
                            String startType1 = detail.getStartType();
                            String realEndType1 = detail.getRealEndType();
                            if(realEndType1==null){
                                realEndType1=detail.getEndType();
                            }
                            if("2".equals(startType1)){
                                start1=start1+0.5;
                            }
                            if("2".equals(realEndType1)){
                                realEnd1=realEnd1+0.5;
                            }
                            if(detail.getId()!=null&&leaveDetail.getId()!=null){
                                if(!detail.getId().equals(leaveDetail.getId())){
                                    if((start>=start1&&start<=realEnd1)||(realEnd>=start1&&realEnd<=realEnd1)
                                            ||(start1>=start&&start1<=realEnd)||(realEnd1>=start&&realEnd1<=realEnd)){
                                        return  "请假时间存在重叠情况！";
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /*for(LeaveDetail leaveDetail:leaveApply.getLeaveDetailList()){
                LeaveApply apply=new LeaveApply();
                if(leaveApply.getId()!=null&&!"".equals(leaveApply.getId())){
                    apply.setId(leaveApply.getId());
                }
                apply.setStartTime(leaveDetail.getStartTime());
                apply.setEndTime(leaveDetail.getEndTime());
                apply.setStaffId(workStaffBasicInfo.getId());
                int count =this.findHisTime(apply);
                if(count>0){
                    if(leaveApply.getStatus()==null||"1".equals(leaveApply.getStatus())||"5".equals(leaveApply.getStatus())){
                        if("1".equals(type)){
                            leaveApply.setStatus("1");
                            this.save(leaveApply);
                        }else if("2".equals(type)){
                            leaveApply.setStatus("5");
                            this.saveExtend(leaveApply);
                        }
                    }
                    return "请假时间与历史请假时间存在重叠情况！";
                }
                apply.setStartType(leaveDetail.getStartType());
                apply.setEndType(leaveDetail.getEndType());
                int count1 =this.findHisDate(apply);
                if(count1>0){
                    if(leaveApply.getStatus()==null||"1".equals(leaveApply.getStatus())||"5".equals(leaveApply.getStatus())){
                        if("1".equals(type)){
                            leaveApply.setStatus("1");
                            this.save(leaveApply);
                        }else if("2".equals(type)){
                            leaveApply.setStatus("5");
                            this.saveExtend(leaveApply);
                        }
                    }
                    return "请假时间与历史请假时间存在重叠情况！";
                }
            }*/
       }
       return "";

    }

    //时间验证
    @Transactional(readOnly = false)
    public String validateTime(Date startTime,String startType,Date endTime,String endType){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        WorkStaffBasicInfo workStaffBasicInfo=this.getBasicInfo();
        List<LeaveDetail> leaveDetails=leaveDetailDao.findListValidateTime(workStaffBasicInfo.getId());
                double start=Integer.parseInt(sdf1.format(startTime));
                double end=Integer.parseInt(sdf1.format(endTime));
                if("2".equals(startType)){
                    start=start+0.5;
                }
                if("2".equals(endType)){
                    end=end+0.5;
                }
                for(int i=0;i<leaveDetails.size();i++){
                    LeaveDetail detail=leaveDetails.get(i);
                    Date stateTime1 = detail.getStartTime();
                    double start1=Integer.parseInt(sdf1.format(stateTime1));
                    Date realEndTime1 = detail.getRealEndTime();
                    if(realEndTime1==null){
                        realEndTime1=detail.getEndTime();
                    }
                    double realEnd1=Integer.parseInt(sdf1.format(realEndTime1));
                    String startType1 = detail.getStartType();
                    String realEndType1 = detail.getRealEndType();
                    if(realEndType1==null){
                        realEndType1=detail.getEndType();
                    }
                    if("2".equals(startType1)){
                        start1=start1+0.5;
                    }
                    if("2".equals(realEndType1)){
                        realEnd1=realEnd1+0.5;
                    }
                        if((start>=start1&&start<=realEnd1)||(end>=start1&&end<=realEnd1)
                                ||(start1>=start&&start1<=end)||(realEnd1>=start&&realEnd1<=end)){
                            return  "请假时间存在重叠情况！";
                        }
                }
        return "";
    }

    public double holidays(String startDate, String endDate, String startType,String endType) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
            Date dBegin = null;
            Date dEnd=null;
            String year=endDate.substring(0,4);
            AjaxJson ajaxJson = new AjaxJson();
            workCalendarService.queryHoliday(year, ajaxJson);
            Map<String, String> map = ajaxJson.getBody();
            String holidays = map.get("holidays");
            String workdays = map.get("workdays");
            int count = 0;
            try {
                dBegin = sdf.parse(startDate);
                dEnd = sdf.parse(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<Date> lDate = DateUtils.findDates(dBegin, dEnd);
            for (Date d : lDate) {
                System.out.println(sf.format(d));
                if (holidays.contains(sf.format(d))) {
                    continue;
                } else if (workdays.contains(sf.format(d))) {
                    count++;
                } else if (!DateUtils.isWeek(sf.format(d))) {
                    count++;
                }
            }
            double c=count-1;
            if(count!=0){
                if("1".equals(startType) && "1".equals(endType) ){
                    c=c+0.5;
                }else if("1".equals(startType) && "2".equals(endType)){
                    c=c+1;
                }else if("2".equals(startType) && "2".equals(endType)){
                    c=c+0.5;
                } else if("2".equals(startType) && "1".equals(endType)){
                    c=c;
                }
            }else{
                c=0;
            }
        return c;
    }
    public static double getDay(Date satrtDate,Date endDate,String startType,String endType) {
        double days = (double) ((endDate.getTime() - satrtDate.getTime()) / (1000*3600*24));
        if("1".equals(startType) && "1".equals(endType)){
            days=days+0.5;
        }else if("1".equals(startType) && "2".equals(endType)){
            days=days+1;
        }else if("2".equals(startType) && "2".equals(endType)){
            days=days+0.5;
        } else if("2".equals(startType) && "1".equals(endType)){
            days=days;
        }
        return days;
    }

    public String getYear(int i){//获取上一年
        Date date = new Date();
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//设置起时间
        cal.add(Calendar.YEAR, i);//增加一年
        return sdfYear.format(cal.getTime());
}
    public String getNextDay(String time){//获取下一天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//设置起时间
        cal.add(Calendar.DATE, 1);//增加一天
        return sdf.format(cal.getTime());
    }
    public static void main(String[] args) {
       /* Date date = new Date();
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//设置起时间
        cal.add(Calendar.YEAR, -1);//增加一年
        System.out.println("输出::"+sdfYear.format(cal.getTime()));*/

    }
    //时间验证
    @Transactional(readOnly = false)
    public  void saveLeaveCount(LeaveDetail leaveDetail,double days,String staffId){
        //请假统计详情
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MMdd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        Date nowDate=new Date();
        String now=sdf2.format(nowDate);
        String start=sdf2.format(leaveDetail.getStartTime());
        double d=Integer.parseInt(now);
        double s=Integer.parseInt(start);
        //获取系统参数
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        String time= UserUtils.getSysParam("reset",UserUtils.getUser());
        String m="";
        String n="";
        String lastYear="";
        if(time!=null&&!"".equals(time)) {
            lastYear=this.getYear(-1)+"12"+time;
            m=sdfYear.format(nowDate)+"12"+time;
            n=sdfYear.format(nowDate)+"-12-"+time;
        }else{
            lastYear=this.getYear(-1)+"1231";
            m=sdfYear.format(nowDate)+"1231";
            n=sdfYear.format(nowDate)+"-12-31";
        }
        String year="";
        double nextDays=0;
        year=sdfYear.format(nowDate);
        double start1=Integer.parseInt(sdf1.format(leaveDetail.getStartTime()));
        Date realEndTime1 = leaveDetail.getRealEndTime();
        if(realEndTime1==null){
            realEndTime1=leaveDetail.getEndTime();
        }
        double realEnd1=Integer.parseInt(sdf1.format(realEndTime1));
        String startType1 = leaveDetail.getStartType();
        String realEndType1 = leaveDetail.getRealEndType();
        if(realEndType1==null){
            realEndType1=leaveDetail.getEndType();
        }
        if("2".equals(startType1)){
            start1=start1+0.5;
        }
        if("2".equals(realEndType1)){
            realEnd1=realEnd1+0.5;
        }
        double resetTime=Integer.parseInt(m)+0.5;
        double lastResetTime=Integer.parseInt(lastYear)+0.5;
        if(start1<=resetTime&&start1>lastResetTime){
            if(resetTime>start1&&start1<realEnd1){
                if("2".equals(leaveDetail.getLeaveType().getModel())){//工作日
                    days=this.holidays(sdf.format(leaveDetail.getStartTime()),
                            n,
                            leaveDetail.getStartType(),
                            "2");
                    nextDays=this.holidays(this.getNextDay(n),
                            sdf.format(realEndTime1),
                            "1",
                            realEndType1);
                }else{
                    try {
                        days=getDay(leaveDetail.getStartTime(),sdf.parse(n), leaveDetail.getStartType(),"2");
                        nextDays=getDay(sdf.parse(this.getNextDay(n)),realEndTime1, "1",realEndType1);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            LeaveCount leaveCount=new LeaveCount();
            leaveCount.setStaffId(staffId);
            leaveCount.setLeaveTypeId(leaveDetail.getLeaveTypeId());
            leaveCount.setYear(year);
            List<LeaveCount> leaveCounts=leaveCountService.findList(leaveCount);
            if(leaveCounts!=null&&leaveCounts.size()>0){
                LeaveCount leaveCount1=leaveCounts.get(0);
                double sum=Double.parseDouble(leaveCount1.getSums());
                int count=Integer.parseInt(leaveCount1.getCounts());
                leaveCount1.setCounts(String.valueOf(count+1));
                leaveCount1.setSums(String.valueOf(sum+days));
                leaveCount1.setUpdateDate(new Date());
                leaveCount1.setResetState("0");
                leaveCountDao.update(leaveCount1);
            }else{
                LeaveCount leaveCount2=new LeaveCount();
                leaveCount2.preInsert();
                leaveCount2.setCreateBy(UserUtils.getUser());
                leaveCount2.setUpdateDate(new Date());
                leaveCount2.setCreateDate(new Date());
                leaveCount2.setUpdateBy(UserUtils.getUser());
                leaveCount2.setDelFlag("0");
                leaveCount2.setStaffId(staffId);
                leaveCount2.setSums(String.valueOf(days));
                leaveCount2.setCounts("1");
                leaveCount2.setResetState("0");//未重置
                leaveCount2.setLeaveTypeId(leaveDetail.getLeaveTypeId());
                leaveCount2.setYear(year);
                leaveCountDao.insert(leaveCount2);
            }
        }
        }
    //请假管理重置定时方法
    @Transactional(readOnly = false)
    public void resetTask() {
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        String date=DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        Date nowDate=new Date();
        String nowYear=sdfYear.format(nowDate);
        LeaveCount l=new LeaveCount();
        l.setYear(nowYear);
        l.setResetState("0");
        List<LeaveCount> leaveCounts= leaveCountDao.findList(l);
        if(leaveCounts!=null&&leaveCounts.size()>0){
            for(LeaveCount leaveCount:leaveCounts){
                WorkStaffBasicInfo workStaffBasicInfo = workStaffAchivesDao.get(leaveCount.getStaffId());
                User u=userDao.get(workStaffBasicInfo.getUserId());
                String time= UserUtils.getSysParam("reset",u);
                if(time==null||"".equals(time)) {
                    time=nowYear+"-12-31";
                }else{
                    time=nowYear+"-12-"+time;
                }
                if(date.equals(time)){
                    if(Double.parseDouble(leaveCount.getLeaveType().getZero())>=Double.parseDouble(leaveCount.getSums())
                            ||"0".equals(leaveCount.getLeaveType().getZero())){
                        //统计下一年已经请假的天数
                        LeaveCount leaveCount2=new LeaveCount();
                        leaveCount2.preInsert();
                        leaveCount2.setCreateBy(u);
                        leaveCount2.setUpdateDate(new Date());
                        leaveCount2.setCreateDate(new Date());
                        leaveCount2.setUpdateBy(u);
                        leaveCount2.setDelFlag("0");
                        leaveCount2.setStaffId(leaveCount.getStaffId());
                        leaveCount2.setSums(String.valueOf(0));
                        leaveCount2.setCounts("1");
                        leaveCount2.setResetState("0");//未重置
                        leaveCount2.setLeaveTypeId(leaveCount.getLeaveTypeId());
                        leaveCount2.setYear(this.getYear(1));
                        leaveCountDao.insert(leaveCount2);
                       /* if("1".equals(leaveCount1.getLeaveType().getMethod())){
                            leaveCountDao.updateReset(leaveCount1.getId());
                        }else{
                            leaveCountDao.delete(leaveCount1);
                        }*/
                    }
                }
            }
        }
      
    }
    //请假管理重置定时方法
    @Transactional(readOnly = false)
    public void backTask() {
        List<LeaveApply> leaveApplyList=dao.getBackTaskList();
        if(leaveApplyList!=null&&leaveApplyList.size()>0){
            for(LeaveApply leaveApply:leaveApplyList){
                User applyer=userDao.get(leaveApply.getApplyer());
                String param=UserUtils.getSysParam("backState",applyer);
                if("是".equals(param)){
                    LeaveDetail detail=new LeaveDetail();
                    detail.setLeaveId(leaveApply.getId());
                    List<LeaveDetail> leaveDetails = leaveDetailDao.findList(detail);
                    leaveApply.setLeaveDetailList(leaveDetails);
                    leaveApply.setBackTime(new Date());
                    leaveApply.setBackStartType("2");
                    String processInstanceId=leaveApply.getProcessInstanceId();
                    try {
                        Map<String, Object> variables = new HashMap<String, Object>();
                        identityService.setAuthenticatedUserId(leaveApply.getApplyer());
                        String contentStr = "请假编号：" + leaveApply.getNo() + "，请假日期：" + DateUtils.formatDate(leaveApply.getApplyTime());
                        String titleStr = "销假人：" + applyer.getName();

                        String businessKey = leaveApply.getId();
                        Office office = officeDao.get(leaveApply.getOfficeId());
                        WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c8lz88a9miiii75090477", office);
                        // 启动流程
                        String processType = workActivityMenu.getProcessType();
                        StringBuffer buffer = new StringBuffer();
                        Activity activity = new Activity();
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(leaveApply.getId(), null, leaveApply.getCompanyId(), titleStr, contentStr, "81", "0", "待审批", ""
                                );
                        List<User> users = new ArrayList<>();
                        List<User> bmzrList = UserUtils.getByRoleActivityEnnameTask("bmzr", 2, office.getId(), "25", applyer);
                        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(), "25", leaveApply.getCreateBy());
                                    if (enusers.size() == 0) {
                                        leaveApply.setStatus("5");
                                        this.save(leaveApply);
                                    }
                                    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(), "25", leaveApply.getCreateBy());
                                }
                                //人员审批
                                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                                    users.add(activity.getUser());
                                }
                            }
                            workProjectNotify.setId("");
                        } else {
                            variables.put("bmzrList", bmzrList);
                            if (bmzrList.size() == 0) {
                                leaveApply.setStatus("5");
                                this.save(leaveApply);
                            }
                            if (bmzrList.size() == 0) {
                                System.out.println("系统自动发起销假：流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！");
                            }

                            variables.put("bmzrCount", bmzrList.size());
                            processType = "leaveBack";
                            users.addAll(bmzrList);
                        }
                        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", "7002");
                            extras.put("procDefKey", "81");
                            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", "审批单：" + leaveApply.getNo());//设置标题；

                        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);
                            WorkActivityProcess pro = new WorkActivityProcess();
                            pro.setId("");
                            pro.setDelFlag("0");
                            pro.preInsert();
                            pro.setRemarks("销假申请");
                            pro.setProcessKey("leaveBack");
                            pro.setIsApproval("1");
                            pro.setCreateBy(applyer);
                            pro.setUpdateBy(applyer);
                            pro.setProcessInstanceId(processInstance.getId());
                            pro.setCount(0);
                            workActivityProcessDao.insert(pro);
                        }
                        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.setProcessInstanceId(processInstance.getId());
                            workActivityProcess.setCreateBy(applyer);
                            workActivityProcess.setUpdateBy(applyer);
                            workActivityProcess.setCount(1);
                            workActivityProcess.setIsApproval("0");
                            workActivityProcessService.insert(workActivityProcess);
                            workActivityProcessService.insertAuditsByType(bmzrList, processInstance.getId(), 1, 1);
                        }
                        leaveApply.setProcessInstanceId(processInstance.getId());
                        leaveApply.setStatus("6");
                        this.save(leaveApply);
                        workActivityProcessService.updateType(processInstance.getId(), "leaveBack");
                    } catch (Exception e) {
                        logger.error("启动审批流程异常：", e);
                    }
                }

            }
        }
    }

    //验证上限天数
    @Transactional(readOnly = false)
    public String validateSumDays(LeaveApply leaveApply){
        if(leaveApply.getLeaveDetailList()!=null&&leaveApply.getLeaveDetailList().size()>0){
            List<LeaveDetail> list=leaveApply.getLeaveDetailList();
            Map<String,String> map=new HashMap<String,String>();
            for(int j=0;j<list.size();j++){
                LeaveDetail leaveDetail=list.get(j);
                if(leaveDetail.getLeaveType()!=null&&!"1".equals(leaveDetail.getDelFlag())){
                    String typeId=leaveDetail.getLeaveType().getId();
                    if(map.containsKey(typeId)){
                      double day= Double.parseDouble(map.get(typeId).toString())+Double.parseDouble(leaveDetail.getDays());
                        map.put(typeId,String.valueOf(day));
                    }else{
                        map.put(typeId,leaveDetail.getDays());
                    }
                }
            }
            for(String key : map.keySet()){
             String value = map.get(key);
             LeaveType leaveType=leaveTypeDao.get(key);
             if("1".equals(leaveType.getMaxDays())){//无上限
                 continue;
             }
                //单次或一次性
                if("3".equals(leaveType.getMethod())||"4".equals(leaveType.getMethod())){
                    if(Double.parseDouble(leaveType.getSetDays())<Double.parseDouble(value)){
                        return leaveType.getName()+"：超过上限天数！";
                    }
                }else if("2".equals(leaveType.getMethod())){//单次累计
                // 查询历史天数
                    String sumDay=leaveDetailDao.sumday(key,leaveApply.getId());
                    double d=Double.parseDouble(sumDay)+Double.parseDouble(value);
                    if(Double.parseDouble(leaveType.getSetDays())<d){
                        return leaveType.getName()+"：超过上限天数！";
                    }
                }else if("1".equals(leaveType.getMethod())){//年度累计
                    // 查询历史天数
                   //待定。。。。。。。。。。。。。
                    //。。。。。。。。。。。。。
                }

            }
        }
        return "";
    }
}