package com.bcxin.ferry.strategy.callback.impl;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ferry.common.emus.SendBoundaryUrlEnum;
import com.bcxin.ferry.dtos.FerryFileCallbackDto;
import com.bcxin.ferry.entity.FerryTaskFileEntity;
import com.bcxin.ferry.service.FerryTaskFileService;
import com.bcxin.ferry.service.FerryTaskService;
import com.bcxin.ferry.strategy.callback.ReceiveCallbackStrategy;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description：接收任务文件回调策略
 * author：linchunpeng
 * date：2024/3/6
 */
@Slf4j
@Service
public class ReceiveTaskFileCallbackStrategy implements ReceiveCallbackStrategy {

    @Autowired
    private FerryTaskService ferryTaskService;
    @Autowired
    private FerryTaskFileService ferryTaskFileService;
    @Autowired
    private RedissonClient redissonClient;

    @Async(value = "taskExecutor")
    @Override
    public void handle(String data) {
        //分布式锁key
        String lockKey = "REDISSON_LOCK_RECEIVE_TASK_FILE_CALLBACK";
        //取锁
        log.info("接收任务文件回调策略，lockKey：{}，取锁中.....", lockKey);
        RLock lock = redissonClient.getLock(lockKey);
        //加锁，并设置过期时间 300s
        lock.lock(300, TimeUnit.SECONDS);
        log.info("取到锁");
        try {
            //修改任务文件状态、摆渡任务状态
            Long taskId = ferryTaskService.updateFerryTaskFileResult(JSONObject.parseObject(data, FerryFileCallbackDto.class));
            if (taskId != null) {
                //开始摆渡明细文件
                ferryTaskService.sendFerryDetailFile(taskId);
                //摆渡任务明细文件
                log.info("摆渡任务明细文件");
                List<FerryTaskFileEntity> ferryTaskFileEntityList = ferryTaskFileService.queryDetailFileByTaskId(taskId);
                for (FerryTaskFileEntity taskFileEntity : ferryTaskFileEntityList) {
                    log.info("摆渡明细文件，taskId：{}，文件id：{}，文件名称：{}", taskId, taskFileEntity.getId(), taskFileEntity.getFileName());
                    ferryTaskFileService.ferryFileToBoundary(taskFileEntity, SendBoundaryUrlEnum.SEND_DETAIL_FILE);
                }
                log.info("摆渡任务明细文件完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收任务文件回调策略异常，{}", e.getMessage(), e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
            log.info("接收任务文件回调策略，lockKey：{}，解锁", lockKey);
        }
    }
}
