package com.storlead.centre.dispatch;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.centre.entity.AttendanceSignRecordEntity;
import com.storlead.centre.entity.HrmschedulesignEntity;
import com.storlead.centre.entity.HrmschedulesignRemindEntity;
import com.storlead.centre.entity.SystemConfigItemEntity;
import com.storlead.centre.service.AttendanceSignRecordService;
import com.storlead.centre.service.HrmschedulesignRemindService;
import com.storlead.centre.service.HrmschedulesignService;
import com.storlead.centre.service.SystemConfigItemService;
import com.storlead.centre.vo.SignDataConvert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @program: 同步考勤数据到OA
 * @description:
 * @author: chenkq
 * @create: 2026-01-08 11:12
 */
@Slf4j
@Component
public class SyncAttendanceSignToOaTask {

    @Resource
    private AttendanceSignRecordService attendanceSignRecordService;
    @Resource
    private HrmschedulesignRemindService hrmschedulesignRemindService;
    @Resource
    private HrmschedulesignService hrmschedulesignService;
    @Resource
    private SystemConfigItemService systemConfigItemService;

    @Value("${environment}")
    private  String environment;

    private final ReentrantLock syncLock = new ReentrantLock();

    @Scheduled(cron ="0 * * * * ? ")
    public void syncSignDataToOA() throws ParseException {
        if(!"prod".equals(environment)) {
            return;
        }

        if (!syncLock.tryLock()) {
            log.warn("syncSignData 正在执行中，本次调度跳过");
            return;
        }

        try {

            LocalTime now = LocalTime.now();
            // ===== 总时间窗：06:00 – 22:30 =====
            if (now.isBefore(LocalTime.of(6, 0))
                    || now.isAfter(LocalTime.of(22, 30))) {
                return;
            }

            boolean morningHighFrequency =
                    (now.getHour() == 8 && now.getMinute() >= 30)
                            || (now.getHour() == 9 && now.getMinute() <= 10);

            boolean eveningHighFrequency =
                    (now.getHour() == 18)
                            || (now.getHour() == 19 && now.getMinute() <= 40);

            boolean highFrequency = morningHighFrequency || eveningHighFrequency;
            // 非高频时间：只允许 5 分钟一次
            if (!highFrequency && now.getMinute() % 5 != 0) {
                return;
            }

            // 获取未同步的数据到
            LambdaQueryWrapper<AttendanceSignRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AttendanceSignRecordEntity::getSyncOa, Integer.valueOf(0));
            List<AttendanceSignRecordEntity> attendances = attendanceSignRecordService.list(lambdaQueryWrapper);

            if (CollectionUtils.isEmpty(attendances)) {
                return;
            }
            List<Long> ids = attendances.stream().map(AttendanceSignRecordEntity::getId).collect(Collectors.toList());
            List<Long> bmd = new ArrayList<>();
            SystemConfigItemEntity systemConfig = systemConfigItemService.getSystemConfigItem("ATTENDANCE_SGIN_PRIORITY_USER_ID");
            if (Objects.nonNull(systemConfig)) {
                String values = systemConfig.getItemFormatValue();
                if (StrUtil.isNotBlank(values)) {
                    bmd = Arrays.stream(values.split(","))
                            .map(String::trim)        // 去空格，防止 " 1"
                            .filter(s -> !s.isEmpty())// 防止空字符串
                            .map(Long::valueOf)
                            .collect(Collectors.toList());
                    ;
                }
            }
            LambdaUpdateWrapper<AttendanceSignRecordEntity> oawp = new LambdaUpdateWrapper<>();
            oawp.set(AttendanceSignRecordEntity::getSyncOa, Integer.valueOf(1));
            oawp.in(AttendanceSignRecordEntity::getId, ids);
            attendanceSignRecordService.update(oawp);
            //同步OA数据
            List<HrmschedulesignEntity> hrmschedulesignsDb;
            List<HrmschedulesignEntity> hrmschedulesigns = SignDataConvert.attendanceListToOaSignVoList(attendances);
            if (!CollectionUtils.isEmpty(hrmschedulesigns)) {
                if (!CollectionUtils.isEmpty(bmd)) {
                    List<Long> finalBmd = bmd;
                    hrmschedulesignsDb = hrmschedulesigns.stream().filter(e -> finalBmd.contains(e.getUserid())).collect(Collectors.toList());
                } else {
                    hrmschedulesignsDb = hrmschedulesigns;
                }
                if (!CollectionUtils.isEmpty(hrmschedulesignsDb)) {
                    hrmschedulesignService.saveBatch(hrmschedulesignsDb);
                }
            }

            List<HrmschedulesignRemindEntity> hrmschedulesignremindsDb;
            List<HrmschedulesignRemindEntity> hrmschedulesignreminds = SignDataConvert.attendanceListToOaSignRemindVoList(attendances);
            if (!CollectionUtils.isEmpty(hrmschedulesignreminds)) {
                if (!CollectionUtils.isEmpty(bmd)) {
                    List<Long> finalBmd = bmd;
                    hrmschedulesignremindsDb = hrmschedulesignreminds.stream().filter(e -> finalBmd.contains(e.getUserid())).collect(Collectors.toList());
                } else {
                    hrmschedulesignremindsDb = hrmschedulesignreminds;
                }
                if (!CollectionUtils.isEmpty(hrmschedulesignremindsDb)) {
                    hrmschedulesignRemindService.saveBatch(hrmschedulesignremindsDb);
                }
            }
        } catch (Exception e) {
            log.error("syncSignDataToOA error ----",e);
        } finally {
            // 👉 确保一定释放锁（防死锁）
            syncLock.unlock();
        }
    }

}
