package com.bcxin.ferry.scheduling;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.bcxin.ferry.common.emus.FerryReceiveTaskStatusEnum;
import com.bcxin.ferry.common.utils.ObsUtil;
import com.bcxin.ferry.configs.ReceiveConfig;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import com.bcxin.ferry.service.FerryReceiveTaskService;
import com.bcxin.ferry.service.FerryTaskService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
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;
import java.util.concurrent.TimeUnit;

/**
 * description：检测接收摆渡文件
 * author：linchunpeng
 * date：2024/3/8
 */
@Slf4j
@Component
public class DetectionReceiveFile {

    @Autowired
    private FerryReceiveTaskService ferryReceiveTaskService;
    @Autowired
    private ReceiveConfig receiveConfig;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private FerryTaskService ferryTaskService;
    @Value("${spring.profiles.active}")
    private String activeFile;

    @Scheduled(cron = "${scheduling-config.detection-receive-file.cron}")
    public void detectionReceiveFile() {
        log.info("===================================定时检测接收摆渡文件===================================");
        //分布式锁key
        String lockKey = "REDISSON_LOCK_DETECTION_RECEIVE_FILE";
        //取锁
        log.info("检测接收摆渡文件， lockKey：{}，取锁中.....", lockKey);
        RLock lock = redissonClient.getLock(lockKey);
        //加锁，并设置过期时间 300s
        lock.lock(900, TimeUnit.SECONDS);
        log.info("取到锁");
        try {
            List<File> fileList = FileUtil.loopFiles(receiveConfig.getDetectionUrl());
            if (CollectionUtil.isNotEmpty(fileList)) {
                log.info("检测到新文件，个数：{}", fileList.size());
                for (File file : fileList) {
                    String fileName = file.getName();
                    try {
                        log.info("新文件，fileName：{}", fileName);
                        String requestId = fileName.substring(0, fileName.indexOf("."));
                        log.info("新文件，requestId：{}", requestId);
                        if (fileName.contains(".complete")) {
                            //摆渡任务执行成功通知
                            log.info("摆渡任务执行成功通知");
                            ferryTaskService.updateFerryTaskComplete(requestId);
                        } else {
                            //先创建一条接收任务
                            FerryReceiveTaskEntity ferryReceiveTaskEntity = ferryReceiveTaskService.receiveRequest(requestId);
                            if (ferryReceiveTaskEntity.getTaskStatus() == FerryReceiveTaskStatusEnum.RECEIVE_REQUEST.getCode()) {
                                //新建的
                                log.info("requestId：{}，是新增接收任务", requestId);
                                //内网接收文件后，直接复制
                                //政务接收文件后，需要判断是摆渡到政务网，还是互联网
                                //摆渡到政务网，也是直接复制，摆渡到互联网，需要上传obs
                                if (activeFile.contains("out")) {
                                    log.info("政务接收文件后");
                                    if (requestId.contains("zw")) {
                                        log.info("摆渡到政务网，也是直接复制");
                                        FileUtil.copy(file, new File(ferryReceiveTaskEntity.getPackageUrl()), true);
                                    } else {
                                        log.info("摆渡到互联网，需要上传obs");
                                        ObsUtil.uploadFile(file, "baidu/push/".concat(fileName));
                                    }
                                } else {
                                    log.info("内网接收文件后，直接复制");
                                    FileUtil.copy(file, new File(ferryReceiveTaskEntity.getPackageUrl()), true);
                                }
                                //执行推送数据
                                log.info("执行推送数据");
                                ferryReceiveTaskService.pushData(ferryReceiveTaskEntity);
                            } else if (ferryReceiveTaskEntity.getTaskStatus() == FerryReceiveTaskStatusEnum.FERRY_COMPLETE.getCode()
                                    || ferryReceiveTaskEntity.getTaskStatus() == FerryReceiveTaskStatusEnum.CALLBACK_COMPLETE.getCode()) {
                                log.info("requestId：{}，是已接收任务，需要重新返回complete文件", requestId);
                                ferryReceiveTaskService.sendCompleteFile(ferryReceiveTaskEntity);
                            } else {
                                log.info("requestId：{}，未完成摆渡，跳过", requestId);
                            }
                        }
                        FileUtil.del(file);
                    } catch (Exception e) {
                        log.error("检测文件：{}，出错，{}", fileName, e.getMessage(), e);
                    }
                }
            } else {
                log.info("无新摆渡进来的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("检测接收摆渡文件异常，{}", e.getMessage(), e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
            log.info("检测接收摆渡文件，lockKey：{}，解锁", lockKey);
        }
        log.info("===================================定时检测接收摆渡文件结束===================================");
    }

}
