class ArrangementManagementServiceImpl implements ArrangementManagementService {

    @Override
    public CommonResult insertArrangement(ArrangementParam arrangementParam){
        Boolean toInsert = true;
        toInsertArrangements = new ArrayList<>();//待插入数据库排班结果
        Date startDate = Date.valueOf(arrangementParam.getStartDate());
        Date endDate = Date.valueOf(arrangementParam.getEndDate());
        Integer departmentId = arrangementParam.getDepartmentId();
        Integer arrangementRuleId = arrangementParam.getId();//排班规则id

        //参数检验
        if(startDate.compareTo(endDate) > 0)
            return CommonResult.fail(ResultCode.E_809);
        if(arrangementRuleId == null)
            return CommonResult.fail(ResultCode.E_801);//排班规则为空
        //已存在排班结果
        if(0!= arrangementMapper.listByDepartmentIdAndDatePeriod(startDate, endDate, departmentId).size()){
            return CommonResult.fail(ResultCode.E_810);
        }

        //时间段内现有所有排班有效信息
        List<Arrangement> arrangements = arrangementMapper.listByUserIdAndDatePeriod(startDate, endDate);

        //对时间范围内每一天排班
        Date today = startDate;
        List<ArrangementConflictParam> conflict = new ArrayList<>();
        while(today.compareTo(endDate) <= 0){
            //生成一天排班
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(today);
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            conflict = saveArrangement(today, week, departmentId, arrangementRuleId, arrangements, conflict, toInsert,
                                    toInsertArrangements);
            if(0 != conflict.size())
                toInsert = false;
            // 下一天
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            java.util.Date tomorrow = calendar.getTime();
            today = new Date(tomorrow.getTime());
        }
        // 确定为可插入，最后一起插入
        if(toInsert.equals(true)){
            for(Arrangement arrangement : toInsertArrangements)
                arrangementMapper.insertSelective(arrangement);
        }
        if(0 != conflict.size())
            return CommonResult.fail(ResultCode.E_808, conflict);
        else
            return CommonResult.success("OK");
    }

}