package com.cool.modules.dingtalk.task;

import com.cool.modules.dingtalk.entity.DingtalkConfigEntity;
import com.cool.modules.dingtalk.service.DingtalkConfigService;
import com.cool.modules.dingtalk.service.DingtalkSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 钉钉同步定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DingtalkSyncTask {

    private final DingtalkConfigService dingtalkConfigService;
    private final DingtalkSyncService dingtalkSyncService;

    /**
     * 定时自动同步
     * 默认每天凌晨2点执行
     */
    @Scheduled(cron = "${dingtalk.sync.cron:0 0 2 * * ?}")
    public void autoSync() {
        log.info("【钉钉定时任务】定时同步任务触发");

        try {
            // 获取配置
            DingtalkConfigEntity config = dingtalkConfigService.getConfig();

            if (config == null) {
                log.warn("【钉钉定时任务】钉钉配置不存在，跳过同步");
                return;
            }

            if (config.getAutoSync() == null || config.getAutoSync() != 1) {
                log.info("【钉钉定时任务】自动同步未启用，跳过同步");
                return;
            }

            // 执行同步（类型为自动：1）
            dingtalkSyncService.syncAll(1);

            log.info("【钉钉定时任务】定时同步任务已启动");

        } catch (Exception e) {
            log.error("【钉钉定时任务】定时同步任务执行异常", e);
        }
    }
}
