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

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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.system.mapper.SysUserMapper;
import com.sundot.airport.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.attendance.mapper.AttendanceTeamUserRecordMapper;
import com.sundot.airport.attendance.domain.AttendanceTeamUserRecord;
import com.sundot.airport.attendance.service.IAttendanceTeamUserRecordService;
import org.springframework.transaction.annotation.Transactional;

import static com.sundot.airport.common.utils.SecurityUtils.getUsername;

/**
 * 考勤班组成员Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-06
 */
@Service
public class AttendanceTeamUserRecordServiceImpl implements IAttendanceTeamUserRecordService {
    @Autowired
    private AttendanceTeamUserRecordMapper attendanceTeamUserRecordMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询考勤班组成员
     *
     * @param userId 考勤班组成员主键
     * @return 考勤班组成员
     */
    @Override
    public AttendanceTeamUserRecord selectAttendanceTeamUserRecordByUserId(Long userId, Date attendanceDate, String checkInType) {
        return attendanceTeamUserRecordMapper.selectAttendanceTeamUserRecordByUserId(userId, attendanceDate, checkInType);
    }

    @Override
    public List<AttendanceTeamUserRecord> selectAttendanceTeamUserRecordPageList(AttendanceTeamUserRecord attendanceTeamUserRecord) {
        return attendanceTeamUserRecordMapper.selectAttendanceTeamUserRecordList(attendanceTeamUserRecord);
    }

    /**
     * 上岗记录中查询考勤班组成员列表
     *
     * @param attendanceTeamUserRecord 考勤班组成员
     * @return 考勤班组成员
     */
    @Override
    public List<AttendanceTeamUserRecord> selectAttendanceTeamUserRecordList(AttendanceTeamUserRecord attendanceTeamUserRecord, boolean changeDate) {
        // 如果指定了考勤日期，则调整查询时间范围
//        if (attendanceTeamUserRecord.getAttendanceDate() != null) {
//            try {
//                String display = configService.selectConfigByKey("attendance.team.user.record.display.end.time");
//                Date date = getDate(new Date(), display);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                String baseDateStr = sdf.format(date);
//                String nextDateStr = sdf.format(DateUtils.addDays(date, 1));
//
//                // 显示时间范围：当日7:00到次日9:00
//                Date displayStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(baseDateStr + " " + configService.selectConfigByKey("attendance.team.user.record.start.time"));
//                Date displayEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextDateStr + " " + display);
//
//                // 设置查询时间范围
//                attendanceTeamUserRecord.setAttendanceDateStart(displayStartDate);
//                attendanceTeamUserRecord.setAttendanceDateEnd(displayEndDate);
//                // 清除原始的attendanceDate，避免冲突
//                attendanceTeamUserRecord.setAttendanceDate(null);
//            } catch (Exception e) {
//                throw new ServiceException("日期格式化错误");
//            }
//        }
        if (changeDate) {
            Date maxDate = attendanceTeamUserRecordMapper.selectMaxDateBy(attendanceTeamUserRecord);
            if (maxDate != null) {
                attendanceTeamUserRecord.setAttendanceDate(maxDate);
            }
        }
        return attendanceTeamUserRecordMapper.selectAttendanceTeamUserRecordList(attendanceTeamUserRecord);
    }


    /**
     * 新增考勤班组成员
     *
     * @param attendanceTeamUserRecord 考勤班组成员
     * @return 结果
     */
    @Override
    public int insertAttendanceTeamUserRecord(AttendanceTeamUserRecord attendanceTeamUserRecord) {
        attendanceTeamUserRecord.setCreateTime(DateUtils.getNowDate());
        return attendanceTeamUserRecordMapper.insertAttendanceTeamUserRecord(attendanceTeamUserRecord);
    }

    /**
     * 修改考勤班组成员
     *
     * @param attendanceTeamUserRecord 考勤班组成员
     * @return 结果
     */
    @Override
    public int updateAttendanceTeamUserRecord(AttendanceTeamUserRecord attendanceTeamUserRecord) {
        attendanceTeamUserRecord.setUpdateTime(DateUtils.getNowDate());
        return attendanceTeamUserRecordMapper.updateAttendanceTeamUserRecord(attendanceTeamUserRecord);
    }

    /**
     * 批量删除考勤班组成员
     *
     * @param userIds 需要删除的考勤班组成员主键
     * @return 结果
     */
    @Override
    public int deleteAttendanceTeamUserRecordByUserIds(Long[] userIds) {
        return attendanceTeamUserRecordMapper.deleteAttendanceTeamUserRecordByUserIds(userIds);
    }

    /**
     * 删除考勤班组成员信息
     *
     * @param userId 考勤班组成员主键
     * @return 结果
     */
    @Override
    public int deleteAttendanceTeamUserRecordByUserId(Long userId) {
        return attendanceTeamUserRecordMapper.deleteAttendanceTeamUserRecordByUserId(userId);
    }

