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

import java.util.*;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.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.service.UserService;
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.workdailyroutine.entity.WorkDailyRoutine;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutineDetail;
import com.jeeplus.modules.workdailyroutine.service.WorkDailyRoutineService;
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.workreceiptssettle.entity.WorkReceiptsSettle;
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.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workincomingmessage.entity.WorkIncomingMessage;
import com.jeeplus.modules.workincomingmessage.dao.WorkIncomingMessageDao;

/**
 * 收文管理Service
 * @author ssrh
 * @version 2018-07-10
 */
@Service
@Transactional(readOnly = true)
public class WorkIncomingMessageService extends CrudService<WorkIncomingMessageDao, WorkIncomingMessage> {

    @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 WorkDailyRoutineService workDailyRoutineService;

	public WorkIncomingMessage get(String id) {
        WorkIncomingMessage workIncomingMessage = super.get(id);
        if(workIncomingMessage!=null&& StringUtils.isNotBlank(workIncomingMessage.getId())){
            WorkClientAttachment attchment = new WorkClientAttachment();
            attchment.setAttachmentId(workIncomingMessage.getId());
            List<WorkClientAttachment> attachments = workClientAttachmentDao.findList(attchment);
            workIncomingMessage.setWorkAttachments(attachments);
        }
        this.queryHandlers(workIncomingMessage);
        return workIncomingMessage;
	}

    private void queryHandlers(WorkIncomingMessage workIncomingMessage) {
        if(workIncomingMessage!=null&&StringUtils.isNotBlank(workIncomingMessage.getHandler())){
            String[] split = workIncomingMessage.getHandler().split(",");
            List<User> userList = userDao.queryListByIds(split);
            workIncomingMessage.setHandlerList(userList);
            workIncomingMessage.setLeaderNameStr(Collections3.extractToString(userList, "name", ","));
        }
    }

