package com.bcxin.ferry.service;


import com.alibaba.fastjson.JSONObject;
import com.bcxin.ferry.common.utils.HttpUtil;
import com.bcxin.ferry.configs.BoundaryServerConfig;
import com.bcxin.ferry.dtos.response.boundary.BoundaryResult;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * description：发送边界服务
 * author：linchunpeng
 * date：2024/3/11
 */
@Slf4j
@Service
public class SendRequestToBoundaryService {

    @Autowired
    private BoundaryServerConfig boundaryServerConfig;
    @Autowired
    private FerryRequestLogService ferryRequestLogService;

    /**
     * description：发送请求到边界服务
     * author：linchunpeng
     * date：2024/3/18
     */
    @Retryable(value = Exception.class, maxAttempts = 10, backoff = @Backoff(delay = 5000L, maxDelay = 60000L, multiplier = 2))
    public BoundaryResult send(Map<String, Object> paramMap) {
        //一秒限制次数
        RateLimiter limiter = RateLimiter.create(10); // 每秒10个令牌
        limiter.acquire();//取令牌
        //执行发送请求
        String paramJson = JSONObject.toJSONString(paramMap);
        log.info("发送请求到边界服务");
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("role_code", boundaryServerConfig.getRoleCode());
        //创建请求日志
//        Long logId = ferryRequestLogService.createLog(paramMap.get("ferryTaskId"), paramMap.get("fileId"), paramMap.get("ferry_accept_url"), paramJson);
        String postResult = HttpUtil.post(boundaryServerConfig.getApi().getSendUrl(), paramJson, headerMap);
        if ("fail".equals(postResult)) {
            //调用边界服务接口失败
            log.error("调用边界服务接口失败");
            throw new RuntimeException("调用边界服务接口失败");
        }
        BoundaryResult result = JSONObject.parseObject(postResult, BoundaryResult.class);
        log.info("发送请求到边界服务成功，返回值：{}", postResult);
        //更新请求日志
        String boundaryTaskId = null;
        if (result.getStatus_code().equals("0")) {
            boundaryTaskId = result.getData().get(0).getTask_id();
        } else {
            //调用边界服务接口失败
            log.error("调用边界服务接口失败");
            throw new RuntimeException("调用边界服务接口失败");
        }
//        ferryRequestLogService.updateLogRequestResult(logId, postResult, boundaryTaskId);
        return result;
    }

}
