package com.bcxin.ferry.scheduling;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ZipUtil;
import com.bcxin.ferry.common.utils.ObsUtil;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import com.bcxin.ferry.service.FerryReceiveTaskService;
import com.bcxin.ferry.service.FerryTaskService;
import com.bcxin.ferry.service.RetryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * description：查询接收任务状态-接收明细文件完成
 * author：linchunpeng
 * date：2024/3/8
 */
@Slf4j
@Component
public class QueryReceiveDetailFileComplete {

    @Autowired
    private FerryReceiveTaskService ferryReceiveTaskService;
    @Autowired
    private RetryService retryService;
    @Value("${spring.profiles.active}")
    private String activeFile;

    @Scheduled(cron = "${scheduling-config.query-receive-detail-file-complete.cron}")
    public void queryReceiveDetailFileComplete() {
        log.info("===================================定时查询接收任务状态-接收明细文件完成===================================");
        //查询是否有接收明细文件完成的任务
        List<FerryReceiveTaskEntity> list = ferryReceiveTaskService.queryReceiveDetailFileComplete();
        if (CollectionUtil.isNotEmpty(list)) {
            for (FerryReceiveTaskEntity receiveTaskEntity : list) {
                //合并文件
                ferryReceiveTaskService.mergeFile(receiveTaskEntity);
                //修改任务状态
                ferryReceiveTaskService.updateTaskStatusMergeFileComplete(receiveTaskEntity.getId());
                //压缩文件，并上传OBS
                if (zipAndUpload(receiveTaskEntity)) {
                    //调用摆渡工具接口，推送数据
                    ferryReceiveTaskService.pushData(receiveTaskEntity.getId());
                }
            }
        }
        log.info("===================================查询接收任务状态-接收明细文件完成结束===================================");
    }

    /**
     * description：压缩文件，并上传OBS
     * author：linchunpeng
     * date：2024/4/19
     */
    private boolean zipAndUpload(FerryReceiveTaskEntity receiveTaskEntity) {
        //压缩文件夹
        if ("out-prod".equals(activeFile)) {
            String filePath = receiveTaskEntity.getPackageUrl();
            File zip = ZipUtil.zip(filePath);
            boolean isPushZw = receiveTaskEntity.getIsPushZw() != null && receiveTaskEntity.getIsPushZw() == 1;
            int uploadCount = 0 ;
            boolean uploadResult = false;
            if (isPushZw) {
                //上传到政务外网
                while (!uploadResult && uploadCount < 10) {
                    uploadResult = retryService.postToBaiduutilServerUploadFile(receiveTaskEntity, zip);
                    uploadCount++;
                    log.info("第{}次上传到政务外网，上传：{}", uploadCount, uploadResult);
                    if (!uploadResult) {
                        //上传失败，等待2分钟
                        log.info("上传失败，等待2分钟");
                        try {
                            Thread.sleep(120000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                //上传OBS
                while (!uploadResult && uploadCount < 10) {
                    //预防上传失败
                    uploadResult = ObsUtil.uploadFile(zip, filePath.substring(filePath.indexOf("baidu/")).concat(".zip"));
                    uploadCount++;
                    log.info("第{}次上传OBS，上传：{}", uploadCount, uploadResult);
                    if (!uploadResult) {
                        //上传失败，等待2分钟
                        log.info("上传失败，等待2分钟");
                        try {
                            Thread.sleep(120000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return uploadResult;
        }
        return true;
    }

}
