package com.sundot.airport.attendance.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.sundot.airport.attendance.domain.AttendancePostRecord;
import com.sundot.airport.attendance.mapper.AttendancePostRecordMapper;
import com.sundot.airport.attendance.service.IAttendancePostRecordService;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.dto.AttendanceWorkDurationDto;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 上岗记录Service业务层处理
 *
 * @author wangchong
 * @date 2025-07-10
 */
@Service
public class AttendancePostRecordServiceImpl implements IAttendancePostRecordService {
    @Autowired
    private AttendancePostRecordMapper attendancePostRecordMapper;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询上岗记录
     *
     * @param id 上岗记录主键
     * @return 上岗记录
     */
    @Override
    public AttendancePostRecord selectAttendancePostRecordById(Long id) {
        return attendancePostRecordMapper.selectAttendancePostRecordById(id);
    }

    /**
     * 查询上岗记录列表
     *
     * @param attendancePostRecord 上岗记录
     * @return 上岗记录
     */
    @Override
    public List<AttendancePostRecord> selectAttendancePostRecordList(AttendancePostRecord attendancePostRecord) {
        List<AttendancePostRecord> records = attendancePostRecordMapper.selectAttendancePostRecordList(attendancePostRecord);
        if (CollectionUtil.isEmpty(records)) {
            return new ArrayList<>();
        }
//        records = records.stream().map(record -> {
//            //下通道时间是2001年1月1日00:00:00，所以这里要设置为null
//            if (record.getCheckOutTime() != null && record.getCheckOutTime().getTime() == 978352000000L) {
//                record.setCheckOutTime(null);
//            }
//            if (record.getWorkDuration() != null && record.getWorkDuration() < 0) {
//                record.setWorkDuration(0L);
//            }
//            return record;
//        }).collect(Collectors.toList());

        records.forEach(record -> {
            //下通道时间是2001年1月1日00:00:00，所以这里要设置为null
            if (record.getCheckOutTime() != null && record.getCheckOutTime().getTime() == 978352000000L) {
                record.setCheckOutTime(null);
            }
            if (record.getWorkDuration() != null && record.getWorkDuration() < 0) {
                record.setWorkDuration(0L);
            }
        });
        return records;
    }

    /**
     * 新增上岗记录
     *
     * @param attendancePostRecord 上岗记录
     * @return 结果
     */
    @Override
    public int insertAttendancePostRecord(AttendancePostRecord attendancePostRecord) {
        attendancePostRecord.setCreateTime(DateUtils.getNowDate());
        return attendancePostRecordMapper.insertAttendancePostRecord(attendancePostRecord);
    }

    /**
     * 修改上岗记录
     *
     * @param attendancePostRecord 上岗记录
     * @return 结果
     */
    @Override
    public int updateAttendancePostRecord(AttendancePostRecord attendancePostRecord) {
        attendancePostRecord.setUpdateTime(DateUtils.getNowDate());
        return attendancePostRecordMapper.updateAttendancePostRecord(attendancePostRecord);
    }

    /**
     * 批量删除上岗记录
     *
     * @param ids 需要删除的上岗记录主键
     * @return 结果
     */
    @Override
    public int deleteAttendancePostRecordByIds(Long[] ids) {
        return attendancePostRecordMapper.deleteAttendancePostRecordByIds(ids);
    }

    /**
     * 删除上岗记录信息
     *
     * @param id 上岗记录主键
     * @return 结果
     */
    @Override
    public int deleteAttendancePostRecordById(Long id) {
        return attendancePostRecordMapper.deleteAttendancePostRecordById(id);
    }

    /**
     * 查询指定用户当天的上岗记录
     *
     * @param createBy 创建人
     * @param userId   用户ID
     * @param today    当天日期
     * @return 上岗记录集合
     */
    @Override
    public List<AttendancePostRecord> selectTodayRecordsByUserId(Long createBy, Long userId, Date today, String locked) {
        return attendancePostRecordMapper.selectTodayRecordsByUserId(createBy, userId, today, locked);
    }

