package com.bcxin.autodownloadupload.service.impl;

import com.bcxin.autodownloadupload.common.utils.FileUtils;
import com.bcxin.autodownloadupload.service.RetryableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * description: 重试方法服务
 * author: linchunpeng
 * date:  2023-04-19 9:26
 */
@Slf4j
@Service
public class RetryableServiceImpl implements RetryableService {

    /**
     * description: 下载拉取结果的zip
     * author: linchunpeng
     * date:  2023-04-19 9:27
     */
    @Override
//    @Retryable(value = Exception.class, maxAttempts = 60, backoff = @Backoff(delay = 120000, maxDelay = 300000, multiplier = 1))
    public String downloadPullResult(String pullResultZipUrl, String savePath) throws Exception {
        String result = null;
        //先等等5分钟在下载
        log.info("先等等5分钟在下载");
        Thread.sleep(300000);
        if (FileUtils.getUrlStatus(pullResultZipUrl) == 404) {
            log.info("下载连接是404，说明没有变更数据，无zip下载");
            return result;
        }
        int count = 0;
        while (StringUtils.isBlank(result) && count < 60) {
            count++;
            try {
                result = FileUtils.downloadByUrl(pullResultZipUrl, savePath);
            } catch (Exception ignored) {

            }
            if (StringUtils.isBlank(result)) {
                log.info("下载拉取zip包出错，等待2分钟，当前等待次数：{}", count);
                Thread.sleep(120000);
            }
        }
        return result;
    }

}
