package com.boman.web.core.service.attendance;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.redis.RedisKey;
import com.boman.domain.GenTable;
import com.boman.domain.GenTableColumn;
import com.boman.domain.constant.FormDataConstant;
import com.boman.domain.dto.*;
import com.boman.web.core.mapper.AttendanceMapper;
import com.boman.web.core.mapper.StandardlyMapper;
import com.boman.web.core.service.TableServiceCmdService;
import com.boman.web.core.service.attendance.rules.AttendanceRulesService;
import com.boman.web.core.service.common.ICommonService;
import com.boman.web.core.service.select.IBaseSelectService;
import com.boman.web.core.utils.AuthUtils;
import com.boman.web.core.utils.JSONObjectUtils;
import com.google.common.collect.Lists;
import javafx.scene.control.Tab;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.boman.common.core.utils.DateUtils.YYYY_MM_DD_HH_MM;
import static com.boman.common.core.utils.DateUtils.dateTimeNow;
import static com.boman.common.core.utils.number.NumberUtils.gtZero;
import static com.boman.common.core.utils.obj.ObjectUtils.*;
import static com.boman.domain.constant.AttendanceConst.*;
import static com.boman.domain.constant.AttendanceRulesConst.*;
import static com.boman.domain.constant.FormDataConstant.CONDITION;
import static com.boman.domain.constant.FormDataConstant.PAGE_ROWS;
import static com.boman.domain.constant.LeaveConst.TABLE_NAME;
import static com.boman.web.core.utils.ColumnUtils.withoutHrReturnColumnNames;
import static com.boman.web.core.utils.HandlerFormDataUtils.handleNullColumnValue;

/**
 * @author shiqian
 * @date 2021年06月03日 15:45
 **/
