package cn.wisenergy.service.impl;

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.WorkTimeOrderMapper;
import cn.wisenergy.model.app.*;
import cn.wisenergy.model.dto.*;
import cn.wisenergy.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
@Slf4j
public class WorkTimeOrderServiceImpl implements WorkTimeOrderService {

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private WorkProjectService workProjectService;

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    @Autowired
    private WorkDeptService workDeptService;

    @Autowired
    private WorkSubmitAdoptService workSbumitAdoptService;

    @Autowired
    private WorkHolidayService workHolidayService;

    @Autowired
    private WorkCollectService workCollectService;

    @Autowired
    private WorkUserDeptService workUserDeptService;

    @Autowired
    private WorkUserProjectService workUserProjectService;


    /**
     * 功能; 获取某日被驳回说明
     *
     * @param userId  用户id
     * @param workDay 某日
     * @return 工单集合
     */
    @Override
    public List<WorkTimeOrder> getByDay(Integer userId, Date workDay) {
        log.info("WorkTimeOrderServiceImpl[]getDayRejectReason[]input.param.userId:{},workDay:{}" + userId, workDay);
        if (null == userId || null == workDay) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.getByDay(userId, workDay);
        if (CollectionUtils.isEmpty(workTimeOrders)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }
        return workTimeOrders;
    }

    /**
     * 功能：获取某日填报小计
     *
     * @param userId  用户id
     * @param workDay 某日
     * @return 填报小计
     */
    @Override
    public SubtotalDto getSubtotalReport(Integer userId, Date workDay) {
        log.info("WorkTimeOrderServiceImpl[]getSubtotalReport[]input.param.userId:{},workDay:{}" + userId, workDay);
        if (null == userId || StringUtils.isEmpty(workDay)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }

        List<WorkTimeOrder> workTimeOrders = getByDay(userId, workDay);
        if (CollectionUtils.isEmpty(workTimeOrders)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }
        SubtotalDto subtotalDto = new SubtotalDto();
        // 今日总工时
        int totalTime = 0;
        // 被驳回原因
        String reason = "";
        // 今日被驳回次数
        int rejectMonth = 0;
        subtotalDto.setUserId(userId);
        subtotalDto.setWorkDay(workDay);
        for (WorkTimeOrder wto : workTimeOrders) {
            totalTime += wto.getWorkTime();
            if (null != wto.getReason()) {
                reason = wto.getProjectName() + ":" + wto.getReason() + ";";
            }
            if (3 == wto.getStatus()) {
                rejectMonth += 1;
            }
        }
        subtotalDto.setReason(reason);
        subtotalDto.setTotalTime(totalTime);
        subtotalDto.setRejectMonth(rejectMonth);
        return subtotalDto;
    }

    /**
     * 功能; 获取某日填报信息
     *
     * @param userId  用户id
     * @param workDay 工作日
     * @return dto
     */
    @Override
    public List<WorkTimeOrderDto> getByDayToDto(Integer userId, Date workDay) {
        log.info("WorkTimeOrderServiceImpl[]getByDayToDto[]input.param.userId:{},workDay:{}" + userId, workDay);
        List<WorkTimeOrder> workTimeOrders = getByDay(userId, workDay);
        if (CollectionUtils.isEmpty(workTimeOrders)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }
        return wtoToWtod(workTimeOrders);
    }

    /**
     * 功能：工时填报
     *
     * @param dto 自定义填报类
     * @return dto
     */
    @Transactional
    @Override
    public List<WorkTimeOrderDto> add(@RequestBody CreateWorkOrderDto dto) {
        log.info("WorkTimeOrderServiceImpl[]add[]input.param.CreateWorkOrderDto:{}" + dto);
        if (null == dto || CollectionUtils.isEmpty(dto.getWorkTimeOrders())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }

        // 1.检查工单
        this.checkWorkOrderInfo(dto.getWorkTimeOrders());

        // 2.保存工单信息
        List<WorkTimeOrderDto> result = this.saveWorkOrderInfo(dto.getWorkTimeOrders());
        log.info("WorkOrderServiceImpl[]add[]add.success");
        return result;
    }

