package com.bcxin.ferry.scheduling;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ferry.common.queue.DetailFileQueue;
import com.bcxin.ferry.dtos.FerryFileCallbackDto;
import com.bcxin.ferry.service.FerryTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * description：从明细文件回调队列取值并操作
 * author：linchunpeng
 * date：2024/3/8
 */
@Slf4j
@Component
public class DetailFileCallbackQueueTake {

    @Autowired
    private FerryTaskService ferryTaskService;

    @Scheduled(cron = "5 */1 * * * ?")
    public void queueTake() {
        log.info("===================================定时从明细文件回调队列取值并操作===================================");
        while (DetailFileQueue.DETAIL_FILE_CALLBACK_QUEUE.size() > 0) {
            String data = null;
            try {
                log.info("明细文件回调队列有值，大小：{}，可以取值", DetailFileQueue.DETAIL_FILE_CALLBACK_QUEUE.size());
                data = DetailFileQueue.DETAIL_FILE_CALLBACK_QUEUE.take();
                FerryFileCallbackDto callbackDto = JSONObject.parseObject(data, FerryFileCallbackDto.class);
                //修改明细文件状态
                log.info("修改单个摆渡明细文件结果");
                Long taskId = ferryTaskService.updateFerryDetailFileResult(callbackDto);
                //修改任务状态为：摆渡明细文件结束
                if (taskId != null) {
                    log.info("根据明细文件状态，修改任务状态，taskId：{}", taskId);
                    ferryTaskService.updateFerryDetailFileComplete(taskId);
                } else {
                    log.info("文件不存在，对应的任务也不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("定时从明细文件回调队列取值并操作异常，{}", e.getMessage(), e);
                if (StringUtils.isNotBlank(data)) {
                    try {
                        log.info("定时从明细文件回调队列取值并操作异常，回调参数放入队列");
                        DetailFileQueue.DETAIL_FILE_CALLBACK_QUEUE.put(data);
                        log.info("定时从明细文件回调队列取值并操作异常，回调参数放入队列，完成");
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                        log.error("定时从明细文件回调队列取值并操作异常，回调参数放入队列异常，{}", ie.getMessage(), ie);
                    }
                }
            }
        }
        log.info("===================================定时从明细文件回调队列取值并操作结束===================================");
    }

}
