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

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

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.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.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.workincomingmessage.entity.WorkIncomingMessage;
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.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.workadministrativeatamp.entity.WorkAdministrativeAtamp;
import com.jeeplus.modules.workadministrativeatamp.dao.WorkAdministrativeAtampDao;

/**
 * 行政盖章Service
 * @author ssrh
 * @version 2018-07-10
 */
@Service
@Transactional(readOnly = true)
public class WorkAdministrativeAtampService extends CrudService<WorkAdministrativeAtampDao, WorkAdministrativeAtamp> {
    @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 WorkAdministrativeAtamp get(String id) {
        WorkAdministrativeAtamp workAdministrativeAtamp = super.get(id);
        if(workAdministrativeAtamp!=null&&StringUtils.isNotBlank(workAdministrativeAtamp.getId())){
            WorkClientAttachment attchment = new WorkClientAttachment();
            attchment.setAttachmentId(workAdministrativeAtamp.getId());
            workAdministrativeAtamp.setWorkAttachments(workClientAttachmentDao.findList(attchment));
        }
        return workAdministrativeAtamp;
    }
	
	public List<WorkAdministrativeAtamp> findList(WorkAdministrativeAtamp workAdministrativeAtamp) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workAdministrativeAtamp.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_ADMINISTRATIVEATAMP.getValue());
            workAdministrativeAtamp.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findList(workAdministrativeAtamp);
	}
	
	public Page<WorkAdministrativeAtamp> findPage(Page<WorkAdministrativeAtamp> page, WorkAdministrativeAtamp workAdministrativeAtamp) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workAdministrativeAtamp.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_ADMINISTRATIVEATAMP.getValue());
            workAdministrativeAtamp.getSqlMap().put("dsf", dataScopeSql);
        }
        int count = dao.queryCount(workAdministrativeAtamp);
        page.setCount(count);
        page.setCountFlag(false);
        workAdministrativeAtamp.setPage(page);
        List<WorkAdministrativeAtamp> recordsList = dao.findList(workAdministrativeAtamp);
        page.setList(recordsList);
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkAdministrativeAtamp workAdministrativeAtamp) {
        long t1 = System.currentTimeMillis();
        preSave(workAdministrativeAtamp);
		super.save(workAdministrativeAtamp);
		this.saveAttachments(workAdministrativeAtamp);
		logger.info("保存行政签章耗时：{}ms",System.currentTimeMillis()-t1);
	}

    private void preSave(WorkAdministrativeAtamp workAdministrativeAtamp) {
        if(workAdministrativeAtamp.getOffice()==null|| StringUtils.isBlank(workAdministrativeAtamp.getOffice().getId())){
            workAdministrativeAtamp.setOffice(UserUtils.getSelectOffice());
        }
        if(workAdministrativeAtamp.getCompany()==null||StringUtils.isBlank(workAdministrativeAtamp.getCompany().getId())){
            workAdministrativeAtamp.setCompany(UserUtils.getSelectCompany());
        }
        if (StringUtils.isBlank(workAdministrativeAtamp.getNum())){
            String serialNum = serialNumTplService.genSerialNum(workAdministrativeAtamp.getComSign(), WorkAdministrativeAtamp.SERIAL_BIZCODE);
            workAdministrativeAtamp.setNum(serialNum);
        }
    }

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


    private void saveAttachments(WorkAdministrativeAtamp workAdministrativeAtamp) {
        for (WorkClientAttachment workClientAttachment : workAdministrativeAtamp.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(workAdministrativeAtamp.getId());
                workClientAttachment.setAttachmentFlag(WorkAdministrativeAtamp.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(),workAdministrativeAtamp.getNum());
                } else {
                    workClientAttachment.preUpdate();
                    workClientAttachmentDao.update(workClientAttachment);
                }
            } else {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
    }

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

    /**
     * 启动审批流程
     */
    private String startAudit(WorkAdministrativeAtamp workAdministrativeAtamp, String processInstanceId){
        long t1 = System.currentTimeMillis();
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(workAdministrativeAtamp.getCurrentUser().getId());
        String contentStr = "申请编号："+workAdministrativeAtamp.getNum()+"，文档类型："+ DictUtils.getDictLabel(workAdministrativeAtamp.getDocType(),"sign_doc_type","")+"，印章类型："+DictUtils.getMainDictLabel(workAdministrativeAtamp.getSealType(),"seal_type","")+"，申请日期："+ DateUtils.formatDate(workAdministrativeAtamp.getCreateDate());
        String titleStr = "签章公司："+ workAdministrativeAtamp.getComSign().getName();

        String businessKey = workAdministrativeAtamp.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(workAdministrativeAtamp.getId(),
                        null,
                        workAdministrativeAtamp.getCompany().getId(),
                        titleStr,
                        contentStr,
                        "56",
                        "0",
                        "待审批",
                        ""
                );

        List<User> users = new ArrayList<>();
        List<User> bmzrList = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"11",workAdministrativeAtamp.getCreateBy());
        List<User> fgldList = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"11",workAdministrativeAtamp.getCreateBy());
        List<User> gzrList = UserUtils.getByRoleActivityEnname("gzr",3,workAdministrativeAtamp.getComSign().getId(),"11",workAdministrativeAtamp.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",workAdministrativeAtamp.getCreateBy());
                    if (enusers.size()==0){
                        workAdministrativeAtamp.setState(ProjectStatusEnum.TSTORE.getValue());
                        this.updateStateById(workAdministrativeAtamp);
                        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",workAdministrativeAtamp.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            if (bmzrList.size()==0){
                workAdministrativeAtamp.setState(ProjectStatusEnum.TSTORE.getValue());
                this.updateStateById(workAdministrativeAtamp);
                return "流程审批人不能为空,部门负责人下无用户,请联系管理员！";
            }
            processType = "administrativeAtamp";
            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","56");
            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", "审批单：" + workAdministrativeAtamp.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(bmzrList,processInstance.getId(),1,1);
            workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
            workActivityProcessService.insertAuditsByType(gzrList,processInstance.getId(),3,0);
        }
        workAdministrativeAtamp.setProcessInstanceId(processInstance.getId());
        workAdministrativeAtamp.setState(ProjectStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(workAdministrativeAtamp);
        logger.info("启动行政签章审批流程耗时：{}ms",System.currentTimeMillis()-t1);
        return "";
    }

    /**
     * 审核流程
     */
    @Transactional(readOnly = false)
    public String auditSave(WorkAdministrativeAtamp workAdministrativeAtamp,List<User> auditUsers) {
        String str = "申请编号："+workAdministrativeAtamp.getNum()+"，文档类型："+ DictUtils.getDictLabel(workAdministrativeAtamp.getDocType(),"sign_doc_type","")+"，印章类型："+DictUtils.getMainDictLabel(workAdministrativeAtamp.getSealType(),"seal_type","")+"，申请日期："+ DateUtils.formatDate(workAdministrativeAtamp.getCreateDate());
        String title = "签章公司："+ workAdministrativeAtamp.getComSign().getName();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workAdministrativeAtamp.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(workAdministrativeAtamp.getAct().getTaskId(), UserUtils.getUser().getId());
        }else {
            workAdministrativeAtamp.getAct().setFlag("yes");
            this.saveAttachments(workAdministrativeAtamp);
        }
        String comment = "";
        if (ProjectStatusEnum.REJECTED.getValue() == workAdministrativeAtamp.getState()){
            comment = ("yes".equals(workAdministrativeAtamp.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
        }else {
            comment = ("yes".equals(workAdministrativeAtamp.getAct().getFlag())?"[同意] ":"[驳回] ")+ workAdministrativeAtamp.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        workAdministrativeAtamp.setState(("yes".equals(workAdministrativeAtamp.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(workAdministrativeAtamp.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(workAdministrativeAtamp.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("administrativeAtamp")) {
            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(workAdministrativeAtamp.getAct().getFlag())) {
                        notifyRole = "调整盖章信息";
                        workAdministrativeAtamp.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(workAdministrativeAtamp.getAct().getFlag())) {
                        workAdministrativeAtamp.setState(ProjectStatusEnum.RECALL.getValue());
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("administrativeAtamp");
            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(workAdministrativeAtamp.getAct().getFlag())) {
                        workActivityProcessService.insertAuditsByType(auditUsers,workAdministrativeAtamp.getProcessInstanceId(),2,1);

                        notifyRole = "业务分管领导审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "fgld";
                    } else {
                        notifyRole = "调整申请";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("fgld".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(workAdministrativeAtamp.getAct().getFlag())) {
                        workActivityProcessService.insertAuditsByType(auditUsers,workAdministrativeAtamp.getProcessInstanceId(),3,1);

                        notifyRole = "签章人审批";
                        workActivityProcess.setIsApproval("1");
                        enname = "gzr";
                    } else {
                        notifyRole = "调整签章信息";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                }else if ("gzr".equals(taskDefKey) && count.contains("3")) {
                    taskCount = "3";
                    exp = "pass";
                    if ("yes".equals(workAdministrativeAtamp.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                    } else {
                        notifyRole = "调整签章信息";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
                    notifyRole = "部门负责人审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "bmzr";
                    if (!"yes".equals(workAdministrativeAtamp.getAct().getFlag())) {
                        workAdministrativeAtamp.setState(ProjectStatusEnum.RECALL.getValue());
                    }
                    break;
                } else if ("apply_end".equals(taskDefKey)) {
                }

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

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

            } else {
                if (!"yes".equals(workAdministrativeAtamp.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(workAdministrativeAtamp.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    //users.addAll(userList);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workAdministrativeAtamp.getId(),
                                            workAdministrativeAtamp.getCreateBy(),
                                            workAdministrativeAtamp.getCompany().getId(),
                                            title,
                                            str,
                                            "56",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add( workAdministrativeAtamp.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workAdministrativeAtamp.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(workAdministrativeAtamp.getId(),
                                        new User(),
                                        workAdministrativeAtamp.getCompany().getId(),
                                        title,
                                        str,
                                        "56",
                                        "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","56");
                            extras.put("id",workProjectNotify.getId());
                            UserUtils.pushInfoToApp(title, str,extras,user1.getId());
                        }
                    }else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workAdministrativeAtamp.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.add(workAdministrativeAtamp.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(workAdministrativeAtamp.getId(),
                                                workAdministrativeAtamp.getCreateBy(),
                                                workAdministrativeAtamp.getCompany().getId(),
                                                title,
                                                str,
                                                "56",
                                                "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(workAdministrativeAtamp);
        return "保存审核意见成功！";
    }

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

            //结束该流程,设为"撤销"状态月
            WorkAdministrativeAtamp administrativeAtamp = new WorkAdministrativeAtamp();
            administrativeAtamp.setId(workAdministrativeAtamp.getId());
            administrativeAtamp.setState(ProjectStatusEnum.RECALL.getValue());
            administrativeAtamp.setProcessInstanceId(workAdministrativeAtamp.getProcessInstanceId());
            administrativeAtamp.preUpdate();
            this.updateStateById(administrativeAtamp);
            actTaskService.endProcessInstance(workAdministrativeAtamp.getProcessInstanceId(), "签章申请-撤回");
        }
    }

    private void updateStateById(WorkAdministrativeAtamp administrativeAtamp) {
        dao.updateProcessIdAndStatus(administrativeAtamp);
    }
}