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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
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.OfficeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.worksealform.dao.WorkSealFormDao;
import com.jeeplus.modules.worksealform.entity.WorkSealForm;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 用印申请Service
 * @author 丁旭
 * @version 2017-04-26
 */
@Service
@Transactional(readOnly = true)
public class WorkSealFormService extends CrudService<WorkSealFormDao, WorkSealForm> {

    @Autowired
    private WorkSealFormDao workSealFormDao;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private PushinfoService pushinfoService;

    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private WorkattachmentService workattachmentService;
    /**
     * 获取流程详细及工作流参数
     * @param id
     */
    @SuppressWarnings("unchecked")
    public WorkSealForm get(String id) {
        WorkSealForm workSealForm = workSealFormDao.get(id);
        List<Workattachment> Workattachments = workattachmentService.findAttachment(workSealForm.getId(),"68");
        workSealForm.setWorkAttachments(Workattachments);
        Map<String,Object> variables=null;
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(workSealForm.getProcessInstanceId()).singleResult();
        if(historicProcessInstance!=null) {
            variables = Collections3.extractToMap(historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).list(), "variableName", "value");
        } else {
            variables = runtimeService.getVariables(runtimeService.createProcessInstanceQuery().processInstanceId(workSealForm.getProcessInstanceId()).active().singleResult().getId());
        }
        workSealForm.setVariables(variables);
        return workSealForm;
    }

    /**
     * 获取流程详细及工作流参数
     * @param id
     */
    @SuppressWarnings("unchecked")
    public WorkSealForm getById(String id) {
        WorkSealForm workSealForm = workSealFormDao.get(id);
        return workSealForm;
    }

    @Transactional(readOnly = false)
    public Map getUseSealById(String id,String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        WorkSealForm workSealForm = this.getById(id);
        Map<String,Object> map = Maps.newHashMap();
        if(workSealForm!=null){
            User user = userDao.get(workSealForm.getCreateBy());
            String officeName = "";
            if(user!=null){
                map.put("userName", user.getName());
                map.put("users", user.getId());
                map.put("photo",user.getPhoto());
                Office office = user.getOffice();
                if(office!=null && office.getName()!=null){
                    officeName = office.getName();
                }
            }
            map.put("officeName",officeName);
            map.put("createDate",workSealForm.getCreateDate()==null?"":sdf.format(workSealForm.getCreateDate()));
            map.put("documentName",workSealForm.getDocumentName());
            map.put("documentCount",workSealForm.getDocumentCount());
            map.put("applicationDate",workSealForm.getApplicationDate());
            String sealType = workSealForm.getSealType();
            if (sealType.equals("1")){
                sealType = "公章";
            }else if (sealType.equals("2")){
                sealType = "合同章";
            }else if (sealType.equals("3")){
                sealType = "法人章";
            }else if (sealType.equals("4")){
                sealType = "其他";
            }
            map.put("sealType",sealType);
            map.put("status",workSealForm.getStatus());
            String agentName = "";
            if (workSealForm.getUser()!=null && workSealForm.getUser().getId()!=null){
                User agentUser = UserUtils.get(workSealForm.getUser().getId());
                if (agentUser!=null && agentUser.getName()!=null){
                    agentName =agentUser.getName();
                }
            }
            map.put("user",agentName);
            String office = "";
            if(workSealForm.getOffice()!=null && workSealForm.getOffice().getName()!=null){
                office = workSealForm.getOffice().getName();
            }
            map.put("workSealOffice",office );
            map.put("status",workSealForm.getStatus());
            map.put("reason",workSealForm.getReason());
            map.put("approvalId",id);
            List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(workSealForm.getId(),"68");
            String files = "";
            if (workattachmentList!=null && workattachmentList.size()!=0){
                for (Workattachment workattachment : workattachmentList){
                    files += workattachment.getUrl()+",";
                }
                if (files.length() > 1) {
                    files = files.substring(0, files.length() - 1);
                }
            }
            map.put("files", files);
            List<Act> list = actTaskService.histoicFlowList(workSealForm.getProcessInstanceId(), "", "");
            List<Act> list2 = actTaskService.toMyStartedList(workSealForm.getProcessInstanceId());
            if (list2!=null && list2.size()!=0) {
                Act act1 = list2.get(list2.size()-1);
                map.put("taskId", act1.getTaskId());
                map.put("taskName", act1.getTaskName());
                map.put("procInsId", act1.getProcInsId());
                map.put("procDefId", act1.getProcDefId());
                map.put("actStatus", act1.getStatus()==null?"todo":act1.getStatus());
                map.put("taskDefKey", act1.getTaskDefKey());
                map.put("procDefKey", "sealform");
            }
            List list1 = new ArrayList();
            String approvalStatus = "0";
            String assigneeName = "";
            if (list!=null && list.size()!=0) {
                if (list.get(0).getHistIns().getActivityName().contains("审批")) {
                    for (int i = list.size() - 1; i > -1; i--) {
                        Act act = list.get(i);
                        Map<String, Object> maps = new HashMap<String, Object>();
                        String state = "0";
                        String activityName = "";
                        if (act.getHistIns().getActivityName().contains("审批")) {
                            if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
                                activityName = "已审批";
                                if (UserUtils.getUser().getName().equals(act.getAssigneeName())){
                                    approvalStatus = "1";
                                }
                            } else {
                                activityName = "待审批";
                                state = "2";
                            }
                        } else {
                            activityName = act.getHistIns().getActivityName();
                        }
                        maps.put("activityName", activityName);
                        maps.put("assigneeName", UserUtils.getUser().getName().equals(act.getAssigneeName()) ? "我" : act.getAssigneeName());
                        maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
                        maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
                        maps.put("durationTime", act.getDurationTime());
                        maps.put("state", state);
                        maps.put("userId", act.getCurrentUser().getId());
                        list1.add(maps);
                    }
                } else {
                    if (workSealForm.getStatus().equals("4") || workSealForm.getStatus().equals("3")){
                        for (int i = 0; i < list.size()-1; i++) {
                            Act act = list.get(i);
                            Map<String, Object> maps = new HashMap<String, Object>();
                            String state = "0";
                            String activityName = "";
                            if (act.getHistIns().getActivityName().contains("发起申请")) {
                                activityName = act.getHistIns().getActivityName();
                                assigneeName = act.getAssigneeName();
                            }else if (act.getHistIns().getActivityName().contains("审批")) {
                                if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
                                    assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
                                }
                                if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
                                    activityName = "已审批";
                                    if (UserUtils.getUser().getName().equals(assigneeName)){
                                        approvalStatus = "1";
                                    }
                                    if (i == (list.size()-2) && workSealForm.getStatus().equals("4")){
                                        activityName = "审核驳回";
                                        state = "1";
                                    }else if (i == (list.size()-2) && workSealForm.getStatus().equals("3")){
                                        activityName = "审核成功";
                                    }
                                } else {
                                    activityName = "待审批";
                                    state = "2";
                                }
                            }
                            else {
                                activityName = act.getHistIns().getActivityName();
                                if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
                                    assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
                                }
                            }
                            maps.put("activityName", activityName);
                            maps.put("assigneeName", UserUtils.getUser().getName().equals(assigneeName) ? "我" : assigneeName);
                            maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
                            maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
                            maps.put("durationTime", act.getDurationTime());
                            maps.put("state", state);
                            maps.put("userId", act.getCurrentUser().getId());
                            list1.add(maps);
                        }
                    }else {
                        for (int i = 0; i < list.size(); i++) {
                            Act act = list.get(i);
                            Map<String, Object> maps = new HashMap<String, Object>();
                            String state = "0";
                            String activityName = "";
                            if (act.getHistIns().getActivityName().contains("发起申请")) {
                                activityName = act.getHistIns().getActivityName();
                                assigneeName = act.getAssigneeName();
                            }else if (act.getHistIns().getActivityName().contains("审批")) {
                                if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
                                    assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
                                }
                                if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
                                    activityName = "已审批";
                                    if (UserUtils.getUser().getName().equals(act.getAssigneeName())){
                                        approvalStatus = "1";
                                    }
                                } else {
                                    activityName = "待审批";
                                    state = "2";
                                }
                            }
                            else {
                                activityName = act.getHistIns().getActivityName();
                                if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
                                    assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
                                }
                            }
                            if (workSealForm.getStatus().equals("5") && i == list.size() - 1) {
                                activityName = "已撤销";
                                state = "1";
                            }
                            maps.put("activityName", activityName);
                            maps.put("assigneeName", UserUtils.getUser().getName().equals(assigneeName) ? "我" : assigneeName);
                            maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
                            maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
                            maps.put("durationTime", act.getDurationTime());
                            maps.put("state", state);
                            maps.put("userId", act.getCurrentUser().getId());
                            list1.add(maps);
                        }
                    }
                }
            }
            map.put("approvalStatus", approvalStatus);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setApprovalId(id);
            List<ApprovalCopy> approvalCopyList = approvalCopyService.findList(approvalCopy);
            String CCName = "";
            String CCId = "";
            Boolean readFlag = false;
            if (approvalCopyList!=null && approvalCopyList.size()!=0) {
                ApprovalCopy approvalCopy1 = approvalCopyList.get(0);
                CCId = approvalCopy1.getCCId();
                String[] CCid = approvalCopy1.getCCId().split(",");
                readFlag = approvalCopy1.getReadFlag().equals("0");
                if (type.equals("3") && readFlag){
                    approvalCopy1.setReadFlag("1");
                    approvalCopyService.save(approvalCopy1);
                }
                for (String userId : CCid) {
                    User CCUser = UserUtils.get(userId);
                    if (CCUser != null) {
                        CCName = CCUser.getName() + ",";
                    }
                }
                if (CCName.length() > 1) {
                    CCName = CCName.substring(0, CCName.length() - 1);
                } else {
                    CCName = "";
                }
            }
            map.put("nameCopy",CCName);
            map.put("CCId",CCId);
            map.put("process",list1);

        }
        return  map;
    }

    /**
     * 获取流程详细信息
     * @param processInstanceId
     */
    @SuppressWarnings("unchecked")
    public WorkSealForm getByProcessInstanceId(String processInstanceId) {
        WorkSealForm workSealForm = workSealFormDao.getByProcessInstanceId(processInstanceId);
        return workSealForm;
    }

    @Transactional(readOnly = false)
     public void delete(WorkSealForm workSealForm) {
        workSealFormDao.delete(workSealForm);
    }

    @Transactional(readOnly = false)
    public void update(WorkSealForm workSealForm) {
        workSealFormDao.update(workSealForm);
    }

    /**
     * 启动流程
     * @param workSealForm
     */
    @Transactional(readOnly = false)
    public void save(WorkSealForm workSealForm, Map<String, Object> variables,String type) {
        // 保存业务数据
        if (StringUtils.isBlank(workSealForm.getId())) {
            // 保存业务数据
            workSealForm.preInsert();
            workSealFormDao.insert(workSealForm);
            logger.debug("save entity: {}", workSealForm);

            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(workSealForm.getCurrentUser().getId());

            // 启动流程
            String businessKey = workSealForm.getId().toString();
            variables.put("type", "sealform");
            variables.put("busId", businessKey);
            variables.put("title", workSealForm.getReason());//设置标题；
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_SEALFORM[0], businessKey, variables);

            // 更新流程实例ID
            workSealForm.setProcessInstanceId(processInstance.getId());
            workSealForm.setProcessInstance(processInstance);
            workSealFormDao.updateProcessInstanceId(workSealForm);

            logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[] {
                    ActUtils.PD_SEALFORM[0], businessKey, processInstance.getId(), variables });
        }else{
            workSealForm.preUpdate();
            workSealFormDao.update(workSealForm);
            workSealForm.getAct().setComment(("yes".equals(workSealForm.getAct().getFlag())?"[重申] ":"[销毁] ")+workSealForm.getAct().getComment());

            // 完成流程任务
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("reApply", "yes".equals(workSealForm.getAct().getFlag())? true : false);
            actTaskService.complete(workSealForm.getAct().getTaskId(), workSealForm.getAct().getProcInsId(), workSealForm.getAct().getComment(), workSealForm.getComment(), vars);
        }

    }


    /**
     * 查询待办任务
     * @param userId 用户ID
     * @return
     */
    public List<WorkSealForm> findTodoTasks(String userId) {

        List<WorkSealForm> results = new ArrayList<WorkSealForm>();
        List<Task> tasks = new ArrayList<Task>();
        // 根据当前人的ID查询
        List<Task> todoList = taskService.createTaskQuery().processDefinitionKey(ActUtils.PD_SEALFORM[0]).taskAssignee(userId).active().orderByTaskPriority().desc().orderByTaskCreateTime().desc().list();
        // PD_SEALFORM
        List<Task> unsignedTasks = taskService.createTaskQuery().processDefinitionKey(ActUtils.PD_SEALFORM[0]).taskCandidateUser(userId).active().orderByTaskPriority().desc().orderByTaskCreateTime().desc().list();
        // 合并
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);
        // 根据流程的业务ID查询实体并关联
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            String businessKey = processInstance.getBusinessKey();
            WorkSealForm workSealForm = workSealFormDao.get(businessKey);
            workSealForm.setTask(task);
            workSealForm.setProcessInstance(processInstance);
            workSealForm.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId((processInstance.getProcessDefinitionId())).singleResult());
            results.add(workSealForm);
        }
        return results;
    }

    @Transactional(readOnly = false)
    public void saveFile(WorkSealForm workSealForm) {
        if (StringUtils.isBlank(workSealForm.getId())){
            workSealForm.preInsert();
            workSealFormDao.insert(workSealForm);
        }else{
            workSealForm.preUpdate();
            workSealFormDao.update(workSealForm);
        }
    }

    public Page<WorkSealForm> find(Page<WorkSealForm> page, WorkSealForm workSealForm) {

        workSealForm.getSqlMap().put("dsf", dataScopeFilter(workSealForm.getCurrentUser(), "o", "u","", MenuStatusEnum.WORK_SEAL_FORM.getValue()));

        workSealForm.setPage(page);

        page.setList(workSealFormDao.findList(workSealForm));

        for(WorkSealForm item : page.getList()) {
            String processInstanceId = item.getProcessInstanceId();
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if(historicProcessInstance!=null) {
                item.setHistoricProcessInstance(historicProcessInstance);
                item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
            } else {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
                if (processInstance != null){
                    item.setProcessInstance(processInstance);
                    item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
                }
            }
            ProcessInstance processInstance = actTaskService.getProcIns(item.getProcessInstanceId());
            if (processInstance!=null) {
                Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                if (StringUtils.isNotBlank(taskInfok.getAssignee()) && taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
                    item.setTask(taskInfok);
                }
            }
        }
        return page;
    }

    /* * 审核审批保存
     * @param testAudit
     */
    @Transactional(readOnly = false)
    public void auditSave(WorkSealForm workSealForm) {

        // 设置意见
        workSealForm.getAct().setComment(("yes".equals(workSealForm.getAct().getFlag())?"[同意] ":"[驳回] ")+workSealForm.getAct().getComment());
        workSealForm.preUpdate();
        this.update(workSealForm);
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workSealForm.getAct().getTaskDefKey();

        //发送通知
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workSealForm.getId());
        notify.setCompanyId(UserUtils.getSelectCompany().getId());
        notify.setType("27");
        notify.setStatus("0");
        notify.setNotifyRole("");

        //业务逻辑对应的条件表达式
        String exp = "";
        // 审核环节
        if ("audit1".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit2".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit3".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit4".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit5".equals(taskDefKey)){
            exp = "pass";
        }else if("apply_end".equals(taskDefKey)){
            exp = "pass";
        }
        // 未知环节，直接返回
        else{
            return;
        }

        // 提交流程任务
        Map<String, Object> vars = Maps.newHashMap();
        vars.put(exp, "yes".equals(workSealForm.getAct().getFlag())? false : true);
        // 提交流程任务
        actTaskService.complete(workSealForm.getAct().getTaskId(), workSealForm.getAct().getProcInsId(), workSealForm.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(workSealForm.getAct().getProcInsId());
        workSealForm.setStatus("2");
        if (!state){
            if ("yes".equals(workSealForm.getAct().getFlag())){
                workSealForm.setStatus("3");
            }else {
                workSealForm.setStatus("4");
            }
        }
        workSealForm.preUpdate();
        this.update(workSealForm);

        //需在workSealForm更新后 操作：
        //1待审核  2审核中 3通过 4驳回 5已撤销 6催办中
        if("2".equals(workSealForm.getStatus())){
            workSealForm = this.get(workSealForm.getId());
            String userId = workSealForm.getVariables().get("assignee").toString();
            if(StringUtils.isNotBlank(userId)){
                notify.setUser(UserUtils.get(userId));
            }
            notify.setTitle("您有新的用印申请待审批");
            notify.setRemarks("待审批");
            notify.setContent("用印申请--待审批");

        }else if("3".equals(workSealForm.getStatus())){
            notify.setUser(workSealForm.getCreateBy());
            notify.setTitle("您的用印申请已通过");
            notify.setRemarks("待通知");
            notify.setContent(workSealForm.getAct().getComment());
        }else if("4".equals(workSealForm.getStatus())){
            notify.setUser(workSealForm.getCreateBy());
            notify.setTitle("您的用印申请被驳回");
            notify.setRemarks("待通知");
            notify.setContent(workSealForm.getAct().getComment());
        }
        workProjectNotifyService.save(notify);

        //更新审核人的阅读状态
        WorkProjectNotify notify2 = new WorkProjectNotify();
        notify2.setUser(UserUtils.getUser());
        notify2.setNotifyId(workSealForm.getId());
        workProjectNotifyService.readByNotifyIdAndNotifyUser(notify2);

        //经办人
        if("3".equals(workSealForm.getStatus()) || "4".equals(workSealForm.getStatus())){
            if(workSealForm.getUser()!=null && StringUtils.isNotBlank(workSealForm.getUser().getId())){
                String jingbanUser = workSealForm.getUser().getId();
                WorkProjectNotify notify3 = new WorkProjectNotify();
                notify3.setNotifyId(workSealForm.getId());
                notify3.setCompanyId(UserUtils.getSelectCompany().getId());
                notify3.setType("27");
                notify3.setStatus("0");
                notify3.setNotifyRole("");
                notify3.setUser(workSealForm.getUser());
                notify3.setRemarks("待通知");
                if("3".equals(workSealForm.getStatus())){
                    notify3.setTitle(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请已通过");
                    notify3.setContent(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请已通过");
                }
                if("4".equals(workSealForm.getStatus())){
                    notify3.setTitle(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请被驳回");
                    notify3.setContent(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请被驳回");
                }
                workProjectNotifyService.save(notify3);
            }
        }

        //抄送
        if("3".equals(workSealForm.getStatus()) || "4".equals(workSealForm.getStatus())){
            ApprovalCopy approvalCopy = approvalCopyService.getByApprovalId(workSealForm.getId());
            if(approvalCopy!=null && StringUtils.isNotBlank(approvalCopy.getCCId())){
                WorkProjectNotify notify1= new WorkProjectNotify();
                notify1.setNotifyId(workSealForm.getId());
                notify1.setCompanyId(UserUtils.getSelectCompany().getId());
                notify1.setType("27");
                notify1.setStatus("0");
                notify1.setNotifyRole("");
                notify1.setContent(workSealForm.getAct().getComment());
                String[] ccIds = approvalCopy.getCCId().split(",");
                for(String ccId : ccIds){
                    if(StringUtils.isNotBlank(ccId)){
                        notify1.setUser(new User(ccId));
                        if("3".equals(workSealForm.getStatus())){
                            notify1.setTitle(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请已通过");
                        }
                        if("4".equals(workSealForm.getStatus())){
                            notify1.setTitle(UserUtils.get(workSealForm.getCreateBy().getId()).getName()+"的用印申请被驳回");
                        }
                        notify1.setRemarks("待通知");
                        notify1.setId("");
                        workProjectNotifyService.save(notify1);
                    }
                }
            }
        }
    }

    /* * 审核审批保存
     * @param testAudit
     */
    @Transactional(readOnly = false)
    public boolean saveWorkSealForm(WorkSealForm workSealForm) {
        try {
            workSealForm.setStatus("1");
            String approverId = "";
            List<String> adds = workSealForm.getAdds();
            for(int i = 0;i<adds.size();i++){
                if(i + 1 == adds.size()){
                    approverId += adds.get(i);
                }else{
                    approverId += adds.get(i) + ",";
                }
            }
            workSealForm.setIds(approverId);
            Map<String, Object> variables = Maps.newHashMap();
            String type = "1";
            String alias = "1";
            List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
            if(!UserUtils.getUser().isAdmin() && approverId!=null && !approverId.equals("")) {
                if (approverId.contains(UserUtils.getUser().getId())){
                    logger.error("用印申请失败,审批人不能为本人");
                    return false;
                }
                String[] approverIds = approverId.split(",");
                for (int i =0 ;i<approverIds.length;i++){
                    assigneeList.add(approverIds[i]);
                }
                type = approverIds.length+"";
                alias = approverIds[0];
            }
            variables.put("assigneeList", assigneeList);
            variables.put("count",assigneeList.size());
            User agent = workSealForm.getUser();//经办人
            Office office = workSealForm.getOffice();//用印部门
            //approver.setId(approverId);
            User CC = new User();
            CC.setId(workSealForm.getCCId());
            User user = UserUtils.getUser();

            workSealForm.setUser(agent);
            workSealForm.setOffice(office);
            //workSealForm.setUser(user);
            workSealForm.setOffice(office);
            workSealForm.setCreateBy(user);
            workSealForm.setUpdateBy(user);
            workSealForm.setDelFlag("0");
            workSealForm.setStatus("1");
            workSealForm.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workSealForm.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            save(workSealForm,variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(workSealForm.getCCId());
            approvalCopy.setUserId(user.getId());
            approvalCopy.setType("sealform");
            approvalCopy.setRemarks(workSealForm.getReason());
            approvalCopy.setApprovalId(workSealForm.getId());
            approvalCopy.setApproverId(approverId);
            approvalCopy.setReadFlag("0");
            approvalCopyService.save(approvalCopy);

            //给抄送人、审批人发送通知
            if(approvalCopy!=null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())){
                String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
                String shenpiIds = alias;//给审批流程的第一个人发送通知
                this.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",用印申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的用印申请需要你审批";
            String status = "待审批";
            Office office1 = workSealForm.getOffice();
            String officeName = "";
            if (office1!=null){
                Office o = officeService.get(office1.getId());
                officeName = o.getName();
            }
            String agentName = "";
            if (agent!=null && agent.getName()!=null){
                agentName =agent.getName();
            }
            String remakers = "用印部门："+officeName+ "\n"
                    +"经办人："+agentName+ "\n"
                    +"日期："+workSealForm.getApplicationDate();
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workSealForm.getId());
            extras.put("procDefKey", "sealform");

            boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
            Pushinfo pushinfo = new Pushinfo();
            pushinfo.setCurrentUser(UserUtils.getUser());
            pushinfo.setRemarks(remakers);
            pushinfo.setUserId(UserUtils.getUser().getId());
            pushinfo.setType("4001");
            pushinfo.setPushId(workSealForm.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfo.setStatus(status);
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfo.setAddcontent("sealform");
            pushinfo.setMobile("ios,android");
            pushinfoService.save(pushinfo);
            if (b){
                return true;
            }
        } catch (Exception e) {
            logger.error("启动用印流程失败：", e);
        }
        return false;
    }

    @Transactional(readOnly = false)
    public void sendNotify(String chaosongIds,String shenpiId,String sealFormId) {
        if(StringUtils.isNotBlank(sealFormId)){
            if(StringUtils.isNotBlank(chaosongIds)){
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setTitle(UserUtils.getUser().getName()+"发起了用印申请");
                notify.setRemarks("待通知");
                notify.setContent(UserUtils.getUser().getName()+"的用印申请");
                notify.setNotifyRole("");
                notify.setNotifyId(sealFormId);
                notify.setStatus("0");
                notify.setCompanyId(UserUtils.getSelectCompany().getId());
                notify.setType("27");
                String[] arr = chaosongIds.split(",");
                for (String id : arr){
                    if(StringUtils.isNotBlank(id)){
                        notify.setId("");
                        notify.setUser(new User(id));
                        workProjectNotifyService.save(notify);
                    }
                }
            }
            if(StringUtils.isNotBlank(shenpiId)){
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setTitle("您有新的用印申请待审批");
                notify.setRemarks("待审批");
                notify.setContent("用印申请--待审批");
                notify.setNotifyRole("");
                notify.setUser(new User(shenpiId));
                notify.setNotifyId(sealFormId);
                notify.setStatus("0");
                notify.setCompanyId(UserUtils.getSelectCompany().getId());
                notify.setType("27");
                workProjectNotifyService.save(notify);
            }
        }
    }



    public List getCreateDateList(String companyId, String date) {
        Map<String,String> map = new HashMap<String, String>();
        map.put("companyId",companyId);
        map.put("date",date);
        return workSealFormDao.getCreateDateList(map);
    }

    public List<WorkSealForm> findByCompany2(WorkSealForm workSealForm, String date) {
        Map<String,Object> map = new HashMap<>();
        map.put("seal",workSealForm);
        map.put("date",date);
        return workSealFormDao.findByCompany2(map);
    }

    public List getCreateDateList1(String time) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("userId",UserUtils.getUser().getId());
        map.put("time",time);
        return workSealFormDao.getCreateDateList1(map);
    }
    public List<WorkSealForm> findByCompany1(String time){
        Map<String,String> map = new HashMap<String,String>();
        map.put("userId",UserUtils.getUser().getId());
        map.put("time",time);
        return workSealFormDao.findByCompany1(map);
    }

    public List getCreateDateListAll(String time) {
        Map<String,String> map = new HashMap<String,String>();
        WorkSealForm w =new WorkSealForm();
        map.put("sqlStr",dataScopeFilter(w.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_SEAL_FORM.getValue()));
        map.put("time",time);
        return workSealFormDao.getCreateDateListAll(map);
    }
    public List<WorkSealForm> findByCompanyAll(String time){
        Map<String,String> map = new HashMap<String,String>();
        WorkSealForm w =new WorkSealForm();
        map.put("sqlStr",dataScopeFilter(w.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_SEAL_FORM.getValue()));
        map.put("time",time);
        return workSealFormDao.findByCompanyAll(map);
    }

    public List<WorkSealForm> findByManage(Map<String,Object> map) {
        return workSealFormDao.findByManage(map);
    }
    public List<WorkSealForm> findByCompanySelf(Map<String,Object> map) {
        return workSealFormDao.findByCompanySelf(map);
    }
}