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

import com.google.common.collect.Maps;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.BaseEntity;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.JPushClientUtil;
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.oa.dao.OaNotifyDao;
import com.jeeplus.modules.oa.dao.OaNotifyDetailDao;
import com.jeeplus.modules.oa.dao.OaNotifyRecordDao;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.oa.entity.OaNotifyRecord;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
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.entity.Workattachment;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
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.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.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通知通告Service
 * @author jeeplus
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class OaNotifyService extends CrudService<OaNotifyDao, OaNotify> {
    @Autowired
    private OaNotifyRecordDao oaNotifyRecordDao;
    @Autowired
    private SystemService systemService;

    @Autowired
    UserDao userDao;
    @Autowired
    private PushinfoService pushinfoService;
    @Autowired
    private WorkattachmentService workattachmentService;
    @Autowired
    private SerialNumTplService serialNumTplService;
    @Autowired
    private OaNotifyDetailDao oaNotifyDetailDao;
    @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 WorkProjectNotifyService workProjectNotifyService;

    public OaNotify get(String id) {
        OaNotify oaNotify = dao.get(id);
        List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(id, "79");
        oaNotify.setWorkAttachments(attachmentList);
        return oaNotify;
    }

    /**
     * 获取通知发送记录
     * @param oaNotify
     * @return
     */
    public OaNotify getRecordList(OaNotify oaNotify) {
        oaNotify.setOaNotifyRecordList(oaNotifyRecordDao.findList(new OaNotifyRecord(oaNotify)));
        return oaNotify;
    }
    public OaNotify getUsers(OaNotify oaNotify) {
        List<OaNotifyRecord> list = oaNotifyRecordDao.findUsers(new OaNotifyRecord(oaNotify));
        List<User> users = new ArrayList<>();
        if (list!=null &&list.size()!=0){
            for(OaNotifyRecord oaNotifyRecord:list){
                users.add(oaNotifyRecord.getUser());
            }
        }
        oaNotify.setUserList(users);
        return oaNotify;
    }
    public OaNotify getOffices(OaNotify oaNotify) {
        List<OaNotifyRecord> list = oaNotifyRecordDao.findOffices(new OaNotifyRecord(oaNotify));
        List<Office> offices = new ArrayList<>();
        if (list!=null &&list.size()!=0){
            for(OaNotifyRecord oaNotifyRecord:list){
                Office office = new Office(oaNotifyRecord.getOfficeId());
                office.setName(oaNotifyRecord.getOfficeName());
                offices.add(office);
            }
        }
        oaNotify.setOfficeList(offices);
        return oaNotify;
    }
    public OaNotify getRecordOfficeList(OaNotify oaNotify) {
        oaNotify.setOaNotifyRecordList(oaNotifyRecordDao.findOffices(new OaNotifyRecord(oaNotify)));
        return oaNotify;
    }

    //获取通知发送的记录，包含已读和未读--PC端使用
    public OaNotify getRecordList2(OaNotify oaNotify){
        oaNotify.setOaNotifyRecordList(oaNotifyRecordDao.findList2(new OaNotifyRecord(oaNotify)));
        return oaNotify;
    }

    //我的通告(个人)
    public Page<OaNotify> findMyself(Page<OaNotify> page, OaNotify oaNotify) {
        User user = UserUtils.getUser();
        oaNotify.setCurrentUser(user);

        if(!user.isAdmin()){
            oaNotify.setCompany(user.getCompany());
        }
        oaNotify.setPage(page);
        List<OaNotify> oaNotifyList = dao.findList(oaNotify);
        for (OaNotify notify:oaNotifyList){
            if (StringUtils.isBlank(notify.getRemarks())) {
                Long endDate = notify.getEndDate().getTime();
                Long startDate = notify.getStartDate().getTime();
                Long now = new Date().getTime();
                if (startDate < now && endDate > now) {
                    notify.setCandel("yes");
                }
            }
        }
        //只查询当前公司下发送给自己的通告
        page.setList(oaNotifyList);
        return page;
    }
    //通告管理(管理员)
    public Page<OaNotify> find(Page<OaNotify> page, OaNotify oaNotify) {
        oaNotify.setPage(page);
        if(!UserUtils.getUser().isAdmin()){
            oaNotify.setCompany(UserUtils.getSelectCompany());

            if(!UserUtils.isManager()){
                List<OaNotify> list = new ArrayList<>();
                page.setList(list);
                return page;
            }
        }
        //查询出当前公司下所有管理员创建的通告
        List<OaNotify> oaNotifyList = dao.findList(oaNotify);
        page.setList(oaNotifyList);

        return page;
    }
    //通告管理
    public Page<OaNotify> findByPc(Page<OaNotify> page, OaNotify oaNotify) {
        oaNotify.setPage(page);
        oaNotify.getSqlMap().put("dsf", dataScopeFilter(oaNotify.getCurrentUser(), "o", "u","s", MenuStatusEnum.OA_NOTIFY.getValue()));
        //查询出当前公司下所有管理员创建的通告
        List<OaNotify> oaNotifyList = dao.findListByPc(oaNotify);
        for (OaNotify notify:oaNotifyList){
            if (StringUtils.isBlank(notify.getRemarks())) {
                Long startDate = notify.getStartDate().getTime();
                Long endDate = notify.getEndDate().getTime();
                Long now = new Date().getTime();
                if ("5".equals(notify.getStatus()) && startDate<now && endDate>now){
                    notify.setCandel("yes");
                }
            }
            if (StringUtils.isNotBlank(notify.getContent())){
                Pattern p = Pattern.compile("\t|\r|\n");
                Matcher m = p.matcher(notify.getContent());
                notify.setContent(m.replaceAll(""));
            }
        }
        page.setList(oaNotifyList);

        return page;
    }

    /**
     * 获取通知数目
     * @param oaNotify
     * @return
     */
    public Long findCount(OaNotify oaNotify) {
        return dao.findCount(oaNotify);
    }

    @Transactional(readOnly = false)
    public void save(OaNotify oaNotify) {
        if(oaNotify.getCompany()==null || StringUtils.isBlank(oaNotify.getCompany().getId())){
            oaNotify.setCompany(UserUtils.getSelectCompany());
        }
        if (oaNotify.getOffice()==null || StringUtils.isBlank(oaNotify.getOffice().getId())){
            oaNotify.setOffice(UserUtils.getSelectOffice());
        }
        String title = StringEscapeUtils.unescapeHtml4(oaNotify.getTitle());
        String content = StringEscapeUtils.unescapeHtml4(oaNotify.getContent());
        oaNotify.setTitle(title);
        oaNotify.setContent(content);
        String contents = "";
        if (oaNotify!=null && oaNotify.getContents()!=null){
            contents = StringEscapeUtils.unescapeHtml4(oaNotify.getContents());
            oaNotify.setContents(contents);
        }

        if (StringUtils.isBlank(oaNotify.getNumber())){
            oaNotify.setNumber(serialNumTplService.genSerialNum(UserUtils.getSelectCompany(), "17"));
        }
        super.save(oaNotify);
        //保存附件
        this.saveAttachments(oaNotify);
        // 更新通知人
        saveDetailList(oaNotify,0);
        // 更新通知部门
        saveDetailList(oaNotify,1);

    }

    @Transactional(readOnly = false)
    public String saveNotify(OaNotify oaNotify) {
        this.save(oaNotify);
        return this.startAudit(oaNotify,oaNotify.getProcessInstanceId());
    }

    private String startAudit(OaNotify oaNotify, String processInstanceId) {
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(oaNotify.getCurrentUser().getId());
        String contentStr = "公告编号："+oaNotify.getNumber()+"，公告类型："+ DictUtils.getMainDictLabel(oaNotify.getType(),"oa_notify_type","")+"，公告日期："+ DateUtils.formatDate(oaNotify.getCreateDate());
        String titleStr = "公告标题："+ oaNotify.getTitle();

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

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

        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);
        }
        oaNotify.setProcessInstanceId(processInstance.getId());
        oaNotify.setStatus(String.valueOf(ProjectStatusEnum.IN_APRL.getValue()));
        dao.updateProcessIdAndStatus(oaNotify);
        return "";
    }

    /**
     *
     * @param oaNotify
     * @param isOffice 0:用户 1：部门
     */
    private void saveDetailList(OaNotify oaNotify,int isOffice) {
        List userList = null;
        if(isOffice==0){
            userList = oaNotify.getUserList();
        }else {
            userList = oaNotify.getOfficeList();
        }
        if(userList ==null|| userList.size()<=0){
            return;
        }
        oaNotifyDetailDao.deleteHandlers(oaNotify.getId(),isOffice);
        Iterator iterator = userList.iterator();
        while (iterator.hasNext()){
            BaseEntity next = (BaseEntity) 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("notifyId", oaNotify.getId());
        map.put("handlerList", userList);
        map.put("flag", isOffice);
        oaNotifyDetailDao.batchInsert(map);
    }

    @Transactional(readOnly = false)
    public void saveAttachments(OaNotify oaNotify) {
        List<Workattachment> workattachments = oaNotify.getWorkAttachments();
        if (workattachments!=null && workattachments.size()!=0) {
            for (Workattachment workattachment : workattachments) {
                if (workattachment.getId() == null) {
                    continue;
                }
                if (workattachment.DEL_FLAG_NORMAL.equals(workattachment.getDelFlag())) {
                    workattachment.setAttachmentId(oaNotify.getId());
                    workattachment.setAttachmentFlag("79");
                    workattachment.setAttachmentUser(UserUtils.getUser().getId());
                    if (StringUtils.isBlank(workattachment.getId()) || "null".equals(workattachment.getId())) {
                        workattachment.preInsert();
                        workattachmentService.insert(workattachment);
                    } else {
                        workattachment.preUpdate();
                        workattachmentService.save(workattachment);
                    }
                } else {
                    workattachmentService.delete(workattachment);
                }
            }
        }
    }

    public void pushNotify(OaNotify oaNotify,String state) {
        this.queryDetails(oaNotify);
        String ids = this.selectRecords(oaNotify);
        Map extras = new HashMap();
        extras.put("type", "2001");
        extras.put("id", oaNotify.getId());
        extras.put("state", state);
        List aliases = new ArrayList();
        if (ids!=null && ids.length()!=0){
            String[] aliase = ids.split(",");
            for (String a:aliase){
                UserUtils.pushIm(a,"公告消息 "+oaNotify.getTitle());
                aliases.add(a);
            }
        }
        Pushinfo pushinfo = new Pushinfo();
        pushinfo.setCompanyId(UserUtils.getSelectCompany().getId());
        pushinfo.setMobile("ios,android");
        pushinfo.setCurrentUser(UserUtils.getUser());
        pushinfo.setRemarks(oaNotify.getContent());
        pushinfo.setUserId(UserUtils.getUser().getId());
        pushinfo.setType("2001");
        pushinfo.setPushId(oaNotify.getId());
        pushinfo.setTitle("公告");
        String status = oaNotify.getUpdateBy().getName() +"  "+ DateUtils.formatDate(new Date());
        pushinfo.setStatus(status);
        pushinfo.setContent(oaNotify.getTitle());
        pushinfo.setPushUserId(ids);
        pushinfo.setParentType("singleCompanyNews");
        pushinfo.setAddcontent(oaNotify.getContents());
        if (oaNotify.getFiles()!=null &&oaNotify.getFiles().length()>0){
            pushinfo.setStatus(oaNotify.getFiles());
        }
        pushinfoService.save(pushinfo);

        boolean b = JPushClientUtil.sendNotificationToAliases(oaNotify.getTitle(), oaNotify.getContent(), extras, aliases);
    }

    private String selectRecords(OaNotify oaNotify) {
        String recordIds = "";
        Set<String> set = new HashSet<String>();
        List<User> users = oaNotify.getUserList();
        if (users !=null && users.size()!=0){
            for (int i = 0; i < users.size(); i++) {
                set.add(users.get(i).getId());
            }
        }
        List<Office> offices = oaNotify.getOfficeList();
        if (offices!=null && offices.size()!=0){
            oaNotify.setOaNotifyRecordOffices(offices);
            for (int i = 0; i < offices.size(); i++) {
                List<User> userList = systemService.findUserByOfficeId(offices.get(i).getId());
                for (User user:userList){
                    set.add(user.getId());
                }
            }
        }
        if (set!=null && set.size()!=0) {
            List aliases = new ArrayList();
            for (String id : set) {
                recordIds += id + ",";
                aliases.add(id);
            }
            if (StringUtils.isNotBlank(recordIds)) {
                recordIds = recordIds.substring(0, recordIds.length() - 1);
            }
        }
        if (StringUtils.isNotBlank(recordIds)){
            oaNotify.setOaNotifyRecordIds(recordIds);
            if (oaNotify.getOaNotifyRecordList().size() > 0){
                oaNotifyRecordDao.insertAll(oaNotify.getOaNotifyRecordList());
            }
        }
        return recordIds;
    }

    @Transactional(readOnly = false)
    public void saveNotifyFile(OaNotify oaNotify) {
        super.save(oaNotify);
        if (oaNotify.getId()!=null && oaNotify.getFiles()!=null){
            Pushinfo pushinfo = new Pushinfo();
            pushinfo.setPushId(oaNotify.getId());
            pushinfo.setType("2001");
            List<Pushinfo> list =pushinfoService.getByPushId(pushinfo);
            if (list!=null && list.size()!=0){
                for (Pushinfo pushinfo1:list){
                    pushinfo1.setAddcontent(oaNotify.getFiles());
                    pushinfoService.save(pushinfo1);
                }
            }
        }
    }

    /**
     * 更新阅读状态
     */
    @Transactional(readOnly = false)
    public void updateReadFlag(OaNotify oaNotify) {
        OaNotifyRecord oaNotifyRecord = new OaNotifyRecord(oaNotify);
        oaNotifyRecord.setUser(oaNotifyRecord.getCurrentUser());

        oaNotifyRecord.setReadDate(new Date());
        oaNotifyRecord.setReadFlag("1");
        oaNotifyRecordDao.update(oaNotifyRecord);
    }
    /**
     * 更新阅读状态
     */
    @Transactional(readOnly = false)
    public void deleteByOaNotifyId(String oaNotifyId) {
        oaNotifyRecordDao.deleteByOaNotifyId(oaNotifyId);
    }
    /**
     * 更新阅读状态
     */
    @Transactional(readOnly = false)
    public void saveRemarks(OaNotify oaNotify) {
        dao.saveRemarks(oaNotify);
    }

    @Transactional(readOnly = false)
    public String uploadFile(OSSClientUtil ossClientUtil, MultipartFile file, OaNotify oaNotify, String flag) {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String url = ossClientUtil.uploadFile2OSS(file,"notify");
        Workattachment workattachment = new Workattachment();
        workattachment.setUrl(url);
        workattachment.setType(fileType);
        workattachment.setAttachmentName(fileName);
        workattachment.setAttachmentUser(UserUtils.getUser().getId());
        workattachment.setAttachmentId(oaNotify.getId());
        workattachment.setCompanyId(UserUtils.getSelectCompany().getId());
        workattachment.setAttachmentFlag(flag);
        workattachmentService.save(workattachment);
        return url;
    }

    @Transactional(readOnly = false)
    public void delFile(String attaId, String attachmentUrl) {
        try {
            Workattachment workattachment = new Workattachment();
            if(StringUtils.isNotBlank(attaId)){
                workattachment.setId(attaId);
                workattachmentService.delete(workattachment);
            }
            if(StringUtils.isNotBlank(attachmentUrl)){
                workattachment.setUrl(attachmentUrl);
                workattachmentService.deleteFileFromAliyun(workattachment,workattachment==null?attachmentUrl:workattachment.getUrl());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

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

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

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

    public void queryDetails(OaNotify oaNotify) {
        if(oaNotify==null)return;
        oaNotify.setOfficeList(this.queryOfficeList(oaNotify));
        oaNotify.setUserList(this.queryUserList(oaNotify));
    }

    private List<Office> queryOfficeList(OaNotify oaNotify) {
        return oaNotifyDetailDao.queryOfficeList(oaNotify);
    }

    private List<User> queryUserList(OaNotify oaNotify) {
        return oaNotifyDetailDao.queryUserList(oaNotify);
    }

    @Transactional(readOnly = false)
    public void cancelProcess(OaNotify oaNotify) throws Exception {
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(oaNotify.getProcessInstanceId());
        process.setIsApproval("0");
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(oaNotify.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(oaNotify.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList!=null && userList.size()!=0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",公告审批编号:"+oaNotify.getNumber() +" 强制撤销!");
            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            OaNotify sendMessage = new OaNotify();
            sendMessage.setId(oaNotify.getId());
            sendMessage.setStatus(String.valueOf(ProjectStatusEnum.RECALL.getValue()));
            sendMessage.setProcessInstanceId(oaNotify.getProcessInstanceId());
            sendMessage.preUpdate();
            dao.updateProcessIdAndStatus(sendMessage);
            actTaskService.endProcessInstance(oaNotify.getProcessInstanceId(), "公告申请-撤回");
        }
    }

    @Transactional(readOnly = false)
    public void logicDelete(OaNotify oaNotify) {
        dao.deleteByLogic(oaNotify);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(oaNotify.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users!=null && users.size()!=0){
            for (User user:users){
                UserUtils.pushMeIm(user.getId());
            }
        }
    }
}