package yangtz.cs.liu.campus.service.impl.teacher;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.utils.HolidayDateUtil;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.var;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.office.SchoolOfficePurchase;
import yangtz.cs.liu.campus.domain.student.SchoolStudentLeave;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherLeave;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherLeaveMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherLeaveService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.office.OfficeTodoListVO;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherLeaveVO;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherVO;
import yangtz.cs.liu.campus.vo.teacher.TeacherLeaveVO;
import yangtz.cs.liu.wechat.vo.common.WorkFlowVo;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.core.constant.ProcessCommon.PENDING;
import static com.core.constant.ProcessCommon.SUSPENDSTATE_PENDING;
import static com.core.constant.ProcessVariables.*;
import static com.ruoyi.common.utils.DateUtils.getTime;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.StringUtils.isNotNull;
import static com.ruoyi.common.utils.StringUtils.substring;
import static yangtz.cs.liu.campus.constant.EmployeeType.EMPLOYEE;
import static yangtz.cs.liu.campus.constant.EmployeeType.TEACH;
import static yangtz.cs.liu.campus.constant.GradeConstant.GRADELEADER;
import static yangtz.cs.liu.campus.constant.GradeConstant.SECTIONLEADER;
import static yangtz.cs.liu.campus.constant.ProcessState.APPROVAL;
import static yangtz.cs.liu.campus.constant.UserType.TEACHER;
import static yangtz.cs.liu.campus.constant.WorkTime.*;
import static yangtz.cs.liu.campus.constant.WorkTime.PMENDTIME;

@Service
public class SchoolTeacherLeaveServiceImpl extends ServiceImpl<SchoolTeacherLeaveMapper, SchoolTeacherLeave> implements ISchoolTeacherLeaveService {

    @Autowired
    private SchoolTeacherLeaveMapper schoolTeacherLeaveMapper;

    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    @Autowired
    private ISchoolTeacherService schoolTeacherService;

    @Resource
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysDeptService deptService;

    //请假状态为通过
    public static final String PASS = "0";

