package com.test.bijihoudaun.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.RegistrationCode;
import com.test.bijihoudaun.mapper.RegistrationCodeMapper;
import com.test.bijihoudaun.service.RegistrationCodeService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class RegistrationCodeServiceImpl extends ServiceImpl<RegistrationCodeMapper, RegistrationCode> implements RegistrationCodeService {

    // 修复：定义日期时间格式器
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public String generateCode(String creator) {
        RegistrationCode registrationCode = new RegistrationCode();
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        registrationCode.setCode(code);
        registrationCode.setCreatedBy(creator);
        // 修复：使用格式化后的日期字符串
        registrationCode.setCreatedAt(LocalDateTime.now().format(DATE_TIME_FORMATTER));
        registrationCode.setExpiryTime(LocalDateTime.now().plusDays(1).format(DATE_TIME_FORMATTER));
        save(registrationCode);
        return code;
    }

    @Override
    @Transactional
    public boolean validateCode(String code) {
        QueryWrapper<RegistrationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        RegistrationCode registrationCode = getOne(queryWrapper);

        if (ObjectUtil.isNull(registrationCode)) {
            return false;
        }

        try {
            // 修复：使用格式器解析日期
            LocalDateTime expiryTime = LocalDateTime.parse(registrationCode.getExpiryTime(), DATE_TIME_FORMATTER);
            if (expiryTime.isBefore(LocalDateTime.now())) {
                remove(queryWrapper); // 注册码过期，删除
                return false;
            }
        } catch (Exception e) {
            // 如果解析失败（可能是旧数据格式），认为已过期
            remove(queryWrapper);
            return false;
        }

        // 验证成功后立即删除，确保一次性使用
        remove(queryWrapper);
        return true;
    }

    @Override
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void deleteExpiredCodes() {
        // 修复：使用格式化后的日期字符串进行比较
        remove(new QueryWrapper<RegistrationCode>().lt("expiry_time", LocalDateTime.now().format(DATE_TIME_FORMATTER)));
    }
}