    /**
     * 批量插入考勤班组成员
     *
     * @param attendanceTeamUserRecord
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertAttendanceTeamUserRecordList(List<AttendanceTeamUserRecord> attendanceTeamUserRecord) {
        List<String> userName = new ArrayList<>();
        attendanceTeamUserRecord.forEach(record -> {
            record.setCreateTime(DateUtils.getNowDate());
            record.setCreateBy(getUsername());
            if (Objects.isNull(record.getAttendanceDate())) {
                record.setAttendanceDate(DateUtils.getNowDate());
            }
            if (Objects.isNull(record.getUserId())) {
                throw new ServiceException("用户id不能为空");
            }

            // 计算班次周期范围：前一天到后一天
            Date startDate = DateUtils.addDays(record.getAttendanceDate(), -1);
            Date endDate = DateUtils.addDays(record.getAttendanceDate(), 1);

            // 构建查询条件
            AttendanceTeamUserRecord searchRecord = new AttendanceTeamUserRecord();
            searchRecord.setUserId(record.getUserId());
//            searchRecord.setAttendanceDateStart(startDate);
//            searchRecord.setAttendanceDateEnd(endDate);
            searchRecord.setAttendanceDate(record.getAttendanceDate());
            searchRecord.setCheckInType("1");

            // 查询时间范围内的记录
            List<AttendanceTeamUserRecord> existingRecords = attendanceTeamUserRecordMapper
                    .selectAttendanceTeamUserRecordList(searchRecord);

            // 检查是否存在班次周期内的重复记录（当日7:00 - 次日7:00）
//            if (hasRecordInShiftPeriod(existingRecords, record.getAttendanceDate())) {
//                // 获取第一个重复记录的用户名
//                AttendanceTeamUserRecord firstDuplicate = existingRecords.stream()
//                        .filter(r -> isWithinShiftPeriod(r.getCreateTime(), new Date()))
//                        .findFirst()
//                        .orElse(null);
//                if (firstDuplicate != null) {
//                    userName.add(firstDuplicate.getUserName());
//                }
//            }

            if (!CollectionUtil.isEmpty(existingRecords)) {
                userName.add(existingRecords.get(0).getUserName());
            }
        });
        if (userName.size() > 0) {
            throw new ServiceException(StrUtil.format("用户【{}】在当前班次周期内已维护", String.join(",", userName)));
        }

        // 先删除后新增
        AttendanceTeamUserRecord oldSearchRecord = new AttendanceTeamUserRecord();
        oldSearchRecord.setCreateBy(attendanceTeamUserRecord.get(0).getCreateBy());
        oldSearchRecord.setAttendanceDate(attendanceTeamUserRecord.get(0).getAttendanceDate());
        List<AttendanceTeamUserRecord> oldList = attendanceTeamUserRecordMapper.selectAttendanceTeamUserRecordList(oldSearchRecord);
        if (CollectionUtil.isNotEmpty(oldList)) {
            Long[] oldIdArray = oldList.stream().map(AttendanceTeamUserRecord::getId).toArray(Long[]::new);
            attendanceTeamUserRecordMapper.deleteAttendanceTeamUserRecordByIds(oldIdArray);
        }
        return attendanceTeamUserRecordMapper.insertAttendanceTeamUserRecordList(attendanceTeamUserRecord);
    }

    @Override
    public List<Long> selectAttendanceTeamLeaderId() {
        AttendanceTeamUserRecord attendanceTeamUserRecord = new AttendanceTeamUserRecord();
        attendanceTeamUserRecord.setAttendanceDate(DateUtils.getNowDate());
        attendanceTeamUserRecord.setCheckInType("1");
        List<AttendanceTeamUserRecord> attendanceTeamUserRecords = selectAttendanceTeamUserRecordList(attendanceTeamUserRecord, true);
        List<Long> collect = attendanceTeamUserRecords.stream().map(AttendanceTeamUserRecord::getAttendanceTeamId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)) {
            return new ArrayList<>();
        }
        List<Long> longs = userMapper.selectAttendanceTeamLeaderId(collect);
        if (CollectionUtil.isEmpty(longs)) {
            return new ArrayList<>();
        }
        return longs.stream().distinct().collect(Collectors.toList());
    }


    /**
     * 判断是否存在班次周期内的记录
     *
     * @param records    查询到的记录列表
     * @param targetDate 目标日期
     * @return 是否存在班次周期内的记录
     */
    private boolean hasRecordInShiftPeriod(List<AttendanceTeamUserRecord> records, Date targetDate) {
        return records.stream().anyMatch(record -> isWithinShiftPeriod(record.getCreateTime(), targetDate));
    }

    /**
     * 判断指定日期是否在目标日期的班次周期内（当日7:00 - 次日7:00）
     *
     * @param recordDate 记录日期
     * @param targetDate 目标日期
     * @return 是否在班次周期内
     */
    private boolean isWithinShiftPeriod(Date recordDate, Date targetDate) {
        if (recordDate == null || targetDate == null) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String end = configService.selectConfigByKey("attendance.team.user.record.end.time");
            targetDate = getDate(targetDate, end);
            String targetDateStr = sdf.format(targetDate);
            String nextDateStr = sdf.format(DateUtils.addDays(targetDate, 1));
            String recordDateStr = sdf.format(recordDate);

            // 班次的开始时间（targetDate 07:00:00）
            Date shiftStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(targetDateStr + " " + configService.selectConfigByKey("attendance.team.user.record.start.time"));

            // 班次的结束时间（targetDate+1天 07:00:00）
            Date shiftEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextDateStr + " " + end);

            // 构造记录日期的代表时间（recordDate 00:00:00）
            Date recordDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(recordDateStr + " 00:00:00");

            // 判断记录日期是否在班次周期内
            return !(recordDateTime.before(shiftStartTime) || recordDateTime.after(shiftEndTime));
        } catch (Exception e) {
            return false;
        }
    }

    private Date getDate(Date targetDate, String time) {
        if (targetDate == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //判断targetDate是否在7点之前
            if (targetDate.before(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(targetDate) + " " + time))) {
                targetDate = DateUtils.addDays(targetDate, -1);
            }
            return targetDate;
        } catch (ParseException e) {
            throw new ServiceException("日期解析失败");
        }
    }

    /**
     * 批量删除考勤班组成员
     *
     * @param ids 需要删除的考勤班组成员主键
     * @return 结果
     */
    @Override
    public int deleteAttendanceTeamUserRecordByIds(Long[] ids) {
        return attendanceTeamUserRecordMapper.deleteAttendanceTeamUserRecordByIds(ids);
    }
}
