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

import java.util.*;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
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.DictUtils;
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.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.worksendmessage.dao.WorkSendMessageDetailDao;
import org.activiti.engine.ActivitiObjectNotFoundException;
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 com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.worksendmessage.entity.WorkSendMessage;
import com.jeeplus.modules.worksendmessage.dao.WorkSendMessageDao;

/**
 * 发文管理Service
 * @author ssrh
 * @version 2018-07-12
 */
@Service
@Transactional(readOnly = true)
public class WorkSendMessageService extends CrudService<WorkSendMessageDao, WorkSendMessage> {

    @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 WorkSendMessageDetailDao workSendMessageDetailDao;

	public WorkSendMessage get(String id) {
        WorkSendMessage workSendMessage = super.get(id);
        return workSendMessage;
	}

    public void queryDetails(WorkSendMessage workSendMessage) {
        if(workSendMessage!=null&& StringUtils.isNotBlank(workSendMessage.getId())){
            WorkClientAttachment attchment = new WorkClientAttachment();
            attchment.setAttachmentId(workSendMessage.getId());
            workSendMessage.setWorkAttachments(workClientAttachmentDao.findList(attchment));
            workSendMessage.setOfficeList(this.queryOfficeLists(workSendMessage));
            workSendMessage.setUserList(this.queryUserLists(workSendMessage));
        }
    }

    private List<User> queryUserLists(WorkSendMessage workSendMessage) {
        return dao.queryUserLists(workSendMessage);
    }

    private List<Office> queryOfficeLists(WorkSendMessage workSendMessage) {
        return dao.queryOfficeLists(workSendMessage);
    }