    @Override
    public List<TeacherLeaveVO> selectSchoolTeacherLeaveList(String submitState, SchoolTeacherLeave schoolTeacherLeave) {
        List<TeacherLeaveVO> teacherLeaveVO = schoolTeacherLeaveMapper.selectSchoolTeacherLeaveList(submitState, schoolTeacherLeave);
        // 当前环节
        for (TeacherLeaveVO leave : teacherLeaveVO) {
            if (StringUtils.isNotBlank(leave.getInstanceId())) {
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(leave.getInstanceId())
                        .list();    // 例如请假会签，会同时拥有多个任务
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    leave.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        leave.setTaskName("已挂起");
                        leave.setSuspendState("2");
                    } else {
                        leave.setTaskName(task.getName());
                        leave.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    leave.setTaskName("已结束");
                }
            } else {
                leave.setTaskName("未启动");
            }
            //判断是否是从钉钉获取到的请假申请(钉钉获取的请假申请没有请假原因)
            if (StringUtils.isEmpty(leave.getReasonForLeave())){
                leave.setTaskName("已结束");
            }
        }
        return teacherLeaveVO;
    }

    /**
     * 教职工信息汇总（请假申请通过的数据）
     */
    @Override
    public List<TeacherLeaveVO> getList(SchoolTeacherLeave schoolTeacherLeave) {
        schoolTeacherLeave.setState(PASS);
        List<TeacherLeaveVO> list = schoolTeacherLeaveMapper.getList(schoolTeacherLeave);
        return list;
    }

    /**
     * 教工请假新增
     */
    @Override
    public int addLeave(SchoolTeacherLeaveVO vo) {
        return 0;
    }

    @Override
    public int removeSchoolTeacherLeaveByIds(List<Long> ids) {
        return schoolTeacherLeaveMapper.removeSchoolTeacherLeaveByIds(ids);
    }

    /**
     * @param schoolTeacherLeave 业务实体
     * @param username           提交申请人 记录到底是哪个人提交了申请
     * @param key                流程标识 用于指定到底启动的是哪个流程(请假流程 办公流程 会议流程等) 这里启动的是 办公流程
     * @param variables          变量集合 流程中指定一些变量,这里我们主要用于动态指定审批人
     *                           <p>
     *                           启动流程
     *                           1. 设置流程申请人.
     *                           2. 设置审批人.审批人因为是动态的,所以放在variables集合里面
     *                           3. 启动流程
     */
    @Override
    public int submitApply(SchoolTeacherLeave schoolTeacherLeave, String username, String key, Map<String, Object> variables) {
        // 业务key 用于对于流程的区分,比如一个办公流程,有很多人都提交了申请,businessKey主要是用来区分不同用户的.toString()因为activiti的表存的是varchar
        String businessKey = schoolTeacherLeave.getId().toString();
        identityService.setAuthenticatedUserId(username);

        //设置级部/处室主任
        variables.put(HANDUSERID1, schoolTeacherLeave.getHandUserId1());
        //设置分管领导
        variables.put(HANDUSERID2, schoolTeacherLeave.getHandUserId2());
        //设置主要领导
        variables.put(HANDUSERID3, schoolTeacherLeave.getHandUserId3());

        //设置销假人
        //variables.put(APPLYUSER, schoolTeacherLeave.getApplyUserId());

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
        String instanceId = processInstance.getId();
        //与我们的业务表开始建立关系
        schoolTeacherLeave.setInstanceId(instanceId);
        schoolTeacherLeave.setState(APPROVAL);
        return schoolTeacherLeaveMapper.updateById(schoolTeacherLeave);
    }

    /**
     * @param entity
     * @param userId
     * @return
     * @author lyric
     * @date 2021-10-07
     * 待办列表
     * <p>
     * 1.根据当前登录人查询出待办任务集合(这里查的不仅是处理人的,还有事用户组的也查出来了,可能之后需要做处理)
     * 2.遍历集合,获取每一个业务对象转vo
     * 3.分页返回
     */
    @Override
    public List<TeacherLeaveVO> findTodoTasks(String key, SchoolTeacherLeave entity, String userId) {
        List<TeacherLeaveVO> list = new ArrayList<>();
        //当前登录人待办任务集合
        List<Task> taskList = processService.findAssigneeTasks(userId, key);
        for (Task task : taskList) {
            TaskEntityImpl taskImpl = (TaskEntityImpl) task;
            //拿到当前任务id
            String processInstanceId = taskImpl.getProcessInstanceId();
            //拿到流程定义对象
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //业务id(我们当时新增的时候指定了businessKey为id)
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolTeacherLeave schoolTeacherLeave = schoolTeacherLeaveMapper.selectById(new Long(businessKey));

//            SysUser user = getTeacherDeptName(schoolTeacherLeave);

            if (StringUtils.isNull(schoolTeacherLeave)) {
                continue;
            }
            //转vo
            TeacherLeaveVO teacherLeaveVO = new TeacherLeaveVO();
            BeanUtils.copyProperties(schoolTeacherLeave, teacherLeaveVO);
            /** 对时间进行处理 */
           /* String datePoor = DateUtils.getDatePoor(schoolTeacherLeave.getEndTime(), schoolTeacherLeave.getStartTime());
            teacherLeaveVO.setTotalTime(datePoor);*/

//            if (isNotNull(user.getDeptId())){
//                teacherLeaveVO.setDeptName(user.getDept().getDeptName());
//            }

            teacherLeaveVO.setTaskId(taskImpl.getId());

            if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                //挂起
                teacherLeaveVO.setTaskName(PENDING);
            } else {
                teacherLeaveVO.setTaskName(taskImpl.getName());
            }
            list.add(teacherLeaveVO);
        }
        List<TeacherLeaveVO> resList = list.stream().sorted(Comparator.comparing(TeacherLeaveVO::getApplyTime).reversed()).collect(Collectors.toList());
        return resList;
    }

    /**
     * @param key
     * @param entity
     * @param userId
     * @return 已办列表
     * @author lyric
     * @date 2021-10-10
     */
    @Override
    public List<TeacherLeaveVO> findDoneTasks(String key, SchoolTeacherLeave entity, String userId) {

        List<TeacherLeaveVO> list = new ArrayList<>();

        //当前登录人完成的历史集合
        List<HistoricTaskInstance> hisList = processService.findDoneTasks(userId, key);

        for (HistoricTaskInstance instance : hisList) {
            //流程实例key
            String processInstanceId = instance.getProcessInstanceId();
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            //业务id
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolTeacherLeave schoolTeacherLeave = schoolTeacherLeaveMapper.selectById(new Long(businessKey));

//            SysUser user = getTeacherDeptName(schoolTeacherLeave);

            if (StringUtils.isNull(schoolTeacherLeave)) {
                continue;
            }
            //转vo
            TeacherLeaveVO teacherLeaveVO = new TeacherLeaveVO();
            BeanUtils.copyProperties(schoolTeacherLeave, teacherLeaveVO);
            /** 对时间进行处理 */
            String datePoor = DateUtils.getDatePoor(schoolTeacherLeave.getEndTime(), schoolTeacherLeave.getStartTime());
            //teacherLeaveVO.setTotalTime(datePoor);
//            if (isNotNull(user.getDeptId())){
//                teacherLeaveVO.setDeptName(user.getDept().getDeptName());
//            }
            list.add(teacherLeaveVO);
        }
        List<TeacherLeaveVO> resList = list.stream().sorted(Comparator.comparing(TeacherLeaveVO::getApplyTime).reversed()).collect(Collectors.toList());
        return resList;
    }

    //待办已办
    @Override
    public List<TeacherLeaveVO> findTasks(String key, String userId) {
        List<TeacherLeaveVO> list = new ArrayList<>();
        //当前登录人待办任务集合
        List<Task> taskList = processService.findAssigneeTasks(userId, key);
        for (Task task : taskList) {
            TaskEntityImpl taskImpl = (TaskEntityImpl) task;
            //拿到当前任务id
            String processInstanceId = taskImpl.getProcessInstanceId();
            //拿到流程定义对象
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //业务id(我们当时新增的时候指定了businessKey为id)
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolTeacherLeave schoolTeacherLeave = schoolTeacherLeaveMapper.selectById(new Long(businessKey));
            if (StringUtils.isNull(schoolTeacherLeave)) {
                continue;
            }
            //转vo
            TeacherLeaveVO teacherLeaveVO = new TeacherLeaveVO();
            BeanUtils.copyProperties(schoolTeacherLeave, teacherLeaveVO);
            teacherLeaveVO.setTaskId(taskImpl.getId());

            if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                //挂起
                teacherLeaveVO.setTaskName(PENDING);
            } else {
                teacherLeaveVO.setTaskName(taskImpl.getName());
            }
            list.add(teacherLeaveVO);
        }

        //当前登录人完成的历史集合
        List<HistoricTaskInstance> hisList = processService.findDoneTasks(userId, key);
        for (HistoricTaskInstance instance : hisList) {
            //流程实例key
            String processInstanceId = instance.getProcessInstanceId();
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            //业务id
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolTeacherLeave schoolTeacherLeave = schoolTeacherLeaveMapper.selectById(new Long(businessKey));
            if (StringUtils.isNull(schoolTeacherLeave)) {
                continue;
            }
            //转vo
            TeacherLeaveVO teacherLeaveVO = new TeacherLeaveVO();
            BeanUtils.copyProperties(schoolTeacherLeave, teacherLeaveVO);
            list.add(teacherLeaveVO);
        }
        List<TeacherLeaveVO> resList = list.stream().sorted(Comparator.comparing(TeacherLeaveVO::getApplyTime).reversed()).collect(Collectors.toList());
        return resList;
    }

    /**
     * 获取教师请假审批中教师姓名
     *
     * @param schoolTeacherLeave
     */
    public SysUser getTeacherDeptName(SchoolTeacherLeave schoolTeacherLeave) {
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.select(SchoolTeacher::getUserId).eq(SchoolTeacher::getId, schoolTeacherLeave.getTeacherId());
        SchoolTeacher teacher = schoolTeacherMapper.selectOne(lqw);
        Long teacherUserId = teacher.getUserId();
        SysUser user = userService.selectUserById(teacherUserId);
        return user;
    }

    /**
     * 时间换算（秒-> 天 时 分 秒）
     * @return
     */
