/**
 * There are <a href="http://www.jeeplus.org/">jeeplus</a> code generation
 */
package com.jeeplus.modules.oa.service;

import com.google.common.collect.Maps;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.BaseService;
import com.jeeplus.common.utils.Collections3;
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.oa.dao.LeaveDao;
import com.jeeplus.modules.oa.entity.Leave;
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.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 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 org.springframework.web.multipart.MultipartFile;

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

/**
 * 请假Service
 * @author liuj
 * @version 2013-04-05
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class LeaveService extends BaseService {
    @Autowired
    private LeaveDao leaveDao;
    @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 ApprovalCopyService approvalCopyService;

    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private WorkattachmentService workattachmentService;

    /**
     * 获取流程详细及工作流参数
     * @param id
     */
    @SuppressWarnings("unchecked")
    public Leave get(String id) {
        Leave leave = leaveDao.get(id);
        Map<String,Object> variables=null;
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(leave.getProcessInstanceId()).singleResult();
        if(historicProcessInstance!=null) {
            variables = Collections3.extractToMap(historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).list(), "variableName", "value");
        } else {
            variables = runtimeService.getVariables(runtimeService.createProcessInstanceQuery().processInstanceId(leave.getProcessInstanceId()).active().singleResult().getId());
        }
        leave.setVariables(variables);

        List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(leave.getId(),"71");
        leave.setWorkattachmentList(workattachmentList);
        return leave;
    }

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

    /**
     * 获取流程详细Leave
     * @param processInstanceId
     */
    @SuppressWarnings("unchecked")
    public Leave getByProcessInstanceId(String processInstanceId) {
        Leave leave = leaveDao.getByProcessInstanceId(processInstanceId);
        return leave;
    }

    @Transactional(readOnly = false)
    public void save(Leave leave) {
        if (leave.getIsNewRecord()){
            leave.preInsert();
            leaveDao.insert(leave);
        }else{
            leave.preUpdate();
            leaveDao.update(leave);
        }
    }

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

            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(leave.getCurrentUser().getId());
            // 启动流程
            String businessKey = leave.getId().toString();
            variables.put("type", "leave");
            variables.put("busId", businessKey);
            variables.put("title", leave.getReason());//设置标题；
            /*String pd_audit_process = "";
            if (type.equals("1")){
                pd_audit_process = ActUtils.PD_AUDIT_PROCESS1[0];
            }else if (type.equals("2")){
                pd_audit_process = ActUtils.PD_AUDIT_PROCESS2[0];
            }else if (type.equals("3")){
                pd_audit_process = ActUtils.PD_AUDIT_PROCESS3[0];
            }else if (type.equals("4")){
                pd_audit_process = ActUtils.PD_AUDIT_PROCESS4[0];
            }else if (type.equals("5")){
                pd_audit_process = ActUtils.PD_AUDIT_PROCESS5[0];
            }*/
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_LEAVE[0], businessKey, variables);
            leave.setProcessInstance(processInstance);
            // 更新流程实例ID
            leave.setProcessInstanceId(processInstance.getId());
            leaveDao.updateProcessInstanceId(leave);
        }else{
            leave.preUpdate();
            leaveDao.update(leave);
            leave.getAct().setComment(("yes".equals(leave.getAct().getFlag()) ? "[重申] " : "[销毁] ") + leave.getAct().getComment());

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


    }

    @Transactional(readOnly = false)
    public void saveFile(Leave leave) {
        if (StringUtils.isBlank(leave.getId())){
            leave.preInsert();
            leaveDao.insert(leave);
        }else{
            leave.preUpdate();
            leaveDao.update(leave);
        }
    }

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

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

    public Page<Leave> find(Page<Leave> page, Leave leave) {

        leave.getSqlMap().put("dsf", dataScopeFilter(leave.getCurrentUser(), "o", "u","", MenuStatusEnum.LEAVE.getValue()));
        leave.setPage(page);
        page.setList(leaveDao.findList(leave));

        for(Leave item : page.getList()) {
            String processInstanceId = item.getProcessInstanceId();
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).active().singleResult();
            //item.setTask(task);
            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;
    }

    @Transactional(readOnly = false)
    public void delete(Leave Leave) {
        leaveDao.delete(Leave);
    }

    @Transactional(readOnly = false)
    public void update(Leave Leave) {
        Leave.preUpdate();
        leaveDao.update(Leave);
    }

    @Transactional(readOnly = false)
    public Map getLeaveById(String id,String type) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Leave leave = this.getById(id);
        Map<String,Object> map = Maps.newHashMap();
        String officeName = "";
        String officeId = "";
        if(leave!=null){
            User user = userDao.get(leave.getCreateBy());
            if(user!=null){
                map.put("userName", user.getName());
                map.put("photo",user.getPhoto());
                map.put("users", user.getId());
                Office office = user.getOffice();
                if(office!=null && office.getName()!=null){
                    officeName = office.getName();
                    officeId = office.getId();
                }
            }
            map.put("createDate",leave.getCreateDate()==null?"":sdf.format(leave.getCreateDate()));
            map.put("startTime",leave.getStartTime());
            map.put("endTime",leave.getEndTime());
            String leaveType = leave.getLeaveType();
            if (leaveType.equals("1")){
                leaveType = "事假";
            }else if(leaveType.equals("2")){
                leaveType = "病假";
            }else if(leaveType.equals("3")){
                leaveType = "调休";
            }else if(leaveType.equals("4")){
                leaveType = "年假";
            }else if(leaveType.equals("5")){
                leaveType = "婚假";
            }else if(leaveType.equals("6")){
                leaveType = "产假";
            }else if(leaveType.equals("7")){
                leaveType = "其他";
            }
            map.put("leaveType",leaveType);
            map.put("leaveDays",leave.getLeaveDays());
            map.put("leaveTime",leave.getLeaveTime());
            map.put("reason",leave.getReason());
            map.put("companyId",leave.getCompanyId());
            map.put("officeName",officeName);
            map.put("officeId",officeId);
            map.put("approvalId",id);
            map.put("status",leave.getStatus());
            List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(leave.getId(),"71");
            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(leave.getProcessInstanceId(), "", "");
            List<Act> list2 = actTaskService.toMyStartedList(leave.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", "leave");
            }
            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();
                        }
                        if (type.equals("1") || type.equals("2")) {
                            maps.put("activityName", activityName);
                            maps.put("assigneeName", UserUtils.getUser().getName().equals(act.getAssigneeName()) ? "我" : act.getAssigneeName());
                        } else if (type.equals("3")) {
                            maps.put("activityName", activityName);
                            maps.put("assigneeName", 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 (leave.getStatus().equals("4") || leave.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) && leave.getStatus().equals("4")){
                                        activityName = "审核驳回";
                                        state = "1";
                                    }else if (i == (list.size()-2) && leave.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(assigneeName)){
                                        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 (leave.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 testAudit
     */
    @Transactional(readOnly = false)
    public String auditSave(Leave leave) {
        try{
            // 设置意见
            leave.getAct().setComment(("yes".equals(leave.getAct().getFlag())?"[同意] ":"[驳回] ")+leave.getAct().getComment());
            System.out.println("comment================="+leave.getAct().getComment());

            // 对不同环节的业务逻辑进行操作
            String taskDefKey = leave.getAct().getTaskDefKey();
            System.out.println("taskDefKey====================="+taskDefKey);

            //发送通知
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(leave.getId());
            notify.setCompanyId(UserUtils.getSelectCompany().getId());
            notify.setType("24");
            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(leave.getAct().getFlag()) ? false : true);
            System.out.println("vars============"+vars.toString());
            // 提交流程任务
            actTaskService.complete(leave.getAct().getTaskId(), leave.getAct().getProcInsId(), leave.getAct().getComment(), vars);
            boolean state = actTaskService.isProcessEnd(leave.getAct().getProcInsId());
            leave.setStatus("2");
            if (!state){
                if ("yes".equals(leave.getAct().getFlag())){
                    leave.setStatus("3");
                }else {
                    leave.setStatus("4");
                }
            }
            leave.preUpdate();
            this.update(leave);

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

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

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

            //抄送
            if("3".equals(leave.getStatus()) || "4".equals(leave.getStatus())){
                ApprovalCopy approvalCopy = approvalCopyService.getByApprovalId(leave.getId());
                if(approvalCopy!=null && StringUtils.isNotBlank(approvalCopy.getCCId())){
                    WorkProjectNotify notify1= new WorkProjectNotify();
                    notify1.setNotifyId(leave.getId());
                    notify1.setCompanyId(UserUtils.getSelectCompany().getId());
                    notify1.setType("24");
                    notify1.setStatus("0");
                    notify1.setNotifyRole("");
                    notify1.setContent(leave.getAct().getComment());
                    String[] ccIds = approvalCopy.getCCId().split(",");
                    for(String ccId : ccIds){
                        if(StringUtils.isNotBlank(ccId)){
                            notify1.setUser(new User(ccId));
                            if("3".equals(leave.getStatus())){
                                notify1.setTitle(UserUtils.get(leave.getCreateBy().getId()).getName()+"的请假申请已通过");
                            }
                            if("4".equals(leave.getStatus())){
                                notify1.setTitle(UserUtils.get(leave.getCreateBy().getId()).getName()+"的请假申请被驳回");
                            }
                            notify1.setRemarks("待通知");
                            notify1.setId("");
                            workProjectNotifyService.save(notify1);
                        }
                    }
                }
            }
            return "保存审核意见成功！";
        }catch (ActivitiObjectNotFoundException e){
            logger.error("ActivitiObjectNotFoundException e:"+e);
            return "流程已审批，不能重新审批！";
        }catch (Exception e){
            logger.error("Exception e:"+e);
            return "保存审核意见失败！！";
        }
    }

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

    public List<Leave> findByCompany2(Leave leave, String date) {
        Map<String,Object> map = new HashMap<>();
        map.put("leave",leave);
        map.put("date",date);
        return leaveDao.findByCompany2(map);
    }

    @Transactional(readOnly = false)
    public void sendNotify(String chaosongIds,String shenpiId,String oaLeaveId) {
        if(StringUtils.isNotBlank(oaLeaveId)){
            if(StringUtils.isNotBlank(chaosongIds)){
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setTitle(UserUtils.getUser().getName()+"发起了请假申请");
                notify.setRemarks("待通知");
                notify.setContent(UserUtils.getUser().getName()+"的请假申请");
                notify.setNotifyRole("");
                notify.setNotifyId(oaLeaveId);
                notify.setStatus("0");
                notify.setCompanyId(UserUtils.getSelectCompany().getId());
                notify.setType("24");
                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(oaLeaveId);
                notify.setStatus("0");
                notify.setCompanyId(UserUtils.getSelectCompany().getId());
                notify.setType("24");
                workProjectNotifyService.save(notify);
            }
        }
    }

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

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

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

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