package com.bcxin.ferry.service;


import com.alibaba.fastjson.JSONObject;
import com.bcxin.ferry.common.utils.HttpUtil;
import com.bcxin.ferry.configs.BaiduutilServerConfig;
import com.bcxin.ferry.dtos.baiduutil.ChangeLogsRequestDto;
import com.bcxin.ferry.dtos.baiduutil.FerryReceiveTaskPushResult;
import com.bcxin.ferry.dtos.baiduutil.FerryTaskPullResult;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import com.bcxin.ferry.entity.FerryTaskEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * description：重试服务
 * author：linchunpeng
 * date：2024/3/11
 */
@Slf4j
@Service
public class RetryService {

    @Autowired
    private BaiduutilServerConfig baiduutilServerConfig;
    @Value("${spring.profiles.active}")
    private String activeFile;


    /**
     * description：调用摆渡工具服务，拉取数据
     * 重试策略：重试3次，第一次10秒，第二次20秒，第三次40秒
     * author：linchunpeng
     * date：2024/3/11
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 10000, maxDelay=60000, multiplier = 2))
    public ChangeLogsRequestDto postToBaiduutilServerPull(FerryTaskEntity ferryTaskEntity) {
        ChangeLogsRequestDto requestDto = new ChangeLogsRequestDto();
        requestDto.setFromTime(ferryTaskEntity.getStartTime());
        requestDto.setEndTime(ferryTaskEntity.getEndTime());
        requestDto.setRegionCodes(ferryTaskEntity.getRegionCode());
        requestDto.setTables(new ArrayList<>());
        requestDto.setAutoFerryTaskId(ferryTaskEntity.getId());
        requestDto.setNeedServerTimeCheck(true);
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(ferryTaskEntity.getRegionCode()).getPullUrl(), JSONObject.toJSONString(requestDto));
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("code") == null || result.getInteger("code") != 200) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        if (!"调用成功".equals(result.getString("message"))) {
            String messageStr = result.getString("message");
            if (messageStr == null) {
                log.error("调用摆渡工具服务接口失败，message字段为null");
                throw new RuntimeException("调用摆渡工具服务接口失败，message字段为null");
            }
            try {
                ChangeLogsRequestDto message = JSONObject.parseObject(messageStr, ChangeLogsRequestDto.class);
                return message;
            } catch (Exception e) {
                log.error("调用摆渡工具服务接口失败，message不是json格式: {}", messageStr, e);
                throw new RuntimeException("调用摆渡工具服务接口失败，message不是json格式");
            }
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");
        return null;
    }


    /**
     * description：调用摆渡工具服务，推送数据
     * 重试策略：重试3次，第一次10秒，第二次20秒，第三次40秒
     * author：linchunpeng
     * date：2024/3/11
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 10000, maxDelay=60000, multiplier = 2))
    public void postToBaiduutilServerPush(FerryReceiveTaskEntity receiveTaskEntity) {
        String regionCode = "";
        if (activeFile.contains("out") && receiveTaskEntity.getRequestId().contains("zw")) {
            regionCode = "govout-to-govin";
        }
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(regionCode).getPushUrl().concat(receiveTaskEntity.getRequestId()).concat("?isNeedUnzip=true"), "{}");
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("code") == null || result.getInteger("code") != 200) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");
    }


    /**
     * description：调用摆渡工具服务，查询北京自动摆渡拉取结果
     * author：linchunpeng
     * date：2024/6/17
     */
    public FerryTaskPullResult postToBaiduutilServerPullResult(FerryTaskEntity ferryTaskEntity) {
        ChangeLogsRequestDto requestDto = new ChangeLogsRequestDto();
        requestDto.setAutoFerryTaskId(ferryTaskEntity.getId());
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(ferryTaskEntity.getRegionCode()).getPullQueryResultUrl(), JSONObject.toJSONString(requestDto));
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("id") == null) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");

        return JSONObject.parseObject(pullResult, FerryTaskPullResult.class);
    }


    /**
     * description：调用摆渡工具服务，查询北京自动摆渡推送结果
     * author：linchunpeng
     * date：2024/6/17
     */
    public FerryReceiveTaskPushResult postToBaiduutilServerPushResult(FerryReceiveTaskEntity receiveTaskEntity) {
        String regionCode = "";
        if (activeFile.contains("out") && receiveTaskEntity.getRequestId().contains("zw")) {
            regionCode = "govout-to-govin";
        }
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(regionCode).getPushQueryResultUrl().concat(receiveTaskEntity.getRequestId()), "{}");
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("requestId") == null) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            throw new RuntimeException("调用摆渡工具服务接口失败");
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");

        return JSONObject.parseObject(pullResult, FerryReceiveTaskPushResult.class);
    }
}
