package cn.com.poc.ocr.scheduler;

import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.message.entity.OCRMessage;
import cn.com.poc.message.service.OCRProducerService;
import cn.com.poc.ocr.entity.BizFileOcrCacheEntity;
import cn.com.poc.ocr.service.BizFileOcrCacheService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * OCR服务
 *
 * @author alex.yao
 * @date 2025/10/30
 */
@Component
public class OCRScheduler {

    @Resource
    private BizFileOcrCacheService bizFileOcrCacheService;

    @Resource
    private OCRProducerService ocrProducerService;


    @Scheduled(fixedDelay = 10000)
    public void taskStatusUpdate() throws Exception {
        BizFileOcrCacheEntity bizFileOcrCacheEntity = new BizFileOcrCacheEntity();
        bizFileOcrCacheEntity.setParseStatus("create");
        bizFileOcrCacheEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizFileOcrCacheEntity> fileOcrCacheEntities = bizFileOcrCacheService.findByExample(bizFileOcrCacheEntity, null);

        if (CollectionUtils.isNotEmpty(fileOcrCacheEntities)) {
            for (BizFileOcrCacheEntity fileOcrCacheEntity : fileOcrCacheEntities) {

                if (fileOcrCacheEntity.getParseStatus().equals("create")) {
                    if (StringUtils.isBlank(fileOcrCacheEntity.getMdFileUrl())) {
                        fileOcrCacheEntity.setParseStatus("queuing");
                        bizFileOcrCacheService.update(fileOcrCacheEntity);

                        OCRMessage message = new OCRMessage();
                        message.setId(fileOcrCacheEntity.getId());
                        message.setFileURL(fileOcrCacheEntity.getFileUrl());
                        message.setMd5(fileOcrCacheEntity.getMd5());
                        ocrProducerService.OCR(message);
                    } else {
                        fileOcrCacheEntity.setParseStatus("complete");
                        bizFileOcrCacheService.update(fileOcrCacheEntity);

                    }
                }

            }
        }
    }

}
