package com.jeeplus.modules.workgooutapply.service;

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
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.isignature.service.ISignatureDocumentService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workgooutapply.dao.WorkGoOutDao;
import com.jeeplus.modules.workgooutapply.entity.WorkGoOutInfo;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class WorkGoOutService extends CrudService<WorkGoOutDao, WorkGoOutInfo> {

    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private WorkActivityMenuService workActivityMenuService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private WorkActivityProcessService workActivityProcessService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    private WorkActivityProcessDao workActivityProcessDao;
    @Autowired
    private SerialNumTplService serialNumTplService;
    @Autowired
    private ISignatureDocumentService signatureDocumentService;

    public WorkGoOutInfo get(String id) {
        WorkGoOutInfo workGoOutInfo = super.get(id);
        if(workGoOutInfo!=null&&StringUtils.isNotBlank(workGoOutInfo.getId())){
            WorkClientAttachment attchment = new WorkClientAttachment();
            attchment.setAttachmentId(workGoOutInfo.getId());
            workGoOutInfo.setWorkAttachments(workClientAttachmentDao.findList(attchment));
        }
        return workGoOutInfo;
    }

    public Page<WorkGoOutInfo> findPage(Page<WorkGoOutInfo> page, WorkGoOutInfo workGoOutInfo) {
        workGoOutInfo.getSqlMap().put("dsf", dataScopeFilter(workGoOutInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_FIELD.getValue()));
        workGoOutInfo.setPage(page);
        page.setList(findList(workGoOutInfo));
        return page;
    }

    public List<WorkGoOutInfo> findList(WorkGoOutInfo workGoOutInfo) {
        return super.findList(workGoOutInfo);
    }

    @Transactional(readOnly = false)
    public String saveAtamp(WorkGoOutInfo workGoOutInfo) {
        save(workGoOutInfo);
        return this.startAudit(workGoOutInfo,workGoOutInfo.getProcessInstanceId());
    }

    @Transactional(readOnly = false)
    public void save(WorkGoOutInfo workGoOutInfo) {
        long t1 = System.currentTimeMillis();
        preSave(workGoOutInfo);
        super.save(workGoOutInfo);
        this.saveAttachments(workGoOutInfo);
        logger.info("保存项目外出申请耗时：{}ms",System.currentTimeMillis()-t1);
    }

    private void preSave(WorkGoOutInfo workGoOutInfo) {

        if(workGoOutInfo.getOffice()==null|| StringUtils.isBlank(workGoOutInfo.getOffice().getId())){
            workGoOutInfo.setOffice(UserUtils.getSelectOffice());
        }
        if(workGoOutInfo.getCompany()==null||StringUtils.isBlank(workGoOutInfo.getCompany().getId())){
            workGoOutInfo.setCompany(UserUtils.getSelectCompany());
        }
        if (StringUtils.isBlank(workGoOutInfo.getNum())){
            String serialNum = serialNumTplService.genSerialNum(UserUtils.getUser().getCompany(), WorkGoOutInfo.SERIAL_BIZCODE);
            workGoOutInfo.setNum(serialNum);
        }
    }

    private void saveAttachments(WorkGoOutInfo workGoOutInfo) {
        for (WorkClientAttachment workClientAttachment : workGoOutInfo.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(workGoOutInfo.getId());
                workClientAttachment.setAttachmentFlag(WorkGoOutInfo.ATTACHMENT_TYPE);
                workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
                    workClientAttachment.preInsert();
                    workClientAttachmentDao.insert(workClientAttachment);
                    signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workGoOutInfo.getNum());
                } else {
                    workClientAttachment.preUpdate();
                    workClientAttachmentDao.update(workClientAttachment);
                }
            } else {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
    }

    /**
     * 启动审批流程
     */
    private String startAudit(WorkGoOutInfo workGoOutInfo, String processInstanceId){
        long t1 = System.currentTimeMillis();
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(workGoOutInfo.getCurrentUser().getId());
        String contentStr = "申请编号："+workGoOutInfo.getNum()+"，申请日期："+ DateUtils.formatDate(workGoOutInfo.getCreateDate());
        String titleStr = "申请人："+ workGoOutInfo.getSubmiter().getName();

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

        List<User> users = new ArrayList<>();
        List<User> gzrList = null;
        List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"11",workGoOutInfo.getCreateBy());
        List<User> fgldList = UserUtils.getByRoleActivityEnname("fzjl",3,office.getId(),"11",workGoOutInfo.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(),"11",workGoOutInfo.getCreateBy());
                    if (enusers.size()==0){
                        workGoOutInfo.setState(ProjectStatusEnum.TSTORE.getValue());
                        this.updateStateById(workGoOutInfo);
                        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(),"11",workGoOutInfo.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            if (bmzrList.size()==0){
                workGoOutInfo.setState(ProjectStatusEnum.TSTORE.getValue());
                this.updateStateById(workGoOutInfo);
                return "流程审批人不能为空,部门负责人下无用户,请联系管理员！";
            }
            variables.put("bmzrList", bmzrList);
            variables.put("bmzrCount",bmzrList.size());
            processType = "notadministrativeAtamp";
            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","92");
            extras.put("id",workProjectNotify.getId());
            UserUtils.pushInfoToApp(titleStr, contentStr,extras,u.getId());
        }
        long t2 = System.currentTimeMillis();
        UserUtils.pushIm(userIds,contentStr);
        logger.info("项目签章推送消息耗时：{}ms",System.currentTimeMillis()-t2);

        variables.put("busId", businessKey);
        variables.put("type", processType);
        variables.put("title", "审批单：" + workGoOutInfo.getNum());//设置标题；

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
            workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
            workActivityProcessService.deleteProcessInstanceId(processInstanceId);
            workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
        }
        List<Activity> list = workActivityMenu.getActivities();
        if (list != null && list.size() != 0) {
            workActivityProcessService.saveList(list, processInstance.getId());
        } else {
            WorkActivityProcess workActivityProcess = new WorkActivityProcess();
            workActivityProcess.setProcessKey(processType);
            workActivityProcess.setCount(1);
            workActivityProcess.setProcessInstanceId(processInstance.getId());
            workActivityProcess.setIsApproval("0");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcess.setCount(2);
            workActivityProcess.setId("");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcessService.insertAuditsByType(bmzrList,processInstance.getId(),1,1);
            workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
        }
        workGoOutInfo.setProcessInstanceId(processInstance.getId());
        workGoOutInfo.setState(ProjectStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(workGoOutInfo);
        logger.info("启动项目外出审批流程耗时：{}ms",System.currentTimeMillis()-t1);
        return "";
    }


    private void updateStateById(WorkGoOutInfo workGoOutInfo) {
        dao.updateProcessIdAndStatus(workGoOutInfo);
    }

    /**
     * 外出审核流程
     */
    @Transactional(readOnly = false)
    public String goOutProjectSave(WorkGoOutInfo workGoOutInfo,List<User> auditUsers) {
        String str = "申请编号："+workGoOutInfo.getNum()+"，申请人："+workGoOutInfo.getSubmiter().getName() +"，申请日期："+ DateUtils.formatDate(workGoOutInfo.getCreateDate());
        String title = "申请人："+ workGoOutInfo.getSubmiter().getName();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workGoOutInfo.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(workGoOutInfo.getAct().getTaskId(), UserUtils.getUser().getId());
        }else {
            workGoOutInfo.getAct().setFlag("yes");
            this.saveAttachments(workGoOutInfo);
        }
        String comment = "";
        if (ProjectStatusEnum.REJECTED.getValue() == workGoOutInfo.getState()){
            comment = ("yes".equals(workGoOutInfo.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
        }else {
            comment = ("yes".equals(workGoOutInfo.getAct().getFlag())?"[同意] ":"[驳回] ")+ workGoOutInfo.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        workGoOutInfo.setState(("yes".equals(workGoOutInfo.getAct().getFlag()) ? ProjectStatusEnum.IN_APRL.getValue() : ProjectStatusEnum.REJECTED.getValue()));
        Map<String, Object> vars = Maps.newHashMap();
        //业务逻辑对应的条件表达式
        String exp = "";
        String taskCount = "";
        String notifyRole = "";
        int key = 0;
        String enname = "";
        List<Activity> activitieList = activityService.getByProcessInstanceId(workGoOutInfo.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(workGoOutInfo.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && (!workActivityMenu.getProcessType().equals("notadministrativeAtamp"))) {
            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(workGoOutInfo.getAct().getFlag())) {
                        notifyRole = "调整外出请求信息";
                        workGoOutInfo.setState(ProjectStatusEnum.REJECTED.getValue());
                        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")){
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setId("");
                    workActivityProcess.setCount(0);
                    if (!"yes".equals(workGoOutInfo.getAct().getFlag())) {
                        workGoOutInfo.setState(ProjectStatusEnum.RECALL.getValue());
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("notadministrativeAtamp");
            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(workGoOutInfo.getAct().getFlag())) {
                        workActivityProcessService.insertAuditsByType(auditUsers, workGoOutInfo.getProcessInstanceId(), 2, 1);

                        notifyRole = "副总经理审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "fgld";
                        vars.put("fgldCount", auditUsers.size());
                        vars.put("fgldList", auditUsers);
                        vars.put("pass",true);
                    } else {
                        notifyRole = "调整申请";
                        workActivityProcess.setIsApproval("2");
                        vars.put("pass",false);
                    }
                    break;
                } else if ("fgld".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(workGoOutInfo.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                        vars.put("pass",true);
                    } else {
                        notifyRole = "调整外出请求信息";
                        workActivityProcess.setIsApproval("2");
                        vars.put("pass",false);
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey) && count.contains("0")) {
                    notifyRole = "部门负责人审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "bmzr";
                    if (!"yes".equals(workGoOutInfo.getAct().getFlag())) {
                        workGoOutInfo.setState(ProjectStatusEnum.RECALL.getValue());
                    }
                    break;
                } else if ("apply_end".equals(taskDefKey)) {
                }
            }
        }
        // 设置意见
        workGoOutInfo.getAct().setComment(("yes".equals(workGoOutInfo.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workGoOutInfo.getAct().getComment());
        workGoOutInfo.preUpdate();
        // 提交流程任务
        vars.put(exp, "yes".equals(workGoOutInfo.getAct().getFlag()) ? true : false);
        vars.put("passs", true);
        workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount, workGoOutInfo.getProcessInstanceId(),taskDefKey,"modifyApply", workGoOutInfo.getAct().getFlag(),comment, activities);
        // 提交流程任务
        actTaskService.complete(workGoOutInfo.getAct().getTaskId(), workGoOutInfo.getAct().getProcInsId(), workGoOutInfo.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(workGoOutInfo.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if (!state) {
            users.add(workGoOutInfo.getCreateBy());
            if ("yes".equals(workGoOutInfo.getAct().getFlag())) {
                workGoOutInfo.setState(ProjectStatusEnum.SIGNED.getValue());
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workGoOutInfo.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(workGoOutInfo.getId(),
                                        workGoOutInfo.getCreateBy(),
                                        workGoOutInfo.getCompany().getId(),
                                        title,
                                        str,
                                        "92",
                                        "0",
                                        "待通知",
                                        notifyRole));

            } else {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workGoOutInfo.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                if (ProjectStatusEnum.RECALL.getValue() != workGoOutInfo.getState()){
                    workGoOutInfo.setState(ProjectStatusEnum.REJECTED.getValue());
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workGoOutInfo.getId(),
                                            workGoOutInfo.getCreateBy(),
                                            workGoOutInfo.getCompany().getId(),
                                            title,
                                            str,
                                            "92",
                                            "0",
                                            "待通知",
                                            notifyRole));
                }
            }
            workActivityProcessService.deleteProcessIdAuditUsers(workGoOutInfo.getProcessInstanceId());
        } else {
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && (!workActivityMenu.getProcessType().equals("notadministrativeAtamp"))) {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workGoOutInfo.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                //users.addAll(userList);
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(workGoOutInfo.getId(),
                                new User(),
                                workGoOutInfo.getCompany().getId(),
                                title,
                                str,
                                "92",
                                "0",
                                "待审批",
                                notifyRole);
                List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
                        activities,
                        workProjectNotify,
                        taskDefKey,
                        workGoOutInfo.getAct().getFlag(),
                        taskCount,
                        workGoOutInfo.getCreateBy(),
                        workGoOutInfo.getOffice().getId(),
                        "92");
                for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
                    users.add(workProjectNotify1.getUser());
                    workProjectNotify1.setId("");
                    workProjectNotify1.setIsNewRecord(false);
                    workProjectNotifyService
                            .save(workProjectNotify1);
                }

            } else {
                if (!"yes".equals(workGoOutInfo.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(workGoOutInfo.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    //users.addAll(userList);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workGoOutInfo.getId(),
                                            workGoOutInfo.getCreateBy(),
                                            workGoOutInfo.getCompany().getId(),
                                            title,
                                            str,
                                            "92",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add( workGoOutInfo.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workGoOutInfo.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(workGoOutInfo.getId(),
                                        new User(),
                                        workGoOutInfo.getCompany().getId(),
                                        title,
                                        str,
                                        "92",
                                        "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<>();
                            if(enname.contains("bmzr")||enname.contains("fgld")) {
                                extras.put("type", "7002");
                            }else {
                                extras.put("type", "7001");
                            }
                            extras.put("procDefKey","92");
                            extras.put("id",workProjectNotify.getId());
                            UserUtils.pushInfoToApp(title, str,extras,user1.getId());
                        }
                    }else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workGoOutInfo.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.add(workGoOutInfo.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(workGoOutInfo.getId(),
                                                workGoOutInfo.getCreateBy(),
                                                workGoOutInfo.getCompany().getId(),
                                                title,
                                                str,
                                                "92",
                                                "0",
                                                "重新申请",
                                                notifyRole));
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
            for (User u : users) {
                UserUtils.pushIm(u.getId(),title);
            }
        }
        if (StringUtils.isNotBlank(title) && userList!=null && userList.size()!=0) {
            for (User u : userList) {
                UserUtils.pushMeIm(u.getId());
            }
        }
        dao.update(workGoOutInfo);
        return "保存审核意见成功！";
    }

    @Transactional(readOnly = false)
    public void cancelProcess(WorkGoOutInfo workGoOutInfo) throws Exception {
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(workGoOutInfo.getProcessInstanceId());
        process.setIsApproval("0");
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(workGoOutInfo.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workGoOutInfo.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() +",外出请求审批编号:"+workGoOutInfo.getNum() +" 强制撤销!");

            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            WorkGoOutInfo workGoOut = new WorkGoOutInfo();
            workGoOut.setId(workGoOutInfo.getId());
            workGoOut.setState(ProjectStatusEnum.RECALL.getValue());
            workGoOut.setProcessInstanceId(workGoOutInfo.getProcessInstanceId());
            workGoOut.preUpdate();
            this.updateStateById(workGoOut);
            actTaskService.endProcessInstance(workGoOutInfo.getProcessInstanceId(), "外出申请-撤回");
        }
    }

    @Transactional(readOnly = false)
    public void delete(WorkGoOutInfo workGoOutInfo) {
        super.delete(workGoOutInfo);
        if(workGoOutInfo.getWorkAttachments()!=null&&workGoOutInfo.getWorkAttachments().size()>0){
            for (WorkClientAttachment workClientAttachment : workGoOutInfo.getWorkAttachments()) {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workGoOutInfo.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users!=null && users.size()!=0){
            for (User user:users){
                UserUtils.pushMeIm(user.getId());
            }
        }
    }
}
