package com.bcxin.ferry.scheduling;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.bcxin.ferry.common.emus.FerryReceiveTaskStatusEnum;
import com.bcxin.ferry.common.emus.SendBoundaryUrlEnum;
import com.bcxin.ferry.dtos.FerryDto;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import com.bcxin.ferry.service.FerryReceiveTaskService;
import com.bcxin.ferry.service.SendRequestToBoundaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * description：查询接收任务状态-摆渡完成
 * author：linchunpeng
 * date：2024/3/8
 */
@Slf4j
@Component
public class QueryReceiveTaskComplete {

    @Autowired
    private FerryReceiveTaskService ferryReceiveTaskService;
    @Autowired
    private SendRequestToBoundaryService sendRequestToBoundaryService;

    @Scheduled(cron = "${scheduling-config.query-receive-task-complete.cron}")
    public void queryReceiveTaskComplete() {
        log.info("===================================定时查询接收任务状态-摆渡完成===================================");
        //查询摆渡工具服务是否推送完成
        ferryReceiveTaskService.queryReceiveTaskIsComplete();
        //查询是否有接收明细文件完成的任务
        List<FerryReceiveTaskEntity> list = ferryReceiveTaskService.queryReceiveTaskComplete();
        if (CollectionUtil.isNotEmpty(list)) {
            for (FerryReceiveTaskEntity receiveTaskEntity : list) {
                log.info("摆渡完成回调，taskId：{}，requestId：{}", receiveTaskEntity.getFerryTaskId().toString(), receiveTaskEntity.getRequestId());
                //回调
                FerryDto callbackDto = new FerryDto();
                callbackDto.setFerry_accept_url(SendBoundaryUrlEnum.SEND_FERRY_COMPLETE_CALLBACK.getValue());
                callbackDto.setFerryTaskId(receiveTaskEntity.getFerryTaskId().toString());
                callbackDto.setFerryTaskResult(receiveTaskEntity.getReceiveResult());
                //调用边界服务接口
                sendRequestToBoundaryService.send(BeanUtil.beanToMap(callbackDto));

                receiveTaskEntity.setTaskStatus(FerryReceiveTaskStatusEnum.CALLBACK_COMPLETE.getCode());
                receiveTaskEntity.setUpdateTime(new Date());
                ferryReceiveTaskService.updateById(receiveTaskEntity);
            }
        }
        log.info("===================================查询接收任务状态-摆渡完成结束===================================");
    }

}
