package com.tax.file.service.async.token;

import com.tax.file.constants.FileConstants;
import com.tax.file.model.FileToken;
import com.tax.file.service.api.FileTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;

@Component
public class TokenCheckTask {

    private static final Logger logger = LoggerFactory.getLogger(TokenCheckTask.class);
    @Autowired
    private FileTokenService fileTokenService;

    @Autowired
    private TokenCheckService tokenCheckService;

    public void checkToken(String uuidFlag){
        Integer tokenId = 0;
        try {
            int runNum = 0;
            while (true) {
                List<FileToken> fileTokenList = fileTokenService.findWaitToken(tokenId, FileConstants.tokenPageNum);
                if(null!=fileTokenList && fileTokenList.size()>0){
                    tokenId = fileTokenList.get(fileTokenList.size()-1).getId();
                    logger.info(uuidFlag + " checkToken taxno number:" + fileTokenList.size() + ",tokenId:" + tokenId + ",runNum:" + (runNum++) + " is start!");
                    CountDownLatch latch = new CountDownLatch(fileTokenList.size());
                    for(FileToken fileToken: fileTokenList){
                        tokenCheckService.doTokenCheck(uuidFlag, latch, fileToken);
                    }
                    latch.await();
                    logger.info(uuidFlag + " checkToken taxno number:" + fileTokenList.size() + ",tokenId:" + tokenId + "is end!");
                    if(runNum>10000) {
                        //防止死循环
                        break;
                    }
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " checkToken is error:" + e.getMessage());
        }
    }

}