    public List<WorkSendMessage> findList(WorkSendMessage workSendMessage) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workSendMessage.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_SENDMESSAGE.getValue());
            workSendMessage.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findList(workSendMessage);
	}
	
	public Page<WorkSendMessage> findPage(Page<WorkSendMessage> page, WorkSendMessage workSendMessage) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workSendMessage.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_SENDMESSAGE.getValue());
            workSendMessage.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findPage(page, workSendMessage);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkSendMessage workSendMessage) {
        preSave(workSendMessage);
		super.save(workSendMessage);
		saveAttachments(workSendMessage);
		saveUserList(workSendMessage);
		saveOfficeList(workSendMessage);
	}

    private void saveOfficeList(WorkSendMessage workSendMessage) {
        List<Office> officeList = workSendMessage.getOfficeList();
        if(officeList ==null|| officeList.size()<=0){
            return;
        }
        workSendMessageDetailDao.deleteHandlers(workSendMessage.getId(),1);
        Iterator<Office> iterator = officeList.iterator();
        while (iterator.hasNext()){
            Office next = iterator.next();
            if (next==null||StringUtils.isBlank(next.getId())){
                iterator.remove();
            }
        }
        if(officeList ==null|| officeList.size()<=0){
            return;
        }
        HashMap<String, Object> map = new HashMap<>(5);
        map.put("messageId", workSendMessage.getId());
        map.put("handlerList", officeList);
        map.put("flag", 1);
        workSendMessageDetailDao.batchInsert(map);
    }

    private void saveUserList(WorkSendMessage workSendMessage) {
        List<User> userList = workSendMessage.getUserList();
        if(userList ==null|| userList.size()<=0){
            return;
        }
        workSendMessageDetailDao.deleteHandlers(workSendMessage.getId(),0);
        Iterator<User> iterator = userList.iterator();
        while (iterator.hasNext()){
            User next = iterator.next();
            if (next==null||StringUtils.isBlank(next.getId())){
                iterator.remove();
            }
        }
        if(userList ==null|| userList.size()<=0){
            return;
        }
        HashMap<String, Object> map = new HashMap<>(5);
        map.put("messageId", workSendMessage.getId());
        map.put("handlerList", userList);
        map.put("flag", 0);
        workSendMessageDetailDao.batchInsert(map);
    }

    private void preSave(WorkSendMessage workSendMessage) {
        if(workSendMessage.getOffice()==null){
            workSendMessage.setOffice(UserUtils.getSelectOffice());
}
        if(workSendMessage.getCompany()==null){
	        workSendMessage.setCompany(UserUtils.getSelectCompany());
        }
        if(StringUtils.isBlank(workSendMessage.getNum())){
            String serialNum = serialNumTplService.genSerialNum(workSendMessage.getCompany(), WorkSendMessage.getBizeCode(workSendMessage.getDocType()));
            workSendMessage.setNum(serialNum);
        }
    }

    private void saveAttachments(WorkSendMessage workSendMessage) {
        for (WorkClientAttachment workClientAttachment : workSendMessage.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(workSendMessage.getId());
                workClientAttachment.setAttachmentFlag(WorkSendMessage.ATTACHMENT_TYPE);
                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 delete(WorkSendMessage workSendMessage) {
		super.delete(workSendMessage);
	}

    @Transactional(readOnly = false)
    public String saveMessage(WorkSendMessage workSendMessage) {
        this.save(workSendMessage);
        return this.startAudit(workSendMessage,workSendMessage.getProcessInstanceId());
    }

    private String startAudit(WorkSendMessage workSendMessage, String processInstanceId) {
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(workSendMessage.getCurrentUser().getId());
        String contentStr = "发文文号："+workSendMessage.getNum()+"，发文类型："+ DictUtils.getMainDictLabel(workSendMessage.getDocType(),"doc_type","")+"，发文日期："+ DateUtils.formatDate(workSendMessage.getCreateDate());
        String titleStr = "发文标题："+ workSendMessage.getTitle();

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

        List<User> users = new ArrayList<>();
        List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",3,workSendMessage.getOffice().getId(),"11",workSendMessage.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",workSendMessage.getCreateBy());
                    if (enusers.size()==0){
                        workSendMessage.setState(ProjectStatusEnum.TSTORE.getValue());
                        this.updateStatusById(workSendMessage);
                        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",workSendMessage.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            if (zjlList.size()==0 ){
                workSendMessage.setState(ProjectStatusEnum.TSTORE.getValue());
                this.updateStatusById(workSendMessage);
            }
            if (zjlList.size()==0){
                return "流程审批人不能为空,总经理下无用户,请联系管理员！";
            }
            processType = "workSendMessage";
            users.addAll(zjlList);
        }
        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","62");
            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", "审批单：" + workSendMessage.getNum());//设置标题；

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
        //        workReceiptsSettle.setProcessInstance(processInstance);
        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.setIsApproval("0");
            workActivityProcess.setProcessInstanceId(processInstance.getId());
            workActivityProcessService.save(workActivityProcess);
            workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),1,1);
        }
        workSendMessage.setProcessInstanceId(processInstance.getId());
        workSendMessage.setState(ProjectStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(workSendMessage);
        return "";
    }

    private void updateStatusById(WorkSendMessage workSendMessage) {
        dao.updateStatusById(workSendMessage);
    }

    @Transactional(readOnly = false)
    public void cancelProcess(WorkSendMessage workSendMessage) throws Exception {
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(workSendMessage.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(workSendMessage.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workSendMessage.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList!=null && userList.size()!=0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                /*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn : toUserConns) {
                    String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 申请人:"+ user.getName()+",发文审批编号:"+workSendMessage.getNum() +" 强制撤销!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    //ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
                }*/
                UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",发文审批编号:"+workSendMessage.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);

            //结束该流程,设为"撤销"状态月
            WorkSendMessage sendMessage = new WorkSendMessage();
            sendMessage.setId(workSendMessage.getId());
            sendMessage.setState(ProjectStatusEnum.RECALL.getValue());
            sendMessage.setProcessInstanceId(workSendMessage.getProcessInstanceId());
            sendMessage.preUpdate();
            dao.updateProcessIdAndStatus(sendMessage);
            actTaskService.endProcessInstance(workSendMessage.getProcessInstanceId(), "发文申请-撤回");
        }
    }

    @Transactional(readOnly = false)
    public String auditSave(WorkSendMessage workSendMessage,List<User> auditUsers) {
        try {
            String str = "发文文号："+workSendMessage.getNum()+"，发文类型："+ DictUtils.getMainDictLabel(workSendMessage.getDocType(),"doc_type","")+"，发文日期："+ DateUtils.formatDate(workSendMessage.getCreateDate());
            String title = "发文标题："+ workSendMessage.getTitle();
            // 对不同环节的业务逻辑进行操作
            String taskDefKey = workSendMessage.getAct().getTaskDefKey();
            if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
                actTaskService.claim(workSendMessage.getAct().getTaskId(), UserUtils.getUser().getId());
            }else {
                workSendMessage.getAct().setFlag("yes");
                this.save(workSendMessage);
            }
            String comment = "";
            if (ProjectStatusEnum.REJECTED.getValue() == workSendMessage.getState()){
                comment = ("yes".equals(workSendMessage.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
            }else {
                comment = ("yes".equals(workSendMessage.getAct().getFlag())?"[同意] ":"[驳回] ")+ workSendMessage.getAct().getComment();
            }
            //yes 的时候状态为审核通过 否则为未通过
            //1 审核中 2 未通过
            workSendMessage.setState(("yes".equals(workSendMessage.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(workSendMessage.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(workSendMessage.getProcessInstanceId());
            List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
            List<Activity> activities = workActivityMenu.getActivities();
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workSendMessage")) {
                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(workSendMessage.getAct().getFlag())) {
                            notifyRole = "调整发文";
                            workSendMessage.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(workSendMessage.getAct().getFlag())) {
                            workSendMessage.setState(ProjectStatusEnum.RECALL.getValue());
                            workActivityProcess.setIsApproval("2");
                        } else {
                            workActivityProcess.setIsApproval("1");
                        }
                        break;
                    }
                }
            } else {
                workActivityMenu.setProcessType("workSendMessage");
                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 ("zjl".equals(taskDefKey) && count.contains("1")) {
                        taskCount = "1";
                        exp = "pass";
                        if ("yes".equals(workSendMessage.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 = "zjl";
                        if (!"yes".equals(workSendMessage.getAct().getFlag())) {
                            workSendMessage.setState(ProjectStatusEnum.RECALL.getValue());
                        }
                        break;
                    } else if ("apply_end".equals(taskDefKey)) {
                    }

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

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

                } else {
                    if (!"yes".equals(workSendMessage.getAct().getFlag())) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workSendMessage.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList);
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(workSendMessage.getId(),
                                                workSendMessage.getCreateBy(),
                                                workSendMessage.getCompany().getId(),
                                                title,
                                                str,
                                                "62",
                                                "0",
                                                "重新申请",
                                                notifyRole));
                        users.add( workSendMessage.getCreateBy());
                    } else {
                        if (StringUtils.isNotBlank(enname)) {
                            WorkProjectNotify notify = new WorkProjectNotify();
                            notify.setNotifyId(workSendMessage.getId());
                            userList = workProjectNotifyService.readByNotifyId(notify);
                            //users.addAll(userList1);
                            WorkProjectNotify workProjectNotify = UtilNotify
                                    .saveNotify(workSendMessage.getId(),
                                            new User(),
                                            workSendMessage.getCompany().getId(),
                                            title,
                                            str,
                                            "62",
                                            "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","62");
                                extras.put("id",workProjectNotify.getId());
                                UserUtils.pushInfoToApp(title, str,extras,user1.getId());
                            }
                        }else {
                            WorkProjectNotify notify = new WorkProjectNotify();
                            notify.setNotifyId(workSendMessage.getId());
                            userList = workProjectNotifyService.readByNotifyId(notify);
                            users.add(workSendMessage.getCreateBy());
                            workProjectNotifyService
                                    .save(UtilNotify
                                            .saveNotify(workSendMessage.getId(),
                                                    workSendMessage.getCreateBy(),
                                                    workSendMessage.getCompany().getId(),
                                                    title,
                                                    str,
                                                    "62",
                                                    "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(workSendMessage);
            if(ProjectStatusEnum.SIGNED.getValue() == workSendMessage.getState()){
                this.sendMessage(workSendMessage);
            }
            return "保存审核意见成功！";
        }catch (ActivitiObjectNotFoundException e){
            logger.error("ActivitiObjectNotFoundException e:",e);
            return "流程已审批，不能重新审批！";
        }catch (Exception e){
            logger.error("Exception e:",e);
            return "保存审核意见失败！！";
        }
    }

    private void sendMessage(WorkSendMessage workSendMessage)throws Exception {
	    try {
            this.queryDetails(workSendMessage);
            String contentStr = "发文标题："+workSendMessage.getTitle()+",发文文号："+workSendMessage.getNum()+"，发文类型："+ DictUtils.getMainDictLabel(workSendMessage.getDocType(),"doc_type","")+"，发文日期："+ DateUtils.formatDate(workSendMessage.getCreateDate());
            String titleStr = "您收到"+workSendMessage.getOffice().getName()+"的发文，请查阅！";
            String remark = "待通知";
            WorkProjectNotify workProjectNotify = UtilNotify.saveNotify(workSendMessage.getId(), null, workSendMessage.getCompany().getId(),
                    titleStr, contentStr, "73", "0", remark, "");
            List<User> userList = workSendMessage.getUserList();
            List<Office> officeList = workSendMessage.getOfficeList();
            User user = new User();
            Set<String> userIds = new HashSet<>(userList.size());
            for (User u : userList) {
                userIds.add(u.getId());
            }
            for (Office office : officeList) {
                user.setOffice(office);
                List<User> users = userDao.findUserByOfficeId(user);
                if (users != null && users.size() > 0) {
                    for (User user1 : users) {
                        userIds.add(user1.getId());
                    }
                }
            }
            for (String userId : userIds) {
                workProjectNotify.setUser(new User(userId));
                workProjectNotify.setId("");
                workProjectNotify.setNotifyRole("");
                workProjectNotifyService.save(workProjectNotify);
            }
            UserUtils.pushIm(new ArrayList<String>(userIds), contentStr);
        }catch (Exception e){
	        throw e;
        }
    }

    public Page<WorkSendMessage> findMemberPage(Page<WorkSendMessage> page, WorkSendMessage workSendMessage) {
        workSendMessage.setPage(page);
        page.setList(dao.queryMemberPage(workSendMessage));
        return page;
    }
}