package com.kexue.skills.task;

import com.kexue.skills.entity.AccountFrozen;
import com.kexue.skills.mapper.AccountFrozenMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 账户冻结单定时任务
 * 扫描过期的冻结单并更新状态
 *
 * @author 系统生成
 * @since 2026-04-11
 */
@Component
public class AccountFrozenTask {

    private static final Logger logger = LoggerFactory.getLogger(AccountFrozenTask.class);

    @Resource
    private AccountFrozenMapper accountFrozenMapper;

    /**
     * 定时扫描过期的冻结单
     * 每隔30分钟执行一次
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void scanExpiredFrozen() {
        logger.info("开始扫描过期的冻结单");
        
        try {
            // 查询所有状态为RESERVED且过期的冻结单
            List<AccountFrozen> expiredFrozenList = accountFrozenMapper.selectExpiredFrozen(new Date());
            
            if (expiredFrozenList != null && !expiredFrozenList.isEmpty()) {
                logger.info("发现 {} 个过期的冻结单", expiredFrozenList.size());
                
                for (AccountFrozen frozen : expiredFrozenList) {
                    // 更新状态为FINALIZED
                    frozen.setStatus("FINALIZED");
                    frozen.setFinalizeReason("timeout");
                    frozen.setUpdateTime(new Date());
                    
                    // 执行更新
                    accountFrozenMapper.updateByPrimaryKey(frozen);
                    logger.info("已处理过期冻结单: {}", frozen.getFrozenId());
                }
            } else {
                logger.info("未发现过期的冻结单");
            }
        } catch (Exception e) {
            logger.error("扫描过期冻结单时发生错误", e);
        }
        
        logger.info("扫描过期冻结单完成");
    }

}
