package com.sunxung.factoring.service.weekWorkPlan.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.component.util.DateUtil;
import com.sunxung.factoring.dict.impl.WorkStateDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.ValidatorEntity.ValidatorType;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.Project;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.Org;
import com.sunxung.factoring.entity.sys.Permission;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.sys.flowable.FlowActivityDefinition;
import com.sunxung.factoring.entity.weekWorkPlan.*;
import com.sunxung.factoring.entity.weekWorkPlan.vo.SearchBusinessProcessingVo;
import com.sunxung.factoring.entity.weekWorkPlan.vo.SearchWeekWorkPlan;
import com.sunxung.factoring.entity.weekWorkPlan.vo.WeeklyMeetingLastWorkPlanBusinessProcessingVo;
import com.sunxung.factoring.mapper.weekWorkPlan.WeekWorkPlanMapper;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.OrgService;
import com.sunxung.factoring.service.sys.PermissionService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowActivityDefinitionService;
import com.sunxung.factoring.service.weekWorkPlan.WeekWorkPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WeekWorkPlanServiceImpl implements WeekWorkPlanService {

    @Autowired
    private WeekWorkPlanMapper weekWorkPlanMapper;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;
    @Autowired
    private FlowActivityDefinitionService flowActivityDefinitionService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public WeekWorkPlanView findWeekWorkPlan(SearchWeekWorkPlan search) {
        WeekWorkPlanView weekWorkPlanView = new WeekWorkPlanView();
        if (null == search.getUserId()) {
            search.setUserId(ThreadLocalUtil.getUser().getId());
        }
        if (null == search.getStartTime()) {
            search.setStartTime(new Date());
            search.setStartTime(DateUtil.addHour(search.getStartTime(), -5));
        }
        // 获取本周工作计划
        Date thisWeekStart = DateUtil.getFirstDayOfWeekClear(search.getStartTime());
        Date thisWeekEnd = DateUtil.getLastDayOfWeekClearMin(search.getStartTime());
        search.setStartTime(thisWeekStart);
        search.setEndTime(thisWeekEnd);
        List<WeekWorkPlan> list = weekWorkPlanMapper.findBySearch(search);
        if (null != list && list.size() > 0) {
            for (WeekWorkPlan plan : list) {
                autoWorkState(plan);
            }
        }
        weekWorkPlanView.setWeekWorkPlanList(list);
        // 获取下周工作计划
        Date nextWeekStart = DateUtil.addWeeks(thisWeekStart, 1);
        Date nextWeekEnd = DateUtil.addWeeks(thisWeekEnd, 1);
        search.setStartTime(nextWeekStart);
        search.setEndTime(nextWeekEnd);
        List<WeekWorkPlan> nextList = weekWorkPlanMapper.findBySearch(search);
        if (null != nextList && nextList.size() > 0) {
            for (WeekWorkPlan plan : nextList) {
                autoWorkState(plan);
            }
        }
        weekWorkPlanView.setNextWeekWorkPlanList(nextList);
        // 封装本周，上周，下周时间
        weekWorkPlanView.setStartTime(DateUtil.dateToString(thisWeekStart, "MM月dd日"));
        weekWorkPlanView.setEndTime(DateUtil.dateToString(thisWeekEnd, "MM月dd日"));
        weekWorkPlanView.setNextStartTime(DateUtil.dateToString(nextWeekStart, "MM月dd日"));
        weekWorkPlanView.setNextEndTime(DateUtil.dateToString(nextWeekEnd, "MM月dd日"));
        weekWorkPlanView.setWeekth(DateUtil.getWeekByDay(thisWeekStart));
        weekWorkPlanView.setLastWeekFirstDay(DateUtil.addWeeks(thisWeekStart, -1));
        weekWorkPlanView.setNextWeekFirstDay(nextWeekStart);
        // 封装当前系统时间所在对应周数
        weekWorkPlanView.setCurrentWeekth(DateUtil.getWeekByDay(DateUtil.addHour(new Date(), -5)));
        // 周一对应的年份
        weekWorkPlanView.setCurrentYear(Integer.parseInt(DateUtil.dateToString(thisWeekStart, "yyyy").toString()));
        return weekWorkPlanView;
    }

    @Override
    @Transactional
    public WeekWorkPlan add(WeekWorkPlan plan) {
        plan.setStartTime(DateUtil.getFirstDayOfWeekClear(plan.getWorkTime()));
        plan.setEndTime(DateUtil.getLastDayOfWeekClearMin(plan.getWorkTime()));
        plan.setWeekth(DateUtil.getWeekByDay(plan.getWorkTime()));
        plan.setUser(ThreadLocalUtil.getUser());
        ValidatorUtil.validator(ValidatorType.ADD, plan);
        weekWorkPlanMapper.add(plan);
        // 判断是否新增的下周继续状态的任务
        Dictionary dic = dictionaryService.get(plan.getWorkState().getId());
        if (dic.getCode().equals(WorkStateDict.ChildEnum.CONTINUE_NEXT_WEEK.getCode())) {
            WeekWorkPlan weekWorkPlan = plan.getNextWeekWorkPlan();
            weekWorkPlan.setLastWorkId(plan.getId());
            weekWorkPlan.setStartTime(DateUtil.getFirstDayOfWeekClear(weekWorkPlan.getWorkTime()));
            weekWorkPlan.setEndTime(DateUtil.getLastDayOfWeekClearMin(weekWorkPlan.getWorkTime()));
            weekWorkPlan.setWeekth(DateUtil.getWeekByDay(weekWorkPlan.getWorkTime()));
            weekWorkPlan.setWorkState(dictionaryService.getByCode(WorkStateDict.ChildEnum.WORKING.getCode()));
            weekWorkPlan.setUser(ThreadLocalUtil.getUser());
            ValidatorUtil.validator(ValidatorType.ADD, weekWorkPlan);
            weekWorkPlanMapper.add(weekWorkPlan);
        }
        return get(plan.getId());
    }

    @Override
    @Transactional
    public WeekWorkPlan update(WeekWorkPlan plan) {
        plan.setStartTime(DateUtil.getFirstDayOfWeekClear(plan.getWorkTime()));
        plan.setEndTime(DateUtil.getLastDayOfWeekClearMin(plan.getWorkTime()));
        plan.setWeekth(DateUtil.getWeekByDay(plan.getWorkTime()));
        ValidatorUtil.validator(ValidatorType.UPDATE, plan);
        // 获取当前时间所在周的第一天
        Date firstDay = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
        // 判断修改的数据是否是本周或者本周后的数据，本周前的数据无法修改
        if (plan.getWorkTime().getTime() < firstDay.getTime()) {
            throw new ValidatorException(CodeUtil.FAIL, "本周前的周工作计划无法修改");
        }
        weekWorkPlanMapper.update(plan);
        // 判断修改的任务状态是否是下周继续状态
        Dictionary dic = dictionaryService.get(plan.getWorkState().getId());
        if (dic.getCode().equals(WorkStateDict.ChildEnum.CONTINUE_NEXT_WEEK.getCode())) {
            WeekWorkPlan nextWeekPlan = plan.getNextWeekWorkPlan();
            nextWeekPlan.setStartTime(DateUtil.getFirstDayOfWeekClear(nextWeekPlan.getWorkTime()));
            nextWeekPlan.setEndTime(DateUtil.getLastDayOfWeekClearMin(nextWeekPlan.getWorkTime()));
            nextWeekPlan.setWeekth(DateUtil.getWeekByDay(nextWeekPlan.getWorkTime()));
            Dictionary nextDic = dictionaryService.getByCode(WorkStateDict.ChildEnum.WORKING.getCode());
            nextWeekPlan.setWorkState(nextDic);
            // 判断是否有ID值
            if (null != nextWeekPlan && null != nextWeekPlan.getId()) {
                ValidatorUtil.validator(ValidatorType.UPDATE, nextWeekPlan);
                weekWorkPlanMapper.update(nextWeekPlan);
            } else {
                nextWeekPlan.setLastWorkId(plan.getId());
                nextWeekPlan.setUser(ThreadLocalUtil.getUser());
                ValidatorUtil.validator(ValidatorType.ADD, nextWeekPlan);
                weekWorkPlanMapper.add(nextWeekPlan);
            }
        } else {
            // 其它状态，则删除之前的下周继续关联的数据
            if (null != plan.getNextWeekWorkPlan() && null != plan.getNextWeekWorkPlan().getId()) {
                delete(plan.getNextWeekWorkPlan().getId());
            }
        }
        return get(plan.getId());
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        if (null == id) {
            throw new ValidatorException(CodeUtil.FAIL, "周工作计划ID不能为空");
        }
        WeekWorkPlan plan = get(id);
        // 获取当前时间所在周的第一天
        Date firstDay = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
        // 判断删除的数据是否是本周或者本周后的数据，本周前的数据无法删除
        if (plan.getWorkTime().getTime() < firstDay.getTime()) {
            throw new ValidatorException(CodeUtil.FAIL, "本周前的周工作计划无法删除");
        }
        boolean flag = weekWorkPlanMapper.delete(id) > 0;
        // 判断是否存在下周继续工作计划,有则删除
        WeekWorkPlan weekWorkPlan = getByLastWeekWorkId(id);
        if (null != weekWorkPlan) {
            flag = weekWorkPlanMapper.delete(weekWorkPlan.getId()) > 0;
        }
        return flag;
    }

    @Override
    public WeekWorkPlan get(Long id) {
        return weekWorkPlanMapper.get(id);
    }

    @Override
    public WeekWorkPlan getByLastWeekWorkId(Long lastWeekWorkId) {
        return weekWorkPlanMapper.getByLastWeekWorkId(lastWeekWorkId);
    }

    public void autoWorkState(WeekWorkPlan weekWorkPlan) {
        if (null != weekWorkPlan && null != weekWorkPlan.getWorkState()) {
            Dictionary dic = dictionaryService.get(weekWorkPlan.getWorkState().getId());
            if (null != dic)
                weekWorkPlan.setWorkState(dic);
        }
    }

    public void autoUser(WeekWorkPlan weekWorkPlan) {
        if (null != weekWorkPlan && null != weekWorkPlan.getUser()) {
            User user = userService.get(weekWorkPlan.getUser().getId());
            if (null != user)
                weekWorkPlan.setUser(user);
        }
    }

    @Override
    public WeekWorkPlan getDetail(Long id) {
        WeekWorkPlan weekWorkPlan = get(id);
        autoWorkState(weekWorkPlan);
        autoUser(weekWorkPlan);
        if (weekWorkPlan.getWorkState().getCode().equals(WorkStateDict.ChildEnum.CONTINUE_NEXT_WEEK.getCode())) {
            WeekWorkPlan nextWeekWorkPlan = getByLastWeekWorkId(id);
            autoWorkState(nextWeekWorkPlan);
            autoUser(nextWeekWorkPlan);
            weekWorkPlan.setNextWeekWorkPlan(nextWeekWorkPlan);
        }
        return weekWorkPlan;
    }

    @Override
    public boolean validatorPlan(WeekWorkPlan plan) {
        WeekWorkPlan weekWorkPlan = weekWorkPlanMapper.getByTitleWorkTime(plan.getTitle(), plan.getWorkTime(),
                ThreadLocalUtil.getUserId());
        if (null != weekWorkPlan) {
            if (null != plan && null != plan.getId()) {
                // 修改
                if (!plan.getId().equals(weekWorkPlan.getId())) {
                    return false;
                }
            } else {
                // 添加
                return false;
            }
        }
        return true;
    }

    @Override
    public List<MonthCalendarWorkPlanView> findCalendarList(SearchWeekWorkPlan search) {
        List<MonthCalendarWorkPlanView> calendarList = new ArrayList<MonthCalendarWorkPlanView>();
        if (null == search.getUserId()) {
            search.setUserId(ThreadLocalUtil.getUser().getId());
        }
        if (null == search.getYearMonth()) {
            search.setYearMonth(DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
        } else {
            search.setYearMonth(search.getYearMonth() + "-01");
        }
        List<WeekWorkPlan> list = weekWorkPlanMapper.findBySearch(search);
        if (null != list && list.size() > 0) {
            for (WeekWorkPlan plan : list) {
                autoWorkState(plan);
                MonthCalendarWorkPlanView view = new MonthCalendarWorkPlanView();
                view.setId(plan.getId());
                view.setTitle(plan.getTitle());
                view.setContent(plan.getWorkContent());
                view.setDesc(plan.getWorkState().getName());
                view.setCalendar(plan.getWorkState().getCode());
                view.setPriority(ConstantConversionUtil.levels.get(plan.getLevel()));
                view.setStart(DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd"));
                view.setEnd(DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd"));
                calendarList.add(view);
            }
        }
        return calendarList;
    }

    @Override
    public List<WeekCalendarWorkPlanView> findWeekList(SearchWeekWorkPlan search) {
        List<WeekCalendarWorkPlanView> weekList = new ArrayList<WeekCalendarWorkPlanView>();
        if (null == search.getUserId()) {
            search.setUserId(ThreadLocalUtil.getUser().getId());
        }
        if (null == search.getStartTime()) {
            Date thisWeekStart = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
            search.setStartTime(thisWeekStart);
        }
        // 处理跨年阶段的周，页面传周的开始时间和结束时间，结束时间存在问题（结束时间的年份统一是周所在年份是不正确的，正确应该是结束时间本身所在年份，现以根据开始时间计算所在周的结束时间解决这问题，不以页面传值为准）
        Date thisWeekEnd = DateUtil.getLastDayOfWeekClearMin(search.getStartTime());
        search.setEndTime(thisWeekEnd);
        search.setWeek("week");
        List<WeekWorkPlan> list = weekWorkPlanMapper.findBySearch(search);
        WeekCalendarWorkPlanView oneWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView twoWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView threeWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView fourWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView fiveWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView sixWeekView = new WeekCalendarWorkPlanView();
        WeekCalendarWorkPlanView seveWeekView = new WeekCalendarWorkPlanView();
        List<WeekCalendarWorkPlanData> oneDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> twoDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> threeDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> fourDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> fiveDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> sixDatas = new ArrayList<WeekCalendarWorkPlanData>();
        List<WeekCalendarWorkPlanData> seveDatas = new ArrayList<WeekCalendarWorkPlanData>();
        String oneWeekDate = "";
        String twoWeekDate = "";
        String threeWeekDate = "";
        String fourWeekDate = "";
        String fiveWeekDate = "";
        String sixWeekDate = "";
        String seveWeekDate = "";
        if (null != list && list.size() > 0) {
            for (WeekWorkPlan plan : list) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(plan.getWorkTime());
                if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 1) {
                    oneWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    oneDatas.add(data);
                } else if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 2) {
                    twoWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    twoDatas.add(data);
                } else if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 3) {
                    threeWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    threeDatas.add(data);
                } else if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 4) {
                    fourWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    fourDatas.add(data);
                } else if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 5) {
                    fiveWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    fiveDatas.add(data);
                } else if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 6) {
                    sixWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    sixDatas.add(data);
                } else {
                    seveWeekDate = DateUtil.dateToString(plan.getWorkTime(), "yyyy-MM-dd");
                    WeekCalendarWorkPlanData data = new WeekCalendarWorkPlanData();
                    autoWeekWorkPlanData(data, plan);
                    seveDatas.add(data);
                }
            }
            autoWeekWorkPlanView(oneWeekView, "周一", oneWeekDate, oneDatas, weekList);
            autoWeekWorkPlanView(twoWeekView, "周二", twoWeekDate, twoDatas, weekList);
            autoWeekWorkPlanView(threeWeekView, "周三", threeWeekDate, threeDatas, weekList);
            autoWeekWorkPlanView(fourWeekView, "周四", fourWeekDate, fourDatas, weekList);
            autoWeekWorkPlanView(fiveWeekView, "周五", fiveWeekDate, fiveDatas, weekList);
            autoWeekWorkPlanView(sixWeekView, "周六", sixWeekDate, sixDatas, weekList);
            autoWeekWorkPlanView(seveWeekView, "周日", seveWeekDate, seveDatas, weekList);
        }
        return weekList;
    }

    public void autoWeekWorkPlanData(WeekCalendarWorkPlanData data, WeekWorkPlan plan) {
        data.setId(plan.getId());
        data.setTitle(plan.getTitle());
        data.setContent(plan.getWorkContent());
        autoWorkState(plan);
        data.setDesc(plan.getWorkState().getName());
        data.setCalendar(plan.getWorkState().getCode());
        data.setPriority(plan.getLevel());
    }

    public void autoWeekWorkPlanView(WeekCalendarWorkPlanView view, String week, String weekDate,
                                     List<WeekCalendarWorkPlanData> datalist, List<WeekCalendarWorkPlanView> weeklist) {
        view.setWeek(week);
        view.setStart(weekDate);
        view.setData(datalist);
        weeklist.add(view);
    }

    @Override
    public List<Weeks> getWeeks(Integer year) {
        List<Weeks> weekList = new ArrayList<Weeks>();
        for (int j = 1; j <= DateUtil.getMaxWeekNumOfYear(year); j++) {
            Weeks week = new Weeks();
            week.setWeek(j);
            week.setStartDate(DateUtil.dateToString(DateUtil.getFirstDayOfOneWeek(year, j), "MM-dd"));
            week.setEndDate(DateUtil.dateToString(DateUtil.getLastDayOfOneWeek(year, j), "MM-dd"));
            weekList.add(week);
        }
        return weekList;
    }

    @Override
    public GridPage<WeekWorkPlanSeeView> findWeekPlanList(SearchWeekWorkPlan search) {
        List<WeekWorkPlanSeeView> list = new ArrayList<WeekWorkPlanSeeView>();
        // if (null != search && null != search.getDepartment()) {
        // Org og = orgService.get(search.getDepartment().getId());
        // search.setDepartment(og);
        // }
        GridPage<User> gp = userService.findByOrgcode(search);
        if (null != gp.getRows() && gp.getRows().size() > 0) {
            for (User us : gp.getRows()) {
                WeekWorkPlanSeeView seeView = new WeekWorkPlanSeeView();
                seeView.setUserId(us.getId());
                seeView.setUserName(us.getName());
                seeView.setMobile(us.getMobile());
                seeView.setTel(us.getTel());
                String orgName = "";
                if (null != us && us.getOrgIdList().size() > 0) {
                    for (Long orgId : us.getOrgIdList()) {
                        orgName += orgService.getOrgRealNameExceptRoot(orgId) + "\t\t";
                    }
                }
                seeView.setDepartment(orgName);
                list.add(seeView);
            }
        }
        return new GridPage<WeekWorkPlanSeeView>(search.getRows(), search.getPage(), gp.getRecords(), list);
    }

    public void getViewUser(SearchWeekWorkPlan search) {
        // 查看多个用户最终结果集
        List<User> usersList = new ArrayList<>();
        // 页面选择的多个用户
        List<User> chooseUsersList = search.getUserList();
        // 页面选择的多个部门
        List<Org> departmentList = search.getDepartmentList();
        // if ((null == chooseUsersList || chooseUsersList.size() < 1)
        // && (null == departmentList || departmentList.size() < 1)) {
        // throw new ValidatorException(CodeUtil.FAIL, "请选择需查询的用户或部门");
        // }
        // 判断当前登录用户是否具有查看周工作计划统计全部人员的权限
        List<Long> permissionIds = permissionService.getPermissionIdByUserId(ThreadLocalUtil.getUser().getId());
        Permission permission = permissionService.getByEname(ConstantConversionUtil.MEETING_SELL_ALL_ENAME);
        if (null != permission && permissionIds.contains(permission.getId())) {
            search.setSellAll(true);
        }
        if (null != chooseUsersList && chooseUsersList.size() > 0) {
            // 去重
            chooseUsersList.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(u -> u.getId()))),
                            ArrayList::new));
            // 判断当前登录用户是否具有查看周工作计划统计全部人员的权限，无权限则需筛选出可查看的用户
            if (null == search.getSellAll()) {
                // 可查看的用户集
                List<Long> viewUserIds = userService.findViewByOrgCode(search);
                // 不可查看的用户ID
                List<User> removeUsers = new ArrayList<>();
                if (null != viewUserIds && viewUserIds.size() > 0) {
                    for (User user : chooseUsersList) {
                        // 选择的用户若不在可查看的用户集中则移除
                        if (!viewUserIds.contains(user.getId()))
                            removeUsers.add(user);
                    }
                }
                chooseUsersList.removeAll(removeUsers);
            }
        }
        // 选择的多个部门下能查看的用户
        List<User> viewUserList = new ArrayList<>();
        if (null != departmentList && departmentList.size() > 0) {
            for (Org department : departmentList) {
                search.setDepartment(department);
                // 根据用户选择的部门查询当前登录用户所能看到的用户
                List<User> userList = userService.findByOrgcodeList(search);
                if (null != userList && userList.size() > 0)
                    viewUserList.addAll(userList);
            }
        }
        // 去重
        viewUserList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(u -> u.getId()))), ArrayList::new));
        // 将选择的多个用户和多个部门下用户添加到用户结果集中
        if (chooseUsersList != null && chooseUsersList.size() > 0) {
            usersList.addAll(chooseUsersList);
        }
        if (viewUserList != null && viewUserList.size() > 0) {
            usersList.addAll(viewUserList);
        }
        // 去重
        usersList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(u -> u.getId()))), ArrayList::new));
        /////////
        // 判断当选择部门后，查询当前登录用户所在部门及下面子部门的用户ID集合，当用户ID集合为空时，表示当前选择的部门下面没有当前登录用户能看见的用户，此时为让SQL查询条件执行并不能查询到数据，故设置用户ID为0（系统中的用户ID是从1递增，不可能为0）添加到集合中
        if (null == usersList || usersList.size() < 1) {
            User user = new User();
            user.setId(0L);
            usersList.add(user);
        } else {
            // 当前用户有可查看的用户，则将可查看用户重新进行排序
            search.setUserList(usersList);
            usersList = userService.orderUserByOrgGradation(search);
        }
        search.setUserList(usersList);
    }

    @Override
    public List<WeeklyMeetingLastWeekPlan> getLastWeekWorkPlanStatistics(SearchWeekWorkPlan search) {
        List<WeeklyMeetingLastWeekPlan> list = new ArrayList<WeeklyMeetingLastWeekPlan>();
        // 每周一的5点之前都查询的是上周计划作为本周计划，故当前时间减去5小时
        Date thisWeekStart = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
        Date thisWeekEnd = DateUtil.getLastDayOfWeekClearMin(DateUtil.addHour(new Date(), -5));
        Date lastWeekStart = DateUtil.addWeeks(thisWeekStart, -1);
        Date lastWeekEnd = DateUtil.addWeeks(thisWeekEnd, -1);
        search.setStartTime(lastWeekStart);
        search.setEndTime(lastWeekEnd);
        // 获取可见用户
        getViewUser(search);
        List<WeekWorkPlan> lastWorks = weekWorkPlanMapper.findLastWeekWorkPlans(search);
        Integer pause = 0; // 暂停
        Integer next = 0; // 下周继续
        Integer finsh = 0; // 完成
        Integer overdue = 0; // 逾期
        Integer stop = 0; // 终止
        if (null != lastWorks && lastWorks.size() > 0) {
            WeeklyMeetingLastWeekPlan pausePlan = new WeeklyMeetingLastWeekPlan();
            WeeklyMeetingLastWeekPlan nextPlan = new WeeklyMeetingLastWeekPlan();
            WeeklyMeetingLastWeekPlan finshPlan = new WeeklyMeetingLastWeekPlan();
            WeeklyMeetingLastWeekPlan overduePlan = new WeeklyMeetingLastWeekPlan();
            WeeklyMeetingLastWeekPlan stopPlan = new WeeklyMeetingLastWeekPlan();
            for (WeekWorkPlan work : lastWorks) {
                autoWorkState(work);
                String state = work.getWorkState().getCode();
                if (WorkStateDict.ChildEnum.PAUSE.getCode().equals(state)) {
                    // 暂停
                    pause++;
                } else if (WorkStateDict.ChildEnum.CONTINUE_NEXT_WEEK.getCode().equals(state)) {
                    // 下周继续
                    next++;
                } else if (WorkStateDict.ChildEnum.FINSH.getCode().equals(state)) {
                    // 完成
                    finsh++;
                } else if (WorkStateDict.ChildEnum.OVERDUE.getCode().equals(state)) {
                    // 逾期
                    overdue++;
                } else if (WorkStateDict.ChildEnum.STOP.getCode().equals(state)) {
                    // 终止
                    stop++;
                }
            }
            pausePlan.setValue(pause);
            pausePlan.setName("暂停");
            pausePlan.setStateId(dictionaryService.getByCode(WorkStateDict.ChildEnum.PAUSE.getCode()).getId());
            nextPlan.setValue(next);
            nextPlan.setName("下周继续");
            nextPlan.setStateId(
                    dictionaryService.getByCode(WorkStateDict.ChildEnum.CONTINUE_NEXT_WEEK.getCode()).getId());
            finshPlan.setValue(finsh);
            finshPlan.setName("完成");
            finshPlan.setStateId(dictionaryService.getByCode(WorkStateDict.ChildEnum.FINSH.getCode()).getId());
            overduePlan.setValue(overdue);
            overduePlan.setName("逾期");
            overduePlan.setStateId(dictionaryService.getByCode(WorkStateDict.ChildEnum.OVERDUE.getCode()).getId());
            stopPlan.setValue(stop);
            stopPlan.setName("终止");
            stopPlan.setStateId(dictionaryService.getByCode(WorkStateDict.ChildEnum.STOP.getCode()).getId());
            String pausePercent = PercentageUtil.convertPercentage(pause.doubleValue() / lastWorks.size());
            String nextPercent = PercentageUtil.convertPercentage(next.doubleValue() / lastWorks.size());
            String finshPercent = PercentageUtil.convertPercentage(finsh.doubleValue() / lastWorks.size());
            String overduePercent = PercentageUtil.convertPercentage(overdue.doubleValue() / lastWorks.size());
            double num = 1;
            double result;
            try {
                result = num - (PercentageUtil.convertDouble(pausePercent).doubleValue()
                        + PercentageUtil.convertDouble(nextPercent).doubleValue()
                        + PercentageUtil.convertDouble(finshPercent).doubleValue()
                        + PercentageUtil.convertDouble(overduePercent).doubleValue());
            } catch (ParseException e) {
                throw new ValidatorException(CodeUtil.FAIL, e.getMessage());
            }
            String stopPercent = PercentageUtil.convertPercentage(result);
            pausePlan.setPercent(pausePercent);
            nextPlan.setPercent(nextPercent);
            finshPlan.setPercent(finshPercent);
            overduePlan.setPercent(overduePercent);
            stopPlan.setPercent(stopPercent);
            list.add(finshPlan);
            list.add(pausePlan);
            list.add(nextPlan);
            list.add(stopPlan);
            list.add(overduePlan);
        }
        return list;
    }

    @Override
    public WeeklyMeetingThisLastWeekPlan findLastWeekWorkPlanList(SearchWeekWorkPlan search) {
        WeeklyMeetingThisLastWeekPlan weekWorkPlan = new WeeklyMeetingThisLastWeekPlan();
        // 每周一的5点之前都查询的是上周计划作为本周计划，故当前时间减去5小时
        Date thisWeekStart = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
        Date thisWeekEnd = DateUtil.getLastDayOfWeekClearMin(DateUtil.addHour(new Date(), -5));
        Date lastWeekStart = DateUtil.addWeeks(thisWeekStart, -1);
        Date lastWeekEnd = DateUtil.addWeeks(thisWeekEnd, -1);
        // 获取上周是一年中的第几周
        Integer lastWeekth = DateUtil.getWeekByDay(lastWeekStart);
        weekWorkPlan.setWeekth(lastWeekth);
        weekWorkPlan.setStartTime(DateUtil.dateToString(lastWeekStart, "MM月dd日"));
        weekWorkPlan.setEndTime(DateUtil.dateToString(lastWeekEnd, "MM月dd日"));
        weekWorkPlan.setYear(Integer.parseInt(DateUtil.dateToString(lastWeekStart, "yyyy").toString()));
        // 获取上周计划
        search.setStartTime(lastWeekStart);
        search.setEndTime(lastWeekEnd);
        // 获取可见用户
        getViewUser(search);
        List<WeekWorkPlan> lastPlans = new ArrayList<WeekWorkPlan>();
        List<WeekWorkPlan> thisPlans = new ArrayList<WeekWorkPlan>();
        if (null != search.getUserList() && search.getUserList().size() > 0) {
            List<User> userList = search.getUserList();
            // 排序：按照部门、人员顺序排序，先将所有人员顺序排列正确，再循环人员依次查询工作计划
            search.setUserList(null);
            // 循环查询用户上周工作计划
            for (User user : userList) {
                search.setUserId(user.getId());
                List<WeekWorkPlan> lasts = weekWorkPlanMapper.findLastWeekWorkPlans(search);
                if (null != lasts && lasts.size() > 0) {
                    for (WeekWorkPlan lastplan : lasts) {
                        autoWorkState(lastplan);
                        autoUser(lastplan);
                        lastPlans.add(lastplan);
                    }
                }
            }
            // 获取本周计划
            search.setStartTime(thisWeekStart);
            search.setEndTime(thisWeekEnd);
            for (User user : userList) {
                search.setUserId(user.getId());
                List<WeekWorkPlan> thiss = weekWorkPlanMapper.findLastWeekWorkPlans(search);
                if (null != thiss && thiss.size() > 0) {
                    for (WeekWorkPlan thisplan : thiss) {
                        autoWorkState(thisplan);
                        autoUser(thisplan);
                        thisPlans.add(thisplan);
                    }
                }
            }
        }
        weekWorkPlan.setLastWeekWorkPlanList(lastPlans);
        weekWorkPlan.setThisWeekWorkPlanList(thisPlans);
        return weekWorkPlan;
    }

    @Override
    public GridPage<WeeklyMeetingLastWorkPlanDetail> findLastWeekPlanDetailList(SearchWeekWorkPlan search) {
        List<WeeklyMeetingLastWorkPlanDetail> planList = new ArrayList<WeeklyMeetingLastWorkPlanDetail>();
        // 每周一的5点之前都查询的是上周计划作为本周计划，故当前时间减去5小时
        Date thisWeekStart = DateUtil.getFirstDayOfWeekClear(DateUtil.addHour(new Date(), -5));
        Date thisWeekEnd = DateUtil.getLastDayOfWeekClearMin(DateUtil.addHour(new Date(), -5));
        Date lastWeekStart = DateUtil.addWeeks(thisWeekStart, -1);
        Date lastWeekEnd = DateUtil.addWeeks(thisWeekEnd, -1);
        search.setStartTime(lastWeekStart);
        search.setEndTime(lastWeekEnd);
        // 判断当前登录用户是否具有查看周工作计划统计全部人员的权限
        List<Long> permissionIds = permissionService.getPermissionIdByUserId(ThreadLocalUtil.getUser().getId());
        Permission permission = permissionService.getByEname(ConstantConversionUtil.MEETING_SELL_ALL_ENAME);
        if (null != permission && permissionIds.contains(permission.getId())) {
            search.setSellAll(true);
        }
        // 根据用户选择的部门查询当前登录用户所能看到的用户
        List<User> userList = userService.findByOrgcodeList(search);
        search.setUserList(userList);
        PageHelper.startPage(search.getPage(), search.getRows()).size();
        List<WeekWorkPlan> list = weekWorkPlanMapper.findLastWeekWorkPlans(search);
        Integer count = weekWorkPlanMapper.countLastWeekWorkPlans(search);
        if (null != list && list.size() > 0) {
            for (WeekWorkPlan plan : list) {
                autoUser(plan);
                autoWorkState(plan);
                WeeklyMeetingLastWorkPlanDetail detail = new WeeklyMeetingLastWorkPlanDetail();
                detail.setWeekWorkPlanId(plan.getId());
                detail.setTitle(plan.getTitle());
                detail.setUserName(plan.getUser().getName());
                detail.setStatus(plan.getWorkState().getName());
                List<Long> orgIds = userService.getOrgIdByUserId(plan.getUser().getId());
                String orgName = "";
                if (null != orgIds && orgIds.size() > 0) {
                    for (Long orgId : orgIds) {
                        orgName += orgService.getOrgRealNameExceptRoot(orgId) + "\t\t";
                    }
                }
                detail.setDepartment(orgName);
                planList.add(detail);
            }
        }
        return new GridPage<WeeklyMeetingLastWorkPlanDetail>(search.getRows(), search.getPage(), count, planList);
    }

    @Override
    public void handleOverdueWork() {
        Dictionary workingState = dictionaryService.getByCode(WorkStateDict.ChildEnum.WORKING.getCode());
        Dictionary overdueState = dictionaryService.getByCode(WorkStateDict.ChildEnum.OVERDUE.getCode());
        List<WeekWorkPlan> works = weekWorkPlanMapper.findWorkingWorkPlanAll(new Date(), workingState.getId());
        if (null != works && works.size() > 0) {
            for (WeekWorkPlan weekWork : works) {
                weekWork.setWorkState(overdueState);
                weekWorkPlanMapper.update(weekWork);
            }
        }
    }

    @Override
    public Date getNowDate() {
        Date startDate = DateUtil.getFirstDayOfWeekClear(new Date());
        Date endDate = DateUtil.addHour(startDate, 5);
        Date nowDate = new Date();
        // 判断当前时间是否在周一0点到5点之间，如果在这个时间段则当前时间减去5小时
        if (nowDate.getTime() >= startDate.getTime() && nowDate.getTime() <= endDate.getTime()) {
            return DateUtil.addHour(nowDate, -5);
        }
        return nowDate;
    }

    @Override
    public Map<String, String> getBusinessModule() {
        Map<String, String> map = new LinkedHashMap<>();
        return map;
    }

    private Map<String, List<Long>> getBusinessProcessingStatistics(SearchBusinessProcessingVo search) {
        Map<String, List<Long>> map = new LinkedHashMap<>();
        if (null != search) {
            setSearchCondition(search);
            // 上周业务进度统计，统计周期：指上周一早上5:00～本周一早上5:00
            // 本周一早上5点
            // Date thisMonday = DateUtil.addHour(DateUtil.getFirstDayOfWeekClear(new Date()), 5);
            // // 上周一早上5点
            // Date lastMonday = DateUtil.addDay(thisMonday, -7);
            //
            // 上周日:23:59:59
            Date thisMonday = DateUtil.addDay(DateUtil.getLastDayOfWeekClear(new Date()), -7);
            // 上周一:00:00:00
            Date lastMonday = DateUtil.getFirstDayOfWeekClear(DateUtil.getFirstDayOfWeek(thisMonday));
            search.setStartTime(lastMonday);
            search.setEndTime(thisMonday);
            search.setAssigneeType(ConstantConversionUtil.PROCESS_TASK);
            // 所有的业务进度的数据
            List<BusinessProcessingLog> businessProcessingList = businessProcessingLogService
                    .findBusinessProgressStatistics(search);
            if (null != businessProcessingList && businessProcessingList.size() > 0) {
                List<Long> allList = businessProcessingList.stream().map(BusinessProcessingLog::getId)
                        .collect(Collectors.toList());
                // 进行中:保理业务已流入当前节点，未提交
                List<Long> processingList = new ArrayList<>();
                businessProcessingList.stream().filter(e -> StringUtil.isEmpty(e.getStatus())).forEach((e) -> {
                    FlowActivityDefinition definition = flowActivityDefinitionService
                            .getMaxTimeLimitByProcDefKeyActKey(e.getBusinessType(), e.getTaskDefKey());
                    // 进行中的
                    if (null != definition) {
                        Float deadline = null;
                        if (definition.getWorkingDay()) {
                            deadline = FlowableUtil.getBusinessDeadlineByWorkingDay(e.getStartTime(),
                                    definition.getTimeLimit(), definition.getWorkingDay());// 工作日时限
                        } else {
                            deadline = FlowableUtil.getBusinessDeadlineByNatureDay(e.getStartTime(),
                                    definition.getTimeLimit(), definition.getWorkingDay());// 自然日时限
                        }
                        if (null == deadline) {
                            processingList.add(e.getId());
                        }
                    }
                });
                // 已完成:保理业务已流入当前节点，已提交但未逾期（提交时：倒计时≧0）；即 overdueDays=null
                List<Long> completedList = businessProcessingList.stream()
                        .filter(e -> StringUtil.isNotEmpty(e.getStatus())).filter(e -> null == e.getOverdueDays())
                        .map(BusinessProcessingLog::getId).collect(Collectors.toList());
                // 逾期中:保理业务已流入当前节点，未提交且已逾期（倒计时<0）；即 overdueDays !=null
                // 逾期的
                List<Long> overdueList = new ArrayList<>();
                businessProcessingList.stream().filter(e -> StringUtil.isEmpty(e.getStatus())).forEach((e) -> {
                    FlowActivityDefinition definition = flowActivityDefinitionService
                            .getMaxTimeLimitByProcDefKeyActKey(e.getBusinessType(), e.getTaskDefKey());
                    // 逾期进行中的
                    if (null != definition) {
                        Float deadline = null;
                        if (definition.getWorkingDay()) {
                            deadline = FlowableUtil.getBusinessDeadlineByWorkingDay(e.getStartTime(),
                                    definition.getTimeLimit(), definition.getWorkingDay());// 工作日时限
                        } else {
                            deadline = FlowableUtil.getBusinessDeadlineByNatureDay(e.getStartTime(),
                                    definition.getTimeLimit(), definition.getWorkingDay());// 自然日时限
                        }
                        if (null != deadline) {
                            if (deadline < 0) {
                                overdueList.add(e.getId());
                                // deadlineStr += "逾期" + Math.abs(deadline)
                                // + (flowActDef.getWorkingDay() ? "个工作日" : "个自然日") + split;
                            }
                        }
                    }
                });
                // 逾期完成：保理业务已流入当前节点，已提交且已逾期（提交时：倒计时<0）；即overdueDays !=null
                List<Long> overdueCompletedList = businessProcessingList.stream()
                        .filter(e -> StringUtil.isNotEmpty(e.getStatus())).filter(e -> null != e.getOverdueDays())
                        .map(BusinessProcessingLog::getId).collect(Collectors.toList());
                map.put("processing", processingList);
                map.put("completed", completedList);
                map.put("overdue", overdueList);
                map.put("overdueCompleted", overdueCompletedList);
                map.put("all", allList);
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> weeklyMeetingLastBusinessProcessingStatistics(SearchBusinessProcessingVo search) {
        Map<String, Object> map = new LinkedHashMap<>();
        Map<String, List<Long>> detailMap = getBusinessProcessingStatistics(search);
        int allNum = 0;
        int processingCount = 0;
        int completedCount = 0;
        int overdueCount = 0;
        int overdueCompletedCount = 0;
        if (null != detailMap && detailMap.size() > 0) {
            allNum = detailMap.get("all").size();
            processingCount = detailMap.get("processing").size();
            completedCount = detailMap.get("completed").size();
            overdueCount = detailMap.get("overdue").size();
            overdueCompletedCount = detailMap.get("overdueCompleted").size();
        }
        map.put("processing", setBusinessProcessingStatistics(processingCount, allNum, "进行中"));
        map.put("completed", setBusinessProcessingStatistics(completedCount, allNum, "已完成"));
        map.put("overdue", setBusinessProcessingStatistics(overdueCount, allNum, "逾期中"));
        map.put("overdueCompleted", setBusinessProcessingStatistics(overdueCompletedCount, allNum, "逾期完成"));
        map.put("all", allNum);
        return map;
    }

    private WeeklyMeetingLastWorkPlanBusinessProcessingStatistics setBusinessProcessingStatistics(Integer num,
                                                                                                  int allNum, String statusName) {
        String completedPercent = null;
        if (allNum == 0) {
            completedPercent = "0%";
        } else {
            completedPercent = PercentageUtil.convertPercentage(num.doubleValue() / allNum);
            if (StringUtil.isNotEmpty(completedPercent)) {
                String ratio = completedPercent.split("%")[0];
                if (StringUtil.isNotEmpty(ratio)) {
                    completedPercent = StringUtil.subZeroAndDot(ratio) + "%";
                }
            }
        }
        WeeklyMeetingLastWorkPlanBusinessProcessingStatistics statistics = new WeeklyMeetingLastWorkPlanBusinessProcessingStatistics(
                statusName, num, completedPercent);
        return statistics;
    }

    private void setSearchCondition(SearchBusinessProcessingVo search) {
        List<Long> newUserIdList = new ArrayList<>();
        if (null != search && null != search.getOrgIdList() && search.getOrgIdList().size() > 0) {
            for (Long orgId : search.getOrgIdList()) {
                Org org = orgService.get(orgId);
                if (null != org) {
                    List<Long> list = orgService.findUserIdByOrgCode(org.getInternalCode());
                    newUserIdList.addAll(list);
                }
            }
        }
        if (null != search && null != search.getUserIdList() && search.getUserIdList().size() > 0) {
            newUserIdList.addAll(search.getUserIdList());
        }
        List<Long> userIdAllList = new ArrayList<>(new HashSet<>(newUserIdList));
        search.setUserIdAllList(userIdAllList);
    }

    @Override
    public GridPage<WeeklyMeetingLastWorkPlanBusinessProcessingVo> weeklyMeetingBusinessProcessingList(
            SearchBusinessProcessingVo search) {
        if (null == search) {
            throw new ValidatorException(CodeUtil.FAIL, "查询条件不能为空");
        }
        // 设置查询某一个状态的条件
        SearchBusinessProcessingVo sh = new SearchBusinessProcessingVo();
        sh.setBusinessProcessingType(search.getBusinessProcessingType());
        sh.setOrgIdList(search.getOrgIdList());
        sh.setUserIdList(search.getUserIdList());
        sh.setBusinessType(search.getBusinessType());
        Map<String, List<Long>> map = getBusinessProcessingStatistics(sh);
        // 分页查询列表的数据
        Page<WeeklyMeetingLastWorkPlanBusinessProcessingVo> page = PageHelper.startPage(search.getPage(),
                search.getRows());
        List<WeeklyMeetingLastWorkPlanBusinessProcessingVo> row = new ArrayList<>();
        if (null != map && map.size() > 0) {
            List<Long> idList = map.get(search.getBusinessProcessingType());
            if (null != idList && idList.size() > 0) {
                search.setBusinessProcessingLogIdList(idList);
                List<BusinessProcessingLog> list = businessProcessingLogService.findBusinessProgressByIds(search);
                if (null != list && list.size() > 0) {
                    for (BusinessProcessingLog log : list) {
                        WeeklyMeetingLastWorkPlanBusinessProcessingVo vo = new WeeklyMeetingLastWorkPlanBusinessProcessingVo();
                        vo.setBusinessProcessingLogId(log.getId());
                        // 人员姓名
                        if (null != log.getAssignee()) {
                            User assign = userService.get(log.getAssignee().getId());
                            vo.setAssigneeName(assign != null ? assign.getName() : "");
                            // 部门
                            StringBuffer sb = new StringBuffer();
                            List<Long> orgIdList = userService.getOrgIdByUserId(assign.getId());
                            if (null != orgIdList && orgIdList.size() > 0) {
                                for (Long orgId : orgIdList) {
                                    sb.append(orgService.getOrgRealNameExceptRoot(orgId));
                                    sb.append("、");
                                }
                            }
                            String str = sb.toString();
                            if (str.contains("、")) {
                                str = str.substring(0, str.length() - 1);
                                vo.setOrgName(str);
                            }
                        }
                        // 业务编号
                        String businessType = log.getBusinessType();
                        Long businessKey = log.getBusnessKey();
                        Project project = (Project) FlowableUtil
                                .getBusinessDateById(businessType + "_" + businessKey);
                        if (null != project) {
                            vo.setBusinessNo(project.getBusinessNumber());
                        }
                        // 处理阶段
                        String processingStage = null;
                        Map<String, String> businessModuleMap = getBusinessModule();
                        if (null != businessModuleMap && businessModuleMap.size() > 0) {
                            String businessTypeName = businessModuleMap.get(businessType);
                            if (StringUtil.isNotEmpty(businessTypeName)) {
                                processingStage = businessTypeName + FlowableUtil.splitChar + log.getTaskName();
                            }
                        }
                        vo.setProcessingStage(processingStage);
                        // 上午、下午开始时间换算
                        String startTime = DateUtil.getDayStringFormat(log.getStartTime());
                        String endTime = DateUtil.getDayStringFormat(log.getEndTime());
                        if (StringUtil.isNotEmpty(startTime)) {
                            if (ConstantUtil.AM_CNAME.equals(DateUtil.getCnameOfAMPM(log.getStartTime()))) {
                                vo.setStartTime(startTime + " " + ConstantUtil.AM_CNAME);
                            } else {
                                vo.setStartTime(startTime + " " + ConstantUtil.PM_CNAME);
                            }
                        }
                        if (StringUtil.isNotEmpty(endTime)) {
                            if (ConstantUtil.AM_CNAME.equals(DateUtil.getCnameOfAMPM(log.getEndTime()))) {
                                vo.setActualCompletedTime(endTime + " " + ConstantUtil.AM_CNAME);
                            } else {
                                vo.setActualCompletedTime(endTime + " " + ConstantUtil.PM_CNAME);
                            }
                        }
                        // 预计完成时间
                        FlowActivityDefinition definition = flowActivityDefinitionService
                                .getMaxTimeLimitByProcDefKeyActKey(log.getBusinessType(), log.getTaskDefKey());
                        if (null != definition && null != definition.getTimeLimit() && definition.getTimeLimit() > 0) {
                            int hours = (int) (definition.getTimeLimit() * 24);
                            Date planCompletTime = DateUtil.addHour(log.getStartTime(), hours);
                            String planCompletTimeStr = DateUtil.getDayStringFormat(planCompletTime);
                            if (StringUtil.isNotEmpty(planCompletTimeStr)) {
                                if (ConstantUtil.AM_CNAME.equals(DateUtil.getCnameOfAMPM(planCompletTime))) {
                                    vo.setPlanCompletedTime(planCompletTimeStr + " " + ConstantUtil.AM_CNAME);
                                } else {
                                    vo.setPlanCompletedTime(planCompletTimeStr + " " + ConstantUtil.PM_CNAME);
                                }
                            }
                        }
                        // 逾期时间设置
                        if (search.getBusinessProcessingType().equals("overdue")) {
                            // 逾期进行中的
                            if (null != definition) {
                                Float deadline = null;
                                if (definition.getWorkingDay()) {
                                    deadline = FlowableUtil.getBusinessDeadlineByWorkingDay(log.getStartTime(),
                                            definition.getTimeLimit(), definition.getWorkingDay());// 工作日时限
                                } else {
                                    deadline = FlowableUtil.getBusinessDeadlineByNatureDay(log.getStartTime(),
                                            definition.getTimeLimit(), definition.getWorkingDay());// 自然日时限
                                }
                                String deadlineStr = "";
                                if (null != deadline) {
                                    if (deadline < 0) {
                                        deadlineStr = "逾期" + Math.abs(deadline)
                                                + (definition.getWorkingDay() ? "个工作日" : "个自然日");
                                    } else {
                                        deadlineStr = deadline + (definition.getWorkingDay() ? "个工作日" : "个自然日");
                                    }
                                }
                                vo.setOverdue(deadlineStr);
                            }
                        } else {
                            // 逾期（完成的情况）
                            if (null != log.getOverdueDays() && log.getOverdueDays() > 0) {
                                vo.setOverdue("逾期" + log.getOverdueDays() + (log.getWorkingDay() ? "个工作日" : "个自然日"));
                            }
                        }
                        row.add(vo);
                    }
                }
            }
        }
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), row);
    }
}
