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

import com.tax.file.constants.FileConstants;
import com.tax.file.model.TkTaxUser;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.service.async.strategy.ExecuteTimesLimitStrategy;
import com.tax.file.utils.DingdingUtil;
import com.yxcheng.token.constants.RedisContants;
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 FileDownTask {

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

    @Autowired
    private TkTaxUserService tkTaxUserService;
    @Autowired
    private AsyncFileDownService asyncFileDownService;
    @Autowired
    protected ExecuteTimesLimitStrategy timesLimitStrategy;

    public void downFile(String uuidFlag) {
        List<TkTaxUser> tkTaxUsers = tkTaxUserService.queryDownloadTaxnoList();
        logger.info(uuidFlag + " downFile taxno number:" + tkTaxUsers.size());
        try {
            if(!timesLimitStrategy.isAccept(RedisContants.FILE_DOWN_MINIO_ERROR_COUNT)) {
                DingdingUtil.send("系统:" + FileConstants.systemName + "  文件服务器上传失败，请检查！",false,null);
            } else {
                if (tkTaxUsers != null && tkTaxUsers.size() > 0) {
                    CountDownLatch latch = new CountDownLatch(tkTaxUsers.size());
                    for (TkTaxUser tkTaxUser : tkTaxUsers) {
                        asyncFileDownService.doDownFile(uuidFlag, latch, tkTaxUser);
                    }
                    latch.await();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " downFile is error:" + e.getMessage());
        }
    }


}