    /**
     * 查询指定班次代码当天的上岗记录
     *
     * @param today      当天日期
     * @param shiftCodes 班次代码列表
     * @return 上岗记录集合
     */
    @Override
    public List<AttendancePostRecord> selectTodayRecordsByShiftCodes(Date today, List<String> shiftCodes) {
        return attendancePostRecordMapper.selectTodayRecordsByShiftCodes(today, shiftCodes);
    }

    /**
     * 根据指定时间获取用户的在岗位置信息
     *
     * @param userId    用户ID
     * @param queryTime 查询时间
     * @return 上岗记录集合
     */
    @Override
    public List<AttendancePostRecord> selectLocationsByTime(Long userId, Date queryTime) {
        return attendancePostRecordMapper.selectLocationsByTime(userId, queryTime);
    }

    /**
     * 根据指定时间获取指定通道的在岗位置信息
     *
     * @param channelCodeList 通道code
     * @param nowDate         查询时间
     * @return 上岗记录集合
     */
    @Override
    public List<AttendancePostRecord> selectLocationsByTimeAndChannelName(List<String> channelCodeList, Date nowDate, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectLocationsByTimeAndChannelName(channelCodeList, nowDate, startTime, endTime);
    }

    /**
     * 查询指定班次代码当天的下岗时间
     *
     * @param today
     * @param shiftCodes
     * @return
     */
    @Override
    public List<AttendancePostRecord> selectCheckOutTimeByShiftCodes(Date today, List<Long> shiftCodes) {
        return attendancePostRecordMapper.selectCheckOutTimeByShiftCodes(today, shiftCodes);
    }

    /**
     * 获取当前登录时间下科长的在岗区域
     *
     * @return
     */
    @Override
    public List<AttendancePostRecord> selectKezhangRecordCount(Long userId, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectKezhangRecordCount(userId, startTime, endTime);
    }

    @Override
    public List<AttendancePostRecord> queryLastTime(Long userId) {
        List<AttendancePostRecord> attendancePostRecords = attendancePostRecordMapper.queryLastTime(userId);
        if (attendancePostRecords.isEmpty()) {
            return new ArrayList<>();
        }
        // 按上岗时间分组
        Map<Date, List<AttendancePostRecord>> recordsByDate = new HashMap<>();
        for (AttendancePostRecord record : attendancePostRecords) {
            Date checkInTime = record.getCheckInTime();
            if (checkInTime != null) {
                recordsByDate.computeIfAbsent(checkInTime, k -> new ArrayList<>()).add(record);
            }
        }

        // 找到最大日期
        Date maxDate = recordsByDate.keySet().stream()
                .max(Date::compareTo)
                .orElse(null);

        // 返回最后一天的所有记录
        return maxDate != null ? recordsByDate.get(maxDate) : new ArrayList<>();
    }

