package cn.novalon.gym.manage.groupcourse.initializer;

import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 项目启动时补全缺失的团课二维码
 * 遍历所有未删除的团课，对qrCodePath为空的课程生成二维码并上传至阿里云OSS
 */
@Component
public class QrCodeInitializer implements CommandLineRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(QrCodeInitializer.class);
    
    private final IGroupCourseRepository groupCourseRepository;
    private final ObjectMapper objectMapper;
    
    public QrCodeInitializer(IGroupCourseRepository groupCourseRepository,
                             ObjectMapper objectMapper) {
        this.groupCourseRepository = groupCourseRepository;
        this.objectMapper = objectMapper;
    }
    
    @Override
    public void run(String... args) {
        logger.info("===== 开始检查团课二维码缺失情况 =====");
        
        groupCourseRepository.findByDeletedAtIsNull()
                .filter(course -> course.getQrCodePath() == null || course.getQrCodePath().isEmpty())
                .flatMap(course -> {
                    try {
                        logger.info("发现缺失二维码的团课 - id={}, name={}", course.getId(), course.getCourseName());
                        
                        // 生成二维码内容：团课基础信息JSON
                        Map<String, Object> qrCodeContent = new HashMap<>();
                        qrCodeContent.put("id", course.getId());
                        qrCodeContent.put("courseName", course.getCourseName());
                        qrCodeContent.put("coachId", course.getCoachId());
                        qrCodeContent.put("courseType", course.getCourseType());
                        qrCodeContent.put("startTime", course.getStartTime() != null ? course.getStartTime().toString() : null);
                        qrCodeContent.put("endTime", course.getEndTime() != null ? course.getEndTime().toString() : null);
                        qrCodeContent.put("maxMembers", course.getMaxMembers());
                        qrCodeContent.put("location", course.getLocation());
                        qrCodeContent.put("description", course.getDescription());
                        
                        String jsonContent = objectMapper.writeValueAsString(qrCodeContent);
                        
                        // 生成二维码并上传到阿里云OSS
                        String uuid = UUID.randomUUID().toString().replace("-", "");
                        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
                        String fileName = "qr_" + uuid + "_" + timestamp + ".png";
                        String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent, fileName);
                        
                        course.setQrCodePath(ossUrl);
                        
                        // 更新数据库
                        return groupCourseRepository.update(course)
                                .doOnSuccess(updated -> logger.info("团课二维码补全成功 - id={}, name={}, ossUrl={}", 
                                        updated.getId(), updated.getCourseName(), ossUrl))
                                .doOnError(error -> logger.error("团课二维码补全失败(更新DB) - id={}, name={}, error: {}", 
                                        course.getId(), course.getCourseName(), error.getMessage()));
                    } catch (Exception e) {
                        logger.error("团课二维码补全失败(生成) - id={}, name={}, error: {}", 
                                course.getId(), course.getCourseName(), e.getMessage(), e);
                        return Mono.empty();
                    }
                })
                .collectList()
                .doOnSuccess(list -> logger.info("===== 团课二维码检查完毕，共补全 {} 个缺失二维码 =====", list.size()))
                .onErrorResume(error -> {
                    logger.error("团课二维码初始化检查异常: {}", error.getMessage(), error);
                    return Mono.empty();
                })
                .subscribe();
    }
}