    /**
     * 功能： 驳回重新填报
     *
     * @param dto 自定义DTO
     * @return 填报信息
     */
    @Transactional
    @Override
    public List<WorkTimeOrderDto> update(CreateWorkOrderDto dto) {
        log.info("WorkTimeOrderServiceImpl[]update[]input.param.CreateWorkOrderDto:{}" + dto);
        if (null == dto || CollectionUtils.isEmpty(dto.getWorkTimeOrders())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<WorkTimeOrderDto> workTimeOrders = dto.getWorkTimeOrders();
        // 判断是否超过8小时
        int count = 0;
        List<WorkTimeOrderDto> byDayToDto = getByDayToDto(workTimeOrders.get(0).getUserId(), workTimeOrders.get(0).getWorkDay());
        for (WorkTimeOrderDto orderDto : byDayToDto) {
            if (2 == orderDto.getStatus() || 5 == orderDto.getStatus())
                count += orderDto.getWorkTime();
        }
        timeNotEight(count, workTimeOrders);

        // 更新数据
        reSubmit(workTimeOrders);
        return dto.getWorkTimeOrders();
    }


    /**
     * 功能：获取待审批数据
     *
     * @param userId    用户id
     * @param projectId 项目id
     * @param type      项目类型
     * @param status    状态
     * @return 自定义dto
     */
    @Override
    public  PageInfo<WorkTimeOrder> getExamine(Integer userId, Integer projectId, Integer type, Integer page, Integer size, Integer status) {
        log.info("WorkOrderServiceImpl[]getExamine[]input.param.userId:{},projectId:{},type:{},page:{},size:{},status:{}" + userId, projectId, type, page, size, status);
        // 判断当前用户是否是管理员
        isManager(userId);
        WorkUser user = workUserService.getById(userId);
        // PC端
        if (null != page && null != size) {
            return pageExamine(user, projectId, type, page, size, status);
        }

        return null;
    }

    /**
     * 功能：获取小程序待审批
     *
     * @param userId    用户id
     * @param projectId 项目Id
     * @param type      类型
     * @return
     */
    @Override
    public List<AppletsPendApprovalDto> getExamineApplets(Integer userId, Integer projectId, Integer type) {
        log.info("WorkOrderServiceImpl[]getExamineApplets[]input.param.userId:{},projectId:{},type:{}" + userId, projectId, type);
        isManager(userId);
        WorkUser user = workUserService.getById(userId);
        // 项目经理
        if (1 == user.getLevel()) {
            QueryWrapper<WorkTimeOrder> wrapper = new QueryWrapper<>();
            projectId = projectId == null ? workProjectService.getByManagerId(userId).get(0).getId() : projectId;
            wrapper.in("status", 1, 4);
            wrapper.eq("project_id", projectId);
            wrapper.orderByDesc("work_day");
            List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectList(wrapper);
            return getDto(workTimeOrders);
        }
        // 部门经理
        if (2 == user.getLevel()) {
            type = null == type ? 5 : type;
            Integer deptId = user.getDeptId();
            QueryWrapper<WorkTimeOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("dept_id", deptId);
            wrapper.in("status", 1, 4);
            wrapper.eq("type", type);
            List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectList(wrapper);
            if (CollectionUtils.isEmpty(workTimeOrders)) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_END);
            }
            return getDto(workTimeOrders);
        }
        return null;
    }

    private List<AppletsPendApprovalDto> getDto(List<WorkTimeOrder> workTimeOrders) {
        List<AppletsPendApprovalDto> appletsPendApprovalDtos = new ArrayList<>();
        Date date = workTimeOrders.get(0).getWorkDay();
        AppletsPendApprovalDto dto = new AppletsPendApprovalDto();
        dto.setWorkDay(date);
        appletsPendApprovalDtos.add(dto);
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            if (date.compareTo(workTimeOrder.getWorkDay()) != 0) {
                date = workTimeOrder.getWorkDay();
                AppletsPendApprovalDto dto2 = new AppletsPendApprovalDto();
                dto2.setWorkDay(workTimeOrder.getWorkDay());
                appletsPendApprovalDtos.add(dto2);
            }
        }
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            System.out.println(workTimeOrder);
        }
        for (AppletsPendApprovalDto approvalDto : appletsPendApprovalDtos) {
            List<WorkTimeOrderDto> workTimeOrderList = new ArrayList<>();
            for (WorkTimeOrder workTimeOrder : workTimeOrders) {
                if (approvalDto.getWorkDay().compareTo(workTimeOrder.getWorkDay()) == 0) {
                    WorkTimeOrderDto workTimeOrderDto = new WorkTimeOrderDto();
                    BeanUtils.copyProperties(workTimeOrder, workTimeOrderDto);
                    workTimeOrderList.add(workTimeOrderDto);
                }
            }
            approvalDto.setWorkTimeOrderDto(workTimeOrderList);
        }
        return appletsPendApprovalDtos;
    }

    /**
     * 功能：批量审批
     *
     * @param reviewerId 审批人
     * @param ids        工单
     * @return 是否成功
     */
    @Transactional
    @Override
    public Boolean examineByIds(Integer reviewerId, List<Integer> ids) {
        log.info("WorkOrderServiceImpl[]examineByIds[]input.param.ids:" + ids);
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }

        Integer level = workUserService.getById(reviewerId).getLevel();
        if (level == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }

        int i = workTimeOrderMapper.updateByIds(reviewerId, ids);
        if (i == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_DATA_FAIL);
        }

        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectBatchIds(ids);
        Integer userId;
        Date workDay;
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            userId = workTimeOrder.getUserId();
            workDay = workTimeOrder.getWorkDay();

            WorkCollect workCollect = workCollectService.getByUserIdAndWorkDay(userId, workDay);
            if (null == workCollect) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
            }
            workCollect.setStatus(2);
            workCollect.setTotalTime(0);
            workCollectService.update(workCollect);
        }
        return true;
    }

    /**
     * 功能： 驳回
     *
     * @param reviewerId 审核人id
     * @param id         工单id
     * @param reason     驳回理由
     * @return 是否成功
     */
    @Transactional
    @Override
    public Boolean rejectById(Integer reviewerId, Integer id, String reason) {
        log.info("WorkOrderServiceImpl[]rejectById[]input.param.reviewerId:{},id:{},reason:{}" + reviewerId, id, reason);
        if (null == reviewerId || null == id || StringUtils.isEmpty(reason)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        Integer level = workUserService.getById(reviewerId).getLevel();
        if (level == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }

        int i = workTimeOrderMapper.updateStatusById(reviewerId, id, reason);
        if (i == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_DATA_FAIL);
        }
        WorkTimeOrder workTimeOrder = workTimeOrderMapper.selectById(id);
        Integer userId = workTimeOrder.getUserId();
        Date workDay = workTimeOrder.getWorkDay();
        WorkCollect workCollect = workCollectService.getByUserIdAndWorkDay(userId, workDay);
        if (null == workCollect) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }
        workCollect.setStatus(3);
        workCollect.setTotalTime(0);
        return workCollectService.update(workCollect);
    }

    /**
     * 功能：查询驳回未提交的
     *
     * @param userId 用户id
     * @return dto
     */
    @Transactional
    @Override
    public List<WorkTimeOrderDto> rejectNotSubmit(Integer userId) {
        log.info("WorkOrderServiceImpl[]rejectById[]input.param.id:{}" + userId);
        isManager(userId);
        QueryWrapper<WorkTimeOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("reviewer_id", userId);
        wrapper.eq("status", 3);
        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(workTimeOrders)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_INFO_IS_NULL);
        }

        return wtoToWtod(workTimeOrders);
    }

    /**
     * 功能：获取用户参与的项目
     *
     * @param userId
     * @return
     */
    @Override
    public List<ProjectDto> getProjectDto(Integer userId) {
        log.info("WorkOrderServiceImpl[]getProjectDto[]input.param.id:{}" + userId);
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<Integer> ids = workUserProjectService.getProjectIdByUserId(userId);
        List<ProjectDto> list = workProjectService.getNameById(ids);
        Integer deptId = workUserDeptService.getDeptIdByUserId(userId);
        List<Integer> idsByDeptId = workUserDeptService.getUserIdsByDeptId(deptId);
        WorkUser workUser = workUserService.getDeptManagerByIds(idsByDeptId);
        list.add(new ProjectDto().setType(5).setProjectName(getTypeName(5)));
        list.add(new ProjectDto().setType(6).setProjectName(getTypeName(6)));
        list.add(new ProjectDto().setType(7).setProjectName(getTypeName(7)));
        list.forEach(index -> index.setDeptManagerName(workUser.getName()));
        return list;
    }

    // workTimeOrder TO WorkTimeOrderDto
    private List<WorkTimeOrderDto> wtoToWtod(List<WorkTimeOrder> workTimeOrders) {
        List<WorkTimeOrderDto> dtos = new ArrayList<>();
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            WorkTimeOrderDto dto = new WorkTimeOrderDto();
            BeanUtils.copyProperties(workTimeOrder, dto);
            dto.setProjectManagerName(getManagerNameByOrder(workTimeOrder));
            dto.setTypeName(getTypeName(dto.getType()));
            dtos.add(dto);
        }

        return dtos;
    }

    private List<ExamineGroupbyProjectDto> getExamineGroupByProjectDto(Integer projectId) {
        QueryWrapper<WorkTimeOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        wrapper.in("status", 1, 4);
        wrapper.orderByDesc("work_day");
        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectList(wrapper);
        return WorkTimeOrderTOEGPD(workTimeOrders);
    }

    private List<ExamineGroupbyProjectDto> WorkTimeOrderTOEGPD(List<WorkTimeOrder> workTimeOrders) {
        if (CollectionUtils.isEmpty(workTimeOrders)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_END);
        }
        List<ExamineGroupbyProjectDto> egpds = new ArrayList<>();
        for (WorkTimeOrder workTimeOrder : workTimeOrders) {
            ExamineGroupbyProjectDto dto = new ExamineGroupbyProjectDto();
            BeanUtils.copyProperties(workTimeOrder, dto);
            egpds.add(dto);
        }
        return egpds;
    }


    private void checkWorkOrderInfo(List<WorkTimeOrderDto> list) {
        log.info("WorkOrderServiceImpl[]checkWorkOrderInfo[]input.method");
        // 1、工单时间不能大于当前天
        Date date = new Date();
        WorkSubmitAdopt workSubmitAdopt = workSbumitAdoptService.getById(1);
        Integer submitTime = workSubmitAdopt.getSubmitTime();
        for (WorkTimeOrderDto dto : list) {
            if (null == dto.getDes()) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.DES_NOT_NULL);
            }
            if (thanDate(dto.getWorkDay())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_TIME_OVER_NOW_DAY);
            }

            if (null == dto.getWorkDay() || null == dto.getWorkTime()) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
            }
            // 2、默认设置超过系统默认3天（包括驳回3天）未填报的工时将不能填报
            if (date.getTime() - dto.getWorkDay().getTime() > submitTime * 24 * 60 * 60 * 1000) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_DAY_THAN_DATE);
            }
            // 3.判断当日是否已经填报
            WorkCollect byUserIdAndWorkDay = workCollectService.getByUserIdAndWorkDay(dto.getUserId(), dto.getWorkDay());
            if (null != byUserIdAndWorkDay) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_ORDER_ALREADY_COMMIT);
            }
        }
        // 4.每天工时累加不得超过八小时
        timeNotEight(0, list);


    }


    //3.每天工时累加不得超过八小时
    private void timeNotEight(int count, List<WorkTimeOrderDto> list) {
        for (WorkTimeOrderDto workOrder : list) {
            count = count + workOrder.getWorkTime();
            if (count > 8) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_TIME_NOT_OVER_EIGHT);
            }
        }
    }

    //判断填报是否超过今天
    private boolean thanDate(Date date) {
        Date date1 = new Date();
        int i;
        i = date1.compareTo(date);
        return -1 == i;
    }

    // 驳回重新填报
    private void reSubmit(List<WorkTimeOrderDto> workTimeOrders) {
        WorkSubmitAdopt workSubmitAdopt = workSbumitAdoptService.getById(1);
        Integer submitTime = workSubmitAdopt.getSubmitTime();
        for (WorkTimeOrderDto workTimeOrderDto : workTimeOrders) {
            if (null == workTimeOrderDto.getDes()) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.DES_NOT_NULL);
            }
            WorkTimeOrder order = workTimeOrderMapper.selectById(workTimeOrderDto.getWorkId());
            if (order.getWorkDay().compareTo(workTimeOrderDto.getWorkDay()) != 0) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.DATE_IS_ERROR);
            }
            Date modifyTime = order.getModifyTime();
            // 判断是否已经驳回三天
            if (new Date().getTime() - DateUtil.getStartOfDay(modifyTime).getTime() > submitTime * 24 * 60 * 60 * 1000) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_DAY_THAN_DATE);
            }
            WorkTimeOrder workTimeOrder = new WorkTimeOrder();
            BeanUtils.copyProperties(workTimeOrderDto, workTimeOrder);
            workTimeOrder.setStatus(4);
            // 获取用户名
            workTimeOrder.setUserName(workUserService.getById(workTimeOrder.getUserId()).getName());
            // 获取项目名
            if (1 == workTimeOrder.getType() || 2 == workTimeOrder.getType()) {
                workTimeOrder.setProjectName(workProjectService.getById(workTimeOrder.getProjectId()).getProjectName());
            }
            // 获取部门id
            Integer deptIdByUserId = workUserDeptService.getDeptIdByUserId(workTimeOrder.getUserId());
            workTimeOrder.setDeptId(deptIdByUserId);
            Date workDay = workTimeOrder.getWorkDay();
            // 默认正常工时
            workTimeOrder.setIsOvertime(0);
            if (workHolidayService.isHoliday(workDay)) {
                workTimeOrder.setIsOvertime(1);
            }
            int iRow = workTimeOrderMapper.updateById(workTimeOrder);
            if (0 == iRow) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_DATA_FAIL);
            }
            WorkCollect workCollect = new WorkCollect();
            BeanUtils.copyProperties(workTimeOrder, workCollect);
            workCollect.setStatus(1);
            workCollect.setTotalTime(workTimeOrder.getWorkTime());
            workCollectService.update(workCollect);
        }
    }

    private List<WorkTimeOrderDto> saveWorkOrderInfo(List<WorkTimeOrderDto> list) {
        log.info("WorkOrderServiceImpl[]saveWorkOrderInfo[]input.method");
        int totalTime = 0;
        int status = 1;
        //根据用户id,获取用户信息

        for (WorkTimeOrderDto dto : list) {
            WorkTimeOrder workTimeOrder = new WorkTimeOrder();
            // 获取用户名
            dto.setUserName(workUserService.getById(dto.getUserId()).getName());
            // 获取项目名
            if ((1 == dto.getType() || 2 == dto.getType()) && null == dto.getProjectId()) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.NO_JOIN_EVERY_PROJECT_PLASE_JION);
            }
            dto.setProjectName(null != dto.getProjectId() ? workProjectService.getById(dto.getProjectId()).getProjectName() : getTypeName(dto.getType()));

            // 获取部门id
            workTimeOrder.setDeptId(workUserDeptService.getDeptIdByUserId(dto.getUserId()));
            Date workDay = dto.getWorkDay();
            // 默认正常工时
            workTimeOrder.setIsOvertime(0);
            if (workHolidayService.isHoliday(workDay)) {
                workTimeOrder.setIsOvertime(1);
            }
            dto.setStatus(status);
            // 如果是请假或者调休直接通过
            if (3 == dto.getType() || 4 == dto.getType()) {
                dto.setStatus(2);
                dto.setProjectName(null);
                dto.setProjectId(null);
            }
            BeanUtils.copyProperties(dto, workTimeOrder);
            int saveRow = workTimeOrderMapper.save(workTimeOrder);
            if (0 == saveRow) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.INSERT_DATA_IS_FAIL);
            }
            totalTime += workTimeOrder.getWorkTime();
        }
        WorkCollect workCollect = new WorkCollect();
        BeanUtils.copyProperties(list.get(0), workCollect);
        workCollect.setTotalTime(totalTime);
        workCollect.setStatus(status);
        if (!workCollectService.insertCollect(workCollect)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INSERT_DATA_IS_FAIL);
        }

        return list;
    }


    // 审批分页
    private PageInfo<WorkTimeOrder> pageExamine(WorkUser user, Integer projectId, Integer type, Integer page, Integer size, Integer status) {
        log.info("WorkOrderServiceImpl[]pageExamine[]input.param.user:{},projectId:{},type:{},page:{},size:{},status:{}" + user, projectId, type, page, size, status);
        PageHelper.startPage(page, size);
        List<WorkTimeOrder> workTimeOrders;
        workTimeOrders = null;
        Integer level = user.getLevel();
        List<Integer> types;
        // 项目经理
        if (1 == level) {
            types = type == null ? Arrays.asList(1, 2, 3, 4) : new ArrayList<>(type);
            workTimeOrders = workTimeOrderMapper.queryByPage(status, projectId, types);
        }
        // 部门经理
        if (2 == level) {
            types = type == null ? Arrays.asList(3, 4, 5, 6) : new ArrayList<>(type);
            workTimeOrders = workTimeOrderMapper.queryByPage(status, null, types);
        }
        PageInfo<WorkTimeOrder> pageInfo = new PageInfo<>(workTimeOrders);

        return pageInfo;
    }


    // 根据工单获取管理员
    private String getManagerNameByOrder(WorkTimeOrder wto) {
        if (1 == wto.getType() || 2 == wto.getType() ) {
            WorkProject workProject = workProjectService.getById(wto.getProjectId());
            return workProject != null ? workUserService.getById(workProject.getManagerId()).getName() : "";
        }
        if (1 != wto.getType() || 2 != wto.getType()) {
            return workUserService.getById(
                    workDeptService.getById(wto.getDeptId()).getDeptManagerId())
                    .getName();
        }
        return null;
    }

    // 判断当前用户是否是管理员
    private void isManager(Integer userId) {
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        // 判断当前用户是否为管理
        WorkUser user = workUserService.getById(userId);
        if (0 == user.getLevel()) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
    }

    private String getTypeName(Integer type) {
        String[] str = {"项目", "商机", "请假", "调休", "外部商务、技术交流", "内部培训、技术准备、管理", "其他非项目/商机工作"};
        return str[--type];
    }

}