@Service
public class AttendanceServiceImpl implements AttendanceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AttendanceServiceImpl.class);

    @Resource
    private ICommonService commonService;
    @Resource
    private AttendanceRulesService rulesService;
    @Resource
    private TableServiceCmdService cmdService;
    @Resource
    private IBaseSelectService selectService;
    @Autowired
    private StandardlyMapper standardlyMapper;
    @Autowired
    private AttendanceMapper attendanceMapper;

    /**
     * 功能描述: 根据tableName和userId查找当月考勤
     *
     * @param tableName tableName
     * @param userId    userId
     * @return java.util.List<com.alibaba.fastjson.JSONObject>
     */
    private List<JSONObject> listByUserId(String tableName, Long userId) {
        requireNonNull(tableName, "tableName is empty");
        requireNonNull(userId, "userId is empty");
        List<String> days = DateUtils.getMonthDays();
        JSONObject map = new JSONObject(2);
        map.put(ATTENDANCE_USER_ID, userId);
        map.put(ATTENDANCE_TABLE_TODAYTIME, days);
        return commonService.getByMap(tableName, map);
    }

    /**
     * 手机端考勤记录页面
     * 功能描述: 根据tableName和userId查找当月考勤
     *
     * @param tableName tableName
     * @param userId    userId
     * @return java.util.List<com.alibaba.fastjson.JSONObject>
     */
    @Override
    public AjaxResult attendanceRecord(String tableName, Long userId) {
        Map<String, Object> mapObj = new HashMap<>(4);
        List<JSONObject> byMap = listByUserId(tableName, userId);
        //异常的时间
        List<String> dateListErr = new ArrayList<>(byMap.size());
        List<String> dateList = new ArrayList<>(byMap.size());
        if (isEmpty(byMap)) {
            mapObj.put("leave", 0);
            mapObj.put("late", 0);
            mapObj.put("leaveOr", 0);
            mapObj.put("abnormal", 0);
            mapObj.put("dateList", dateList);
            mapObj.put("dateListErr", dateListErr);
            return AjaxResult.success(mapObj);
        }
        //  早退        迟到      请假         异常
        int leave = 0, late = 0, leaveOr = 0, abnormal = 0;
        for (JSONObject jsonObject : byMap) {
            if (ObjectUtils.isNotEmpty(jsonObject.get("attendance_table_leave")) && "Y".equals(String.valueOf(jsonObject.get("attendance_table_leave")))) {
                leave++;
            }

            if (ObjectUtils.isNotEmpty(jsonObject.get("attendance_table_late")) && "Y".equals(String.valueOf(jsonObject.get("attendance_table_late")))) {
                late++;
            }

            if (ObjectUtils.isNotEmpty(jsonObject.get("attendance_table_leave_or")) && "Y".equals(String.valueOf(jsonObject.get("attendance_table_leave_or")))) {
                leaveOr++;
            }
            //异常
            if (ObjectUtils.isNotEmpty(jsonObject.get("attendance_table_judge")) && "Y".equals(String.valueOf(jsonObject.get("attendance_table_judge")))) {
                abnormal++;
                if (ObjectUtils.isNotEmpty(jsonObject.get("attendance_table_todaytime"))) {
                    dateListErr.add(jsonObject.getString("attendance_table_todaytime"));
                }
            }else {
                dateList.add(jsonObject.getString("attendance_table_todaytime"));
            }
        }
        mapObj.put("leave", leave);
        mapObj.put("late", late);
        mapObj.put("leaveOr", leaveOr);
        mapObj.put("abnormal", abnormal);
        mapObj.put("dateList", dateList);
        mapObj.put("dateListErr", dateListErr);
        return AjaxResult.success(mapObj);
    }


    /**
     * 根据tableName和userId查找当月考勤详细记录
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult detailedRecord(FormDataDto dto) {
        // 查询条件
        JSONObject condition = ifNullSetEmpty(dto.getFixedData().getJSONObject(CONDITION));
        String tableName = dto.getTable();
        GenTable genTable = cmdService.getTableFromRedisByTableName(RedisKey.TABLE_INFO, dto.getTable());
        List<GenTableColumn> columns = genTable.getColumns();
        JSONObject packCondition = ifNullSetEmpty(selectService.packColCondition(columns, condition));
        int total = selectService.countByCondition(tableName, condition, packCondition);
        JSONObject result = new JSONObject();
        result.put(FormDataConstant.PAGE_TOTAL, total);
        if (total <= 0) {
            result.put(FormDataConstant.PAGE_ROWS, null);
            return AjaxResult.success(result);
        }
        List<String> showData = withoutHrReturnColumnNames(columns);
        List<JSONObject> rows = selectService.selectByCondition(tableName, condition, packCondition, showData, dto);
        // 查询时为null的列不显示的处理
        handleNullColumnValue(rows, showData);

        List<Map<String, Object>> detailedRecordList = new ArrayList<>();
        if (isEmpty(rows)) {
            result.put(FormDataConstant.PAGE_ROWS, rows);
            return AjaxResult.success(result);
        }

        for (JSONObject jsonObject : rows) {
            Map<String, Object> map = new HashMap<>(5);
            String attendanceTableWork = jsonObject.get("attendance_table_work").toString();
            String attendanceTableOffWork = jsonObject.get("attendance_table_offwork").toString();
            String attendanceTableWorkPm = jsonObject.get("attendance_table_work_pm").toString();
            String attendanceTableOffWorkPm = jsonObject.get("attendance_table_offwork_pm").toString();
            map.put("attendanceTableWork", "未打卡");
            map.put("attendanceTableOffWork", "未打卡");
            map.put("attendanceTableWorkPm", "未打卡");
            map.put("attendanceTableOffWorkPm", "未打卡");
            if (isNotEmpty(attendanceTableWork)) {
                map.put("attendanceTableWork", DateUtils.dateToMMdd(DateUtils.parseDate(attendanceTableWork.substring(0,attendanceTableWork.length()-2))) + " 已打卡");
            }
            if (isNotEmpty(attendanceTableOffWork)) {
                map.put("attendanceTableOffWork", DateUtils.dateToMMdd(DateUtils.parseDate(attendanceTableOffWork.substring(0,attendanceTableOffWork.length()-2))) + " 已打卡");
            }
            if (isNotEmpty(attendanceTableWorkPm)) {
                map.put("attendanceTableWorkPm", DateUtils.dateToMMdd(DateUtils.parseDate(attendanceTableWorkPm.substring(0,attendanceTableWorkPm.length()-2))) + " 已打卡");
            }
            if (isNotEmpty(attendanceTableOffWorkPm)) {
                map.put("attendanceTableOffWorkPm", DateUtils.dateToMMdd(DateUtils.parseDate(attendanceTableOffWorkPm.substring(0,attendanceTableOffWorkPm.length()-2))) + " 已打卡");
            }

            map.put("dateTime", jsonObject.get("attendance_table_week") + " " + jsonObject.get("attendance_table_todaytime"));
            detailedRecordList.add(map);
        }

        result.put(PAGE_ROWS, detailedRecordList);
        return AjaxResult.success(result);
    }

    /**
     * 功能描述: 显示是上班打卡还是下班打卡
     *
     * @param tableName tableName
     * @param userName  userName
     * @return java.lang.String
     */
    @Override
    public String showAttendanceType(String tableName, String userName) {
        requireNonNull(tableName, "tableName is empty");
        requireNonNull(userName, "userName is empty");
        JSONObject attendanceTableUsername = commonService.getOneByMap(tableName, JSONObjectUtils.putValue("attendance_table_username", userName, ATTENDANCE_TABLE_TODAYTIME, DateUtils.getDate()));
        GregorianCalendar ca = new GregorianCalendar();
        int result = ca.get(GregorianCalendar.AM_PM);
        if (0 == result) {
            //上午上班打卡
            return (MapUtils.isEmpty(attendanceTableUsername) || isEmpty(attendanceTableUsername.getString(ATTENDANCE_TABLE_WORK)))? GO_TO_WORK : GO_OFF_WORK;
        } else {
            if (MapUtils.isEmpty(attendanceTableUsername) || isEmpty(attendanceTableUsername.getString(ATTENDANCE_TABLE_WORK_PM))) {
                return GO_TO_WORK_PM;
            } else {
                return GO_OFF_WORK_PM;
            }
        }
    }

    @Override
    public List<JSONObject> checkAttendanceType(String tableName, String userName) {
        requireNonNull(tableName, "tableName is empty");
        requireNonNull(userName, "userName is empty");

        String yyyyMmDd = DateUtils.getYyyyMmDd();
        JSONObject map = new JSONObject(2);
        map.put(ATTENDANCE_USER_NAME, userName);
        map.put(ATTENDANCE_TABLE_WORK, yyyyMmDd);
        return commonService.getByMap(tableName, map);
    }

    /**
     * 功能描述: 查询该人的一天打卡时间
     *
     * @param tableName tableName
     * @param userName  userName
     * @return com.boman.domain.dto.AjaxResult
     */
    @Override
    public JSONObject attendanceTime(String tableName, String userName) {
        requireNonNull(tableName, "tableName is empty");
        requireNonNull(userName, "userName is empty");

        JSONObject result = new JSONObject();
        List<JSONObject> attendanceList = listByUserNameAndTime(tableName, userName, DateUtils.getDate());
        // 今天 还未打卡
        if (isEmpty(attendanceList)) {
            result.put(GO_TO_WORK, null);
            result.put(GO_OFF_WORK, null);
            result.put(GO_TO_WORK_PM, null);
            result.put(GO_OFF_WORK_PM, null);
            return result;
        }

        attendanceList = attendanceList.stream()
                .sorted(Comparator.comparing(json -> json.getTimestamp(ATTENDANCE_TABLE_CREATE_TIME)))
                .collect(Collectors.toList());

        Timestamp goToWorkTime = null;
        Timestamp goOffWorkTime = null;
        Timestamp goToWorkTimePm = null;
        Timestamp goOffWorkTimePm = null;
        for (JSONObject attendance : attendanceList) {
            if (isNotEmpty(attendance.get(ATTENDANCE_TABLE_WORK))) {
                goToWorkTime = attendance.getTimestamp(ATTENDANCE_TABLE_WORK);
            }
            if (isNotEmpty(attendance.get(ATTENDANCE_TABLE_OFFWORK))) {
                goOffWorkTime = attendance.getTimestamp(ATTENDANCE_TABLE_OFFWORK);
            }
            if (isNotEmpty(attendance.get(ATTENDANCE_TABLE_WORK_PM))) {
                goToWorkTimePm = attendance.getTimestamp(ATTENDANCE_TABLE_WORK_PM);
            }
            if (isNotEmpty(attendance.get(ATTENDANCE_TABLE_OFFWORK_PM))) {
                goOffWorkTimePm = attendance.getTimestamp(ATTENDANCE_TABLE_OFFWORK_PM);
            }
        }
        result.put(GO_TO_WORK, goToWorkTime == null ? null : goToWorkTime.toString());
        result.put(GO_OFF_WORK, goOffWorkTime == null ? null : goOffWorkTime.toString());
        result.put(GO_TO_WORK_PM, goToWorkTimePm == null ? null : goToWorkTimePm.toString());
        result.put(GO_OFF_WORK_PM, goOffWorkTimePm == null ? null : goOffWorkTimePm.toString());
        return result;
    }

    /**
     * 功能描述: 打卡
     *
     * @param dto dto
     * @return com.alibaba.fastjson.JSONObject
     */
    @Override
    public JSONObject clockOn(ClockOnDto dto) {
        int type = requireNonNull(dto.getType(), "clockOn type is empty");
        String tableName = requireNonNull(dto.getTableName(), "clockOn tableName is empty");

        JSONObject commitData = new JSONObject();
        Long deptId = AuthUtils.getLoginUser().getSysUser().getDeptId();
        commitData.put(ATTENDANCE_USER_NAME, SecurityUtils.getUsername());
        commitData.put(ATTENDANCE_TABLE_TODAYTIME, DateUtils.getDate());
        commitData.put(ATTENDANCE_TABLE_LONGITUDE, dto.getLongitude());
        commitData.put(ATTENDANCE_TABLE_LATITUDE, dto.getLatitude());
        commitData.put(ATTENDANCE_USER_ID, SecurityUtils.getUserId());
        commitData.put(ATTENDANCE_DEPT_ID, deptId);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        // 是否请假
        if (checkIsLeave()) {
            //
        }

        //获取考勤规定时间
        JSONObject rules = rulesService.listByDeptId(deptId);
        //规定上午上班时间
        String attendanceRulesStartTime = rules.get("attendance_rules_start_time").toString();
        //规定下午上班时间
        String attendanceRulesEndTime = rules.get("attendance_rules_end_time").toString();
        //规定的下午上班时间
        String attendanceRulesStartTimePm = rules.get("attendance_rules_start_time_pm").toString();
        //规定的下午下班时间
        String attendanceRulesEndTimePm = rules.get("attendance_rules_end_time_pm").toString();
        UpdateDto updateDto = new UpdateDto();
        //如果是更新
        JSONObject commitDataUpdate = new JSONObject();
        if (GO_TO_WORK_TYPE == type) {
            if (checkIsLate(currentTime, type)) {
                //判断迟到多久
                Date date = DateUtils.strToDate(attendanceRulesStartTime, "yyyy-MM-dd HH:mm:ss");
                String datePoor = DateUtils.getDatePoor(currentTime, date);
                commitData.put(LATE_TIME, datePoor);
                commitData.put(ATTENDANCE_ABNORMAL, Y);
                commitData.put(ATTENDANCE_TABLE_LATE, Y);
            }
            commitData.put(ATTENDANCE_TABLE_WORK, currentTime);
            commitDataUpdate.put(ATTENDANCE_TABLE_WORK, currentTime);
        } else if (GO_OFF_WORK_TYPE == type) {
            if (checkIsLeaveEarly(currentTime, type)){
                Date date = DateUtils.strToDate(attendanceRulesEndTime, "yyyy-MM-dd HH:mm:ss");
                String datePoor = DateUtils.getDatePoor(currentTime, date);
                commitData.put(LEAVE_EARLY_TIME, datePoor);
                commitData.put(ATTENDANCE_ABNORMAL, Y);
                commitData.put(ATTENDANCE_TABLE_LATE, Y);
            }
            commitData.put(ATTENDANCE_TABLE_OFFWORK, currentTime);
            commitDataUpdate.put(ATTENDANCE_TABLE_OFFWORK, currentTime);
        } else if (GO_TO_WORK_TYPE_PM == type) {
            if (checkIsLate(currentTime, type)) {
                Date date = DateUtils.strToDate(attendanceRulesStartTimePm, "yyyy-MM-dd HH:mm:ss");
                String datePoor = DateUtils.getDatePoor(currentTime, date);
                commitData.put(LATE_TIME_PM, datePoor);
                commitData.put(ATTENDANCE_ABNORMAL, Y);
                commitData.put(ATTENDANCE_TABLE_LATE, Y);
            }
            commitData.put(ATTENDANCE_TABLE_WORK_PM, currentTime);
            commitDataUpdate.put(ATTENDANCE_TABLE_WORK_PM, currentTime);
        } else if (GO_OFF_WORK_TYPE_PM == type) {
            if (checkIsLeaveEarly(currentTime, type)){
                Date date = DateUtils.strToDate(attendanceRulesEndTimePm, "yyyy-MM-dd HH:mm:ss");
                String datePoor = DateUtils.getDatePoor(currentTime, date);
                commitData.put(LEAVE_EARLY_TIME_PM, datePoor);
                commitData.put(ATTENDANCE_ABNORMAL, Y);
                commitData.put(ATTENDANCE_TABLE_LATE, Y);
            }
            commitData.put(ATTENDANCE_TABLE_OFFWORK_PM, currentTime);
            commitDataUpdate.put(ATTENDANCE_TABLE_OFFWORK_PM, currentTime);
        }
        JSONObject jsonObject = JSONObjectUtils.putValue(ATTENDANCE_USER_NAME, SecurityUtils.getUsername(), ATTENDANCE_TABLE_TODAYTIME, DateUtils.getDate());
        JSONObject oneByMap = commonService.getOneByMap(tableName, jsonObject);
        if (MapUtils.isEmpty(oneByMap)) {
            saveClockOn(tableName, commitData);
        } else {
            Long id = oneByMap.getLong("id");
            updateDto.setCommitData(commitDataUpdate);
            JSONObject condition = JSONObjectUtils.putValue("id", id);
            updateDto.setTableName(tableName);
            updateDto.setCondition(condition);
            commonService.update(updateDto);
        }
        return commitData;
    }

    /**
     * 按月统计人员考勤信息
     *
     * @param map
     * @return
     */
    @Override
    public AjaxResult statisticsByMonth(Map<String, Object> map) {
        String date = String.valueOf(map.get("date"));
        String name = String.valueOf(map.get("name"));
        int page = ((Integer) map.get("page"));
        int pageSize = ((Integer) map.get("pageSize"));
        int pageNo = (page - 1) * pageSize;
        if ("null".equals(name)) {
            name = "";
        }
        List<JSONObject> jsonObjects = standardlyMapper.statisticsByMonth(date, name, pageNo, pageSize);
        return AjaxResult.success(jsonObjects);
    }

    /**
     * 查询用户某月的上班打卡时间
     *
     * @param date
     * @param userId
     * @return
     */
    @Override
    public AjaxResult findDate(String date, Long userId) {
        //定义返回值
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //根据日期 年-月和用户id查询用户当月打卡记录
        List<JSONObject> jsonObjects = standardlyMapper.findDate(date, userId);
        //获取某月的所有日期
        List<String> monthEveryDays = DateUtils.getMonthEveryDays(date);
        String workDaKa = " 上午上班打卡";
        String workDaKaPm = " 下午上班打卡";
        String offDaKa = " 上午下班打卡";
        String offDaKaPm = " 下午下班打卡";
        String onDaKa = " 未打卡";
        //给返回值中添加所有日期数据
        if (monthEveryDays != null && monthEveryDays.size() > 0) {
            for (String monthEveryDay : monthEveryDays) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("date", monthEveryDay);
                jsonObject.put("attendanceTableWork", onDaKa);
                jsonObject.put("attendanceTableOffWork", onDaKa);
                jsonObject.put("attendanceTableWorkPm", onDaKa);
                jsonObject.put("attendanceTableOffWorkPm", onDaKa);
                jsonObjectList.add(jsonObject);
            }
            if (jsonObjects.size() > 0) {
                for (JSONObject jsonObjectDay : jsonObjectList) {
                    String dateDay = String.valueOf(jsonObjectDay.get("date"));
                    for (JSONObject jsonObject : jsonObjects) {
                        Object attendanceTableWork = jsonObject.get("attendanceTableWork");
                        if (ObjectUtils.isNotEmpty(attendanceTableWork)) {
                            String[] s = String.valueOf(attendanceTableWork).split(" ");
                            if (s[0].equals(dateDay)) {
                                jsonObjectDay.put("attendanceTableWork", s[1] + workDaKa);
                            }
                        }
                        Object attendanceTableOffWork = jsonObject.get("attendanceTableOffWork");
                        if (ObjectUtils.isNotEmpty(attendanceTableOffWork)) {
                            String[] s = String.valueOf(attendanceTableOffWork).split(" ");
                            if (s[0].equals(dateDay)) {
                                jsonObjectDay.put("attendanceTableOffWork", s[1] + offDaKa);
                            }
                        }
                        Object attendanceTableWorkPm = jsonObject.get("attendanceTableWorkPm");
                        if (ObjectUtils.isNotEmpty(attendanceTableWorkPm)) {
                            String[] s = String.valueOf(attendanceTableWorkPm).split(" ");
                            if (s[0].equals(dateDay)) {
                                jsonObjectDay.put("attendanceTableWorkPm", s[1] + workDaKaPm);
                            }
                        }
                        Object attendanceTableOffWorkPm = jsonObject.get("attendanceTableOffWorkPm");
                        if (ObjectUtils.isNotEmpty(attendanceTableOffWorkPm)) {
                            String[] s = String.valueOf(attendanceTableOffWorkPm).split(" ");
                            if (s[0].equals(dateDay)) {
                                jsonObjectDay.put("attendanceTableOffWorkPm", s[1] + offDaKaPm);
                            }
                        }
                    }
                }
            }
        }

        return AjaxResult.success(jsonObjectList);
    }

    /**
     * 请假通过后,修改考勤表对应时间的是否请假
     * @param dto
     * {
     *     "table": "attendance_table",
     *     "fixedData": {
     *         "condition": {
     *             "user_id": 133,
     *             "user_name": 姓名,
     *             "dept_id": 133,
     *             "leavefrom_start_time": "2021-08-03 13:14:23",
     *             "leavefrom_end_time": "2021-08-06 13:14:23"
     *         }
     *     }
     * }
     * @return
     */
    @Override
    public AjaxResult updateAttendance(FormDataDto dto) {
        JSONObject condition = ifNullSetEmpty(dto.getFixedData().getJSONObject(CONDITION));
        //表名
        String tableName = dto.getTableName();
        //请假开始时间
        String leaveFromStartTime = condition.get("leavefrom_start_time").toString();
        //请假结束时间
        String leaveFromEndTime = condition.get("leavefrom_end_time").toString();
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(leaveFromStartTime, ftf);
        LocalDate endDate = LocalDate.parse(leaveFromEndTime, ftf);
        List<LocalDate> datesBetween = DateUtils.getDatesBetween(startDate, endDate);
        List<String> dateTime = new ArrayList<>();
        for (LocalDate localDate : datesBetween) {
            dateTime.add(localDate.toString());
        }
        JSONObject conditionSelect = new JSONObject();
        //需要ATTENDANCE_TABLE_TODAYTIME字段是查询可见
        condition.put(ATTENDANCE_TABLE_TODAYTIME,dateTime);
        condition.put(IS_DEL,"N");
        //查询考勤表中是否有对应日期的数据
        List<JSONObject> byMap = commonService.getByMap(tableName, conditionSelect);
        List<String> dateTimeUser = new ArrayList<>();
        if(isNotEmpty(byMap)){
            //如果不为空说明当前日期有考勤记录,直接修改状态后更新
            for (JSONObject jsonObject : byMap) {
                Long id = Long.parseLong(jsonObject.get("id").toString());
                UpdateDto uto = new UpdateDto();
                uto.setTableName(tableName);
                uto.setCondition(JSONObjectUtils.putValue("id",id));
                uto.setCommitData(JSONObjectUtils.putValue(ATTENDANCE_TABLE_LEAVE_OR,"Y"));
                commonService.update(uto);
                dateTimeUser.add(jsonObject.get(ATTENDANCE_TABLE_TODAYTIME).toString());
            }
        }
        if (isNotEmpty(dateTimeUser)){
            dateTime.removeAll(dateTimeUser);
        }

        for (String date : dateTime) {
            JSONObject commitData = new JSONObject();
            commitData.put(ATTENDANCE_USER_NAME,condition.get("user_name"));
            commitData.put(ATTENDANCE_USER_ID, condition.get("user_id"));
            commitData.put(ATTENDANCE_DEPT_ID,condition.get("dept_id"));
            commitData.put(ATTENDANCE_TABLE_TODAYTIME,date);
            commitData.put(ATTENDANCE_TABLE_CREATE_TIME,DateUtils.getNowDate());
            commitData.put(ATTENDANCE_TABLE_CREATE_BY,"admin");
            commitData.put(ATTENDANCE_TABLE_LEAVE_OR,"Y");
            FormDataDto fto = new FormDataDto();
            fto.setObjId(-1L);
            fto.setTable(tableName);
            fto.setFixedData(commitData);
            cmdService.objectSave(fto);
        }
        return AjaxResult.success();
    }

    /**
     * 功能描述: 保存打卡信息
     *
     * @param tableName  tableName
     * @param commitData commitData
     * @return boolean
     */
    private boolean saveClockOn(String tableName, JSONObject commitData) {
        FormDataDto dto = new FormDataDto();
        dto.setObjId(-1L);
        dto.setTable(tableName);
        dto.setFixedData(commitData);
        AjaxResult ajaxResult = cmdService.objectSave(dto);
        return AjaxResult.checkSuccess(ajaxResult);
    }

    /**
     * 功能描述: 是否迟到
     *
     * @param arrivalTime 上班打卡时间
     * @return boolean
     */
    private boolean checkIsLate(Timestamp arrivalTime, int type) {
        JSONObject rule = rulesService.listByDeptId(AuthUtils.getLoginUser().getSysUser().getDeptId());
        String hourMi = "";
        if (GO_TO_WORK_TYPE == type) {
            hourMi = rule.getString(ATTENDANCE_RULES_START_TIME);
        }
        if (GO_TO_WORK_TYPE_PM == type) {
            hourMi = rule.getString(ATTENDANCE_RULES_START_TIME_PM);
        }
        String yearMonth = DateUtils.getDate();
        String ruleStartTime = yearMonth + " " + hourMi;
        Date date = DateUtils.strToDate(ruleStartTime, YYYY_MM_DD_HH_MM);
        return arrivalTime.after(date);
    }

    /**
     * 功能描述: 是否早退
     *
     * @param leaveTime 下班打卡时间
     * @return boolean
     */
    private boolean checkIsLeaveEarly(Timestamp leaveTime,int type) {
        JSONObject rule = rulesService.listByDeptId(AuthUtils.getLoginUser().getSysUser().getDeptId());
        //判断上午下班时间
        if (GO_OFF_WORK_TYPE == type) {
            Timestamp ruleEndTime = rule.getTimestamp(ATTENDANCE_RULES_END_TIME);
            return leaveTime.before(ruleEndTime);
        }else if (GO_OFF_WORK_TYPE_PM == type) {
            //判断下午下班时间
            Timestamp ruleEndTimePm = rule.getTimestamp(ATTENDANCE_RULES_END_TIME_PM);
            return leaveTime.before(ruleEndTimePm);
        }
        return false;
    }


    private boolean checkIsLeave() {


        return true;
    }

    /**
     * 功能描述: 根据username和time查找
     *
     * @param tableName tableName
     * @param userName  userName
     * @param time      time
     * @return java.util.List<com.alibaba.fastjson.JSONObject>
     */
    private List<JSONObject> listByUserNameAndTime(String tableName, String userName, String time) {
        JSONObject condition = new JSONObject(2);
        condition.put(ATTENDANCE_USER_NAME, userName);
        condition.put(ATTENDANCE_TABLE_TODAYTIME, time);
        return commonService.getByMap(tableName, condition);
    }

}