//    public String timeConversion(Long totalTime){
//        int day= (int) Math.floor(totalTime / 86400000); //天
//        int hours = (int) Math.floor((totalTime % 86400000) / 3600); //小时
//        int minutes = (int) Math.floor(((totalTime % 86400000) % 3600) / 60); //分钟
//        return (day + "天" + hours + "时" + minutes + "分" );
//    }

    /**
     * @author lyric
     * @date 2021-10-11
     * 设置候选组
     */
    public void setCandidateUser(String key, Map<String, Object> variables) {
        List<SysUser> userList = userService.selectUserListByRoleKey(key);
        List<String> userIds = userList.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
        String candidateUsers = String.join(",", userIds);
        variables.put(CHARGEUSERIDS, candidateUsers);
    }

    /**
     * @param taskId
     * @param schoolTeacherLeave 销假
     * @author lyric
     * @date 2022/10/28 10:44
     */
    @Override
    public void cancelLeave(String taskId, SchoolTeacherLeave schoolTeacherLeave) {
        //修改实际开始时间,实际结束时间
        schoolTeacherLeaveMapper.updateById(schoolTeacherLeave);
        //结束任务
        taskService.complete(taskId);
    }

    /**
     * 获取请假详情
     */
    @Override
    public TeacherLeaveVO selectById(Long id) {
        return schoolTeacherLeaveMapper.getById(id);
    }

    /**
     * 获取级部主任或处室主任
     */
    @Override
    public List<SchoolTeacher> getLeader(Long applyOrgid, String employeeType, SchoolTeacherVO teacherVO) {
        //判断用户所有部门是属于级部还是科室
        SysDept sysDept = deptService.selectDeptById(applyOrgid);
        String ancestors = sysDept.getAncestors();
        //查询级部
        List<SysDept> sysDepts = deptService.selectGrade(new SysDept());
        if (sysDepts.size() > 0){
            for (SysDept dept : sysDepts) {
                if (ancestors.contains(dept.getDeptId().toString())){
                    employeeType = "0";
                    applyOrgid = dept.getDeptId();
                    break;
                }
            }
        }
        //如果是教工，则传过来的是级部id
        if (employeeType.equals(TEACH)) {
            List<SchoolTeacher> teacherList = gradeMentorService.getGradeDirector(applyOrgid, GRADELEADER, teacherVO);
            return teacherList;
        }
        //职工，所处处室（部门）id
        String[] split = ancestors.split(",");
        if (split.length >= 4){
            //获取第三级部门
            applyOrgid = Long.parseLong(split[3]);
        }
        return schoolTeacherService.getSectionDirector(applyOrgid, SECTIONLEADER, teacherVO);
    }

    /**
     * 教工请假时长处理
     */
    @Override
    public int teacherLeaveDeal(SchoolTeacherLeave leave, List<String> restList) {
        //判断所需数据不为空
        if (StringUtils.isNull(leave.getStartTime()) || StringUtils.isNull(leave.getStartSort())
                || StringUtils.isNull(leave.getEndTime()) || StringUtils.isNull(leave.getEndSort())) {
            throw new ServiceException("请假开始时间或结束时间不完整，请检查");
        }
        String startTime = HolidayDateUtil.format1.format(leave.getStartTime());
        String endTime = HolidayDateUtil.format1.format(leave.getEndTime());
        int startSort = Integer.valueOf(leave.getStartSort());
        int endSort = Integer.valueOf(leave.getEndSort());
        return HolidayDateUtil.courseNum(startTime, endTime, startSort, endSort, restList);
    }

    /**
     * 职工请假时长处理
     */
    @Override
    public double workerLeaveDeal(SchoolTeacherLeave leave, List<String> restList) {
        //判断所需数据不为空
        if (StringUtils.isNull(leave.getStartTime()) || StringUtils.isNull(leave.getEndTime())) {
            throw new ServiceException("请假开始时间或结束时间不完整，请检查");
        }
        String startTime = HolidayDateUtil.format.format(leave.getStartTime());
        String endTime = HolidayDateUtil.format.format(leave.getEndTime());

        return HolidayDateUtil.calculateTimeHour(startTime, endTime, AMSTARTTIME, AMENDTIME, PMSTARTTIME, PMENDTIME, restList);
    }

    @Override
    public void judgeDate(SchoolTeacherLeave leave){
        if(StringUtils.isNull(leave.getStartTime())){
            throw new ServiceException("请假开始时间未选择");
        }
        if(StringUtils.isNull(leave.getEndTime())){
            throw new ServiceException("请假结束时间未选择");
        }
        //判断请假开始结束时间是否合理开始时间<=结束时间
        String start = HolidayDateUtil.format.format(leave.getStartTime());
        String end = HolidayDateUtil.format.format(leave.getEndTime());

        int res = start.compareTo(end);
        if(res > 0){
            throw new ServiceException("请假开始时间大于结束时间，时间选择不合理");
        } else if (res == 0) {
           // 时间相同
            //当请假人为教工时
            if(TEACH.equals(leave.getApplyType())){
                if(StringUtils.isNull(leave.getStartSort())){
                    throw new ServiceException("请假开始课程节次未选择");
                }
                if(StringUtils.isNull(leave.getEndSort())){
                    throw new ServiceException("请假结束课程节次未选择");
                }
                if(Integer.parseInt(leave.getStartSort()) > Integer.parseInt(leave.getEndSort())){
                    throw new ServiceException("课程节次选择不合理");
                }
            }
        }
    }


    /**
     * 根据请假总时长判断用户是否选择对应节点的审批人
     * 请假半天（0.5天）,选择级部处室主任（必填，不需判断）
     * 半天到2天之间，选择分管领导
     * 2天以上选择主要领导
     */
    @Override
    public void judgeHandUser(SchoolTeacherLeave leave) {
        //判断请假开始结束时间是否合理开始时间<=结束时间
        double time = leave.getTotalTime();
        if (0.5 < time && time <= 2) {
            if (leave.getHandUserId2() == null) {
                throw new ServiceException("您还没有选择分管领导");
            }
        }

        if (time > 2) {
            if (leave.getHandUserId2() == null || leave.getHandUserId3() == null) {
                throw new ServiceException("您的请假天数超过两天，请选择分管领导和主要领导");
            }
        }
    }

    //如果新增时请假时间大于2天，此时数据库中存了分管领导和主要领导的信息
    // 在修改时，如果改后的请假时长小于2天后或半天后，则对应的应将数据库中分管领导或主要领导删除、
    /**
     * 根据请假总时长判断用户是否选择对应节点的审批人
     * 请假半天（0.5天）,选择级部处室主任（必填，不需判断）
     * 半天到2天之间，选择分管领导0.5< X <= 2
     * 2天以上选择主要领导>2
     */
    @Override
    public int editLeave(SchoolTeacherLeave schoolTeacherLeave) {

        //判断这种情况，新增时教师类型是教工，，后来修改为职工，
        SchoolTeacherLeave leave = schoolTeacherLeaveMapper.selectById(schoolTeacherLeave.getId());
        //
        LambdaUpdateWrapper<SchoolTeacherLeave> luw = new LambdaUpdateWrapper<>();
        luw
                .eq(SchoolTeacherLeave::getId,schoolTeacherLeave.getId())
                .set(SchoolTeacherLeave::getTitle,schoolTeacherLeave.getTitle())
                .set(SchoolTeacherLeave::getTeacherId,schoolTeacherLeave.getTeacherId())
                .set(SchoolTeacherLeave::getTeacherName,schoolTeacherLeave.getTeacherName())
                .set(SchoolTeacherLeave::getApplyOrgid,schoolTeacherLeave.getApplyOrgid())
                .set(SchoolTeacherLeave::getApplyOrgname,schoolTeacherLeave.getApplyOrgname())
                .set(SchoolTeacherLeave::getApplyType,schoolTeacherLeave.getApplyType())
                .set(SchoolTeacherLeave::getApplyUser,schoolTeacherLeave.getApplyUser())
                .set(SchoolTeacherLeave::getStartTime,schoolTeacherLeave.getStartTime())
                .set(SchoolTeacherLeave::getEndTime,schoolTeacherLeave.getEndTime())
                .set(SchoolTeacherLeave::getTotalTime,schoolTeacherLeave.getTotalTime())
                .set(SchoolTeacherLeave::getType,schoolTeacherLeave.getType())
                .set(SchoolTeacherLeave::getReasonForLeave,schoolTeacherLeave.getReasonForLeave())
                .set(SchoolTeacherLeave::getHandUserId1,schoolTeacherLeave.getHandUserId1())
                .set(SchoolTeacherLeave::getHandUserName1,schoolTeacherLeave.getHandUserName1())
                .set(SchoolTeacherLeave::getState,schoolTeacherLeave.getState())
                ;
        // TODO 修改 判断这种情况，新增时教师类型是教工0，，后来修改为职工1，则课次、级部/处室主任需要从表里删除
        if(EMPLOYEE.equals(schoolTeacherLeave.getApplyType())){
            luw
                    .set(SchoolTeacherLeave::getStartSort,null)
                    .set(SchoolTeacherLeave::getEndSort,null)
                    .set(SchoolTeacherLeave::getHandUserId1,null)
                    .set(SchoolTeacherLeave::getHandUserName1,null)
                    ;
            schoolTeacherLeave.setStartSort(null);
            schoolTeacherLeave.setEndSort(null);
            schoolTeacherLeave.setHandUserId1(null);
            schoolTeacherLeave.setHandUserName1(null);
        }
        double time = schoolTeacherLeave.getTotalTime();
        //处理请假时长与分管领导、主要领导
        if (0.5 < time && time <= 2) {
            //此时需要将主要领导置空
           luw
                   .set(SchoolTeacherLeave::getHandUserId3,null)
                   .set(SchoolTeacherLeave::getHandUserName3,null)
                   ;
           schoolTeacherLeave.setHandUserId3(null);
           schoolTeacherLeave.setHandUserName3(null);
        }

        if (time <= 0.5) {
            //此时需要将分管领导和主要领导置空
            luw
                    .set(SchoolTeacherLeave::getHandUserId2,null)
                    .set(SchoolTeacherLeave::getHandUserName2,null)
                    .set(SchoolTeacherLeave::getHandUserId3,null)
                    .set(SchoolTeacherLeave::getHandUserName3,null)
            ;
            schoolTeacherLeave.setHandUserId2(null);
            schoolTeacherLeave.setHandUserName2(null);
            schoolTeacherLeave.setHandUserId3(null);
            schoolTeacherLeave.setHandUserName3(null);
        }
        return schoolTeacherLeaveMapper.update(schoolTeacherLeave,luw);
    }

    @Override
    public WorkFlowVo workFlows(Long id) {
        SchoolTeacherLeave teacherLeave = schoolTeacherLeaveMapper.selectById(id);
        String instanceId = teacherLeave.getInstanceId();
        List<String> messages = schoolTeacherLeaveMapper.selectComment(instanceId);
        WorkFlowVo workFlowVo = new WorkFlowVo();
        List<String> newMessages = new ArrayList<>();
        List<String> handleUserName = new ArrayList<>();
        for (String message : messages) {
            String substring = substring(message, 1, 3);
            newMessages.add(substring);
        }
        if (teacherLeave.getHandUserName1() != null) {
            handleUserName.add(teacherLeave.getHandUserName1());
        }
        if (teacherLeave.getHandUserName2() != null) {
            handleUserName.add(teacherLeave.getHandUserName2());
        }
        if (teacherLeave.getHandUserName3() != null) {
            handleUserName.add(teacherLeave.getHandUserName3());
        }
        workFlowVo.setComment(newMessages);
        workFlowVo.setHandUserName(handleUserName);
        /*******************通过用户id查询用户的职务*****************************/
        return workFlowVo;
    }
}