    @Override
    public List<Long> queryKeIds() {
//        Map<String, Date> shiftTime = getShiftTime();
        Map<String, Date> shiftTime = getShiftTimeNew();
        List<Long> longs = attendancePostRecordMapper.queryKeIds(shiftTime.get("start"), shiftTime.get("end"));
        if (CollectionUtil.isNotEmpty(longs)) {
            return longs.stream().distinct().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<AttendancePostRecord> selectTeamOnList(Date date, Long attendanceTeamId) {
        return attendancePostRecordMapper.selectTeamOnList(date, attendanceTeamId);
    }

    /**
     * 获取当前班次周期的开始和结束时间
     *
     * @return map  startTime:开始时间  endTime:结束时间
     */
    @Override
    public Map<String, Date> getShiftTime() {
        try {
            Date now = DateUtils.getNowDate();
            String todayStr = DateUtils.getDate();
            String startTime = configService.selectConfigByKey("attendance.post.record.start.time");
            String endTime = configService.selectConfigByKey("attendance.post.record.end.time");

            // 参数校验
            if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
                throw new RuntimeException("班次时间配置缺失");
            }

            // 构造昨天的班次开始时间
            Date yesterday = DateUtils.addDays(now, -1);
            String yesterdayStr = DateUtils.parseDateToStr("yyyy-MM-dd", yesterday);
            Date shiftStartTime = DateUtils.parseDate(yesterdayStr + " " + startTime);

            // 构造今天的班次结束时间
            Date shiftEndTime = DateUtils.parseDate(todayStr + " " + endTime);

            // 如果当前时间在昨天班次时间段内，则属于昨天班次
            // 否则属于今天班次（需要重新计算今天的班次时间段）
            if (now.compareTo(shiftStartTime) >= 0 && now.compareTo(shiftEndTime) < 0) {
                // 属于昨天班次，直接返回已计算的时间段
                Map<String, Date> map = new HashMap<>();
                map.put("start", shiftStartTime);
                map.put("end", shiftEndTime);
                return map;
            } else {
                // 属于今天班次，重新计算时间段
                Date todayShiftStart = DateUtils.parseDate(todayStr + " " + startTime);
                Date tomorrowShiftEnd = DateUtils.addDays(todayShiftStart, 1);

                Map<String, Date> map = new HashMap<>();
                map.put("start", todayShiftStart);
                map.put("end", tomorrowShiftEnd);
                return map;
            }
        } catch (Exception e) {
            throw new RuntimeException("班次时间计算错误: " + e.getMessage(), e);
        }
    }

    /**
     * 获取当前班次周期的开始和结束时间
     *
     * @return map  startTime:开始时间  endTime:结束时间
     */
    @Override
    public Map<String, Date> getShiftTimeNew() {
        String todayStr = DateUtils.getDate();
        Date shiftStartTime = DateUtils.parseDate(todayStr + " " + "00:00:00");
        Date shiftEndTime = DateUtils.parseDate(todayStr + " " + "23:59:59");
        Map<String, Date> map = new HashMap<>();
        map.put("start", shiftStartTime);
        map.put("end", shiftEndTime);
        return map;
    }

    /**
     * 查询指定用户最近的上岗记录的考勤日期
     *
     * @param createBy 创建人
     * @param userId   用户ID
     * @return 考勤日期
     */
    @Override
    public Date selectMaxDateByUserId(Long createBy, Long userId) {
        return attendancePostRecordMapper.selectMaxDateByUserId(createBy, userId);
    }

    @Override
    public BigDecimal selectPersonalTotalWorkDurationInTimeRange(Long userId, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectPersonalTotalWorkDurationInTimeRange(userId, startTime, endTime);
    }

    @Override
    public BigDecimal selectTopUserWorkDurationInTimeRange(Long attendanceStationId, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectTopUserWorkDurationInTimeRange(attendanceStationId, startTime, endTime);
    }

    /**
     * 根据角色标识查询今日上岗用户列表
     *
     * @param date 考勤日期
     * @param list 角色标识
     * @return 用户列表
     */
    @Override
    public List<SysUser> selectUserListByRoleKey(Date date, List<String> list) {
        return attendancePostRecordMapper.selectUserListByRoleKey(date, "1", list);
    }

    /**
     * 查询指定用户ID列表在指定时间段内的总工作时长
     *
     * @param list      用户ID列表
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 总工作时长（分钟）
     */
    @Override
    public BigDecimal selectTotalWorkDurationInTimeRange(List<Long> list, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectTotalWorkDurationInTimeRange(list, startTime, endTime);
    }

    @Override
    public List<AttendanceWorkDurationDto> selectBatchPersonalTotalWorkDurationInTimeRange(List<Long> userIds, Date startTime, Date endTime) {
        return attendancePostRecordMapper.selectBatchPersonalTotalWorkDurationInTimeRange(userIds, startTime, endTime);
    }
}