    public List<WorkIncomingMessage> findList(WorkIncomingMessage workIncomingMessage) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workIncomingMessage.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_INCOMINGMESSAGE.getValue());
            workIncomingMessage.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findList(workIncomingMessage);
	}
	
	public Page<WorkIncomingMessage> findPage(Page<WorkIncomingMessage> page, WorkIncomingMessage workIncomingMessage) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workIncomingMessage.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_INCOMINGMESSAGE.getValue());
            workIncomingMessage.getSqlMap().put("dsf", dataScopeSql);
        }
        workIncomingMessage.setPage(page);
        List<WorkIncomingMessage> list = dao.findList(workIncomingMessage);
        if(list!=null&&list.size()>0){
            for (WorkIncomingMessage incomingMessage : list) {
                this.queryHandlers(incomingMessage);
            }
        }
        page.setList(list);
        return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkIncomingMessage workIncomingMessage) {
	    if(workIncomingMessage.getOffice()==null){
	        workIncomingMessage.setOffice(UserUtils.getSelectOffice());
        }
        if(workIncomingMessage.getCompany()==null){
	        workIncomingMessage.setCompany(UserUtils.getSelectCompany());
        }
        User createBy = workIncomingMessage.getCreateBy();
        if(createBy != null){
            createBy = UserUtils.get(createBy.getId());
        }else {
            createBy = UserUtils.getUser();
            workIncomingMessage.setCreateBy(createBy);
        }
        if(StringUtils.isBlank(workIncomingMessage.getNum())){
            workIncomingMessage.setNum(serialNumTplService.genSerialNum(createBy.getCompany(),workIncomingMessage.SERIAL_BIZCODE));
        }
		super.save(workIncomingMessage);
        this.saveAttachments(workIncomingMessage);
    }

    private void saveAttachments(WorkIncomingMessage workIncomingMessage) {
        for (WorkClientAttachment workClientAttachment : workIncomingMessage.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(workIncomingMessage.getId());
                workClientAttachment.setAttachmentFlag(WorkIncomingMessage.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(WorkIncomingMessage workIncomingMessage) {
		super.delete(workIncomingMessage);
		if(workIncomingMessage.getWorkAttachments()!=null&&workIncomingMessage.getWorkAttachments().size()>0){
            for (WorkClientAttachment workClientAttachment : workIncomingMessage.getWorkAttachments()) {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workIncomingMessage.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 void cancelProcess(WorkIncomingMessage workIncomingMessage) throws Exception {

        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(workIncomingMessage.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(workIncomingMessage.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workIncomingMessage.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()+",收文审批编号:"+workIncomingMessage.getNum() +" 强制撤销!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    //ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
                }*/
                UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",收文审批编号:"+workIncomingMessage.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);

            //结束该流程,设为"撤销"状态月
            WorkIncomingMessage incomingMessage = new WorkIncomingMessage();
            incomingMessage.setId(workIncomingMessage.getId());
            incomingMessage.setState(ProjectStatusEnum.RECALL.getValue());
            incomingMessage.setProcessInstanceId(workIncomingMessage.getProcessInstanceId());
            incomingMessage.preUpdate();
            this.updateStateById(incomingMessage);
            actTaskService.endProcessInstance(workIncomingMessage.getProcessInstanceId(), "收文申请-撤回");
        }
    }

    private void updateStateById(WorkIncomingMessage incomingMessage) {
        dao.updateProcessIdAndStatus(incomingMessage);
    }

    /**
     * 审核流程
     */
    @Transactional(readOnly = false)
    public String auditSave(WorkIncomingMessage workIncomingMessage,List<User> auditUsers) {
        String str = "收文编号："+ workIncomingMessage.getNum()+"，来文字号："+workIncomingMessage.getWordSize()+"，来文单位："+workIncomingMessage.getIncomePart()+"，来文日期："+ DateUtils.formatDate(workIncomingMessage.getIncomeDate());
        String title = "来文标题："+ workIncomingMessage.getTitle();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workIncomingMessage.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) &&!taskDefKey.contains("audit")) {
            actTaskService.claim(workIncomingMessage.getAct().getTaskId(), UserUtils.getUser().getId());
        }else {
            workIncomingMessage.getAct().setFlag("yes");
            this.saveAttachments(workIncomingMessage);
        }
        String comment = "";
        if (ProjectStatusEnum.REJECTED.getValue() == workIncomingMessage.getState()){
            comment = ("yes".equals(workIncomingMessage.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
        }else {
            comment = ("yes".equals(workIncomingMessage.getAct().getFlag())?"[同意] ":"[驳回] ")+ workIncomingMessage.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        workIncomingMessage.setState(("yes".equals(workIncomingMessage.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(workIncomingMessage.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(workIncomingMessage.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("incomeMessage")) {
            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(workIncomingMessage.getAct().getFlag())) {
                        notifyRole = "调整收文信息";
                        workIncomingMessage.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(workIncomingMessage.getAct().getFlag())) {
                        workIncomingMessage.setState(ProjectStatusEnum.RECALL.getValue());
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("incomeMessage");
            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 ("xzzg".equals(taskDefKey) && count.contains("1")) {
                    taskCount = "1";
                    exp = "pass";
                    if ("yes".equals(workIncomingMessage.getAct().getFlag())) {
                        workActivityProcessService.insertAuditsByType(auditUsers,workIncomingMessage.getProcessInstanceId(),2,1);
                        vars.put("zjlList", auditUsers);
                        vars.put("zjlCount",auditUsers.size());
                        notifyRole = "总经理审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "zjl";
                    } else {
                        notifyRole = "调整收文信息";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("zjl".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(workIncomingMessage.getAct().getFlag())) {
                        notifyRole = "申请人审批";
                        workActivityProcess.setIsApproval("1");
                    } else {
                        notifyRole = "调整收文信息";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                }else if ("consume".equals(taskDefKey) && count.contains("3")) {
                    taskCount = "3";
                    exp = "pass";
                    if ("yes".equals(workIncomingMessage.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
                    notifyRole = "行政主管审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "xzzg";
                    if (!"yes".equals(workIncomingMessage.getAct().getFlag())) {
                        workIncomingMessage.setState(ProjectStatusEnum.RECALL.getValue());
                    }
                    break;
                } else if ("apply_end".equals(taskDefKey)) {
                }

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

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

            } else {
                if (!"yes".equals(workIncomingMessage.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(workIncomingMessage.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    //users.addAll(userList);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workIncomingMessage.getId(),
                                            workIncomingMessage.getCreateBy(),
                                            workIncomingMessage.getCompany().getId(),
                                            title,
                                            str,
                                            "55",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add( workIncomingMessage.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workIncomingMessage.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(workIncomingMessage.getId(),
                                        new User(),
                                        workIncomingMessage.getCompany().getId(),
                                        title,
                                        str,
                                        "55",
                                        "0",
                                        "待审批",
                                        notifyRole);
                        List<User> userLists = UserUtils.getByRoleActivityEnnames(enname, workIncomingMessage.getOffice().getId(),"11", workIncomingMessage.getCreateBy());
                        users.addAll(userLists);
                        for (User user1:userLists){
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String,Object> extras = new HashMap<>();
                            extras.put("type","7001");
                            extras.put("procDefKey","55");
                            if(enname.contains("zjl")){
                                extras.put("type","7003");
                            }
                            extras.put("id",workProjectNotify.getId());
                            UserUtils.pushInfoToApp(title,str,extras,user1.getId());
                        }

                    }else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workIncomingMessage.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.add(workIncomingMessage.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(workIncomingMessage.getId(),
                                                workIncomingMessage.getCreateBy(),
                                                workIncomingMessage.getCompany().getId(),
                                                title,
                                                str,
                                                "55",
                                                "0",
                                                "待审批",
                                                notifyRole));
                    }
                    if ("zjl".equals(taskDefKey)){
                        if(StringUtils.isNotBlank(workIncomingMessage.getHandler())) {
                            this.createDailyRoutine(workIncomingMessage);
                        }else {
                            workIncomingMessage.setDailyId("NoN");
                        }
                    }
                }
            }
        }
        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(workIncomingMessage);
        return "保存审核意见成功！";
    }

    private void createDailyRoutine(WorkIncomingMessage workIncomingMessage) {
        WorkIncomingMessage incomingMessage = this.get(workIncomingMessage.getId());
        WorkDailyRoutine workDailyRoutine = new WorkDailyRoutine();
        workDailyRoutine.setName(incomingMessage.getTitle()+"-"+incomingMessage.getWordSize()+"-"+incomingMessage.getIncomePart());
        workDailyRoutine.setSource("收文发送");
        workDailyRoutine.setStatus("未完成");
        workDailyRoutine.setCreateBy(UserUtils.getUser());
        workDailyRoutine.setCreateDate(new Date());
        workDailyRoutine.setSourceId(incomingMessage.getId());
        workDailyRoutine.setRemarks(workIncomingMessage.getOpinion());
        List<WorkClientAttachment> workAttachments = incomingMessage.getWorkAttachments();
        if(workAttachments!=null&&workAttachments.size()>0){
            for (WorkClientAttachment workAttachment : workAttachments) {
                workAttachment.setId("");
            }
        }
        workDailyRoutine.setWorkAttachments(workAttachments);
        List<WorkDailyRoutineDetail> detailList = new ArrayList<>();
        String handlers = workIncomingMessage.getHandler();
        if(StringUtils.isNotBlank(handlers)){
            String[] split = handlers.split(",");
            WorkDailyRoutineDetail routineDetail = null;
            for (String uid : split) {
                routineDetail = new WorkDailyRoutineDetail();
                routineDetail.setOperator(new User(uid));
                detailList.add(routineDetail);
            }
        }
        workDailyRoutine.setDetailList(detailList);
        workDailyRoutineService.save(workDailyRoutine);
        workIncomingMessage.setDailyId(workDailyRoutine.getId());
    }

    @Transactional(readOnly = false)
    public String saveIncome(WorkIncomingMessage workIncomingMessage) {
        User createBy = workIncomingMessage.getCreateBy();
        if(createBy != null){
            createBy = UserUtils.get(createBy.getId());
        }else {
            createBy = UserUtils.getUser();
            workIncomingMessage.setCreateBy(createBy);
        }
        if(StringUtils.isBlank(workIncomingMessage.getNum())){
            workIncomingMessage.setNum(serialNumTplService.genSerialNum(createBy.getCompany(),workIncomingMessage.SERIAL_BIZCODE));
        }
        if(workIncomingMessage.getOffice()==null||StringUtils.isBlank(workIncomingMessage.getOffice().getId())){
            workIncomingMessage.setOffice(UserUtils.getSelectOffice());
        }
        if(workIncomingMessage.getCompany()==null||StringUtils.isBlank(workIncomingMessage.getCompany().getId())){
            workIncomingMessage.setCompany(UserUtils.getSelectCompany());
        }
        super.save(workIncomingMessage);
        this.saveAttachments(workIncomingMessage);
        return this.startAudit(workIncomingMessage,workIncomingMessage.getProcessInstanceId());
    }

    /**
     * 启动审批流程
     */
    private String startAudit(WorkIncomingMessage workIncomingMessage, String processInstanceId){

        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(workIncomingMessage.getCurrentUser().getId());
        User createUser = UserUtils.getUser();
        String contentStr = "收文编号："+ workIncomingMessage.getNum()+"，来文字号："+workIncomingMessage.getWordSize()+"，来文单位："+workIncomingMessage.getIncomePart()+"，来文日期："+ DateUtils.formatDate(workIncomingMessage.getIncomeDate());
        String titleStr = "来文标题："+ workIncomingMessage.getTitle();

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

        List<User> users = new ArrayList<>();
        List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"11",workIncomingMessage.getCreateBy());
        List<User> xzzgList = UserUtils.getByRoleActivityEnname("xzzg",3,office.getId(),"11",workIncomingMessage.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",workIncomingMessage.getCreateBy());
                    if (enusers.size()==0){
                        workIncomingMessage.setState(ProjectStatusEnum.TSTORE.getValue());
                        this.updateStateById(workIncomingMessage);
                        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",workIncomingMessage.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            //variables.put("xzzgList", xzzgList);
            if (zjlList.size()==0 || xzzgList.size()==0){
                workIncomingMessage.setState(ProjectStatusEnum.TSTORE.getValue());
                this.updateStateById(workIncomingMessage);
            }
            if (xzzgList.size()==0){
                return "流程审批人不能为空,角色行政主管下无用户,请联系管理员！";
            }
                /*if (xzzgList.size()==0){
                    return "流程审批人不能为空,行政主管下无用户,请联系管理员！";
                }*/
            //variables.put("xzzgCount",xzzgList.size());
            processType = "incomeMessage";
            users.addAll(xzzgList);
        }
        List<String> userIds = new ArrayList<>(users.size());
        for (User u : users){
            userIds.add(u.getId());
            workProjectNotify.setUser(u);
            workProjectNotify.setId("");
            workProjectNotify.setNotifyRole("行政主管审批");
            workProjectNotifyService.save(workProjectNotify);
            Map<String,Object> extras = new HashMap<>();
            extras.put("type","7001");
            extras.put("procDefKey","55");
            extras.put("id",workProjectNotify.getId());
            UserUtils.pushInfoToApp(titleStr, contentStr,extras,u.getId());
        }
        UserUtils.pushIm(userIds,contentStr);
        variables.put("xzzgCount",xzzgList.size());
        variables.put("xzzgList",xzzgList);
        variables.put("busId", businessKey);
        variables.put("type", processType);
        variables.put("title", "审批单：" + workIncomingMessage.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.setProcessInstanceId(processInstance.getId());
            workActivityProcess.setIsApproval("0");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcess.setCount(2);
            workActivityProcess.setId("");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcess.setCount(3);
            workActivityProcess.setId("");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcessService.insertAuditsByType(xzzgList,processInstance.getId(),1,1);
            workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),2,0);
            ArrayList<User> users1 = new ArrayList<>();
            users1.add(workIncomingMessage.getCreateBy());
            workActivityProcessService.insertAuditsByType(users1,processInstance.getId(),3,0);
        }
        workIncomingMessage.setProcessInstanceId(processInstance.getId());
        workIncomingMessage.setState(ProjectStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(workIncomingMessage);
        return "";
    }
}