package com.bcxin.ferry.service;


import com.alibaba.fastjson.JSONObject;
import com.bcxin.ferry.common.utils.Base64Util;
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.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 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 void 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());
        boolean isZw = ferryTaskEntity.getRegionCode().equals("govout-to-govin");
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(isZw).getPullUrl(), JSONObject.toJSONString(requestDto));
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("code") == null || result.getInteger("code") != 200) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");
    }


    /**
     * 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 isNeedUnzip = "?isNeedUnzip=false";
        if ("out-prod".equals(activeFile)) {
            //外网还是要解压的
            isNeedUnzip = "?isNeedUnzip=true";
        }
        boolean isZw = receiveTaskEntity.getIsPushZw() != null && receiveTaskEntity.getIsPushZw() == 1;
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(isZw).getPushUrl().concat(receiveTaskEntity.getRequestId()).concat(isNeedUnzip), "{}");
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("code") == null || result.getInteger("code") != 200) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");
    }


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

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

    /**
     * description：调用摆渡工具服务，查询北京自动摆渡推送结果
     * author：linchunpeng
     * date：2024/6/17
     */
    public FerryReceiveTaskPushResult postToBaiduutilServerPushResult(FerryReceiveTaskEntity receiveTaskEntity) {
        boolean isZw = receiveTaskEntity.getIsPushZw() != null && receiveTaskEntity.getIsPushZw() == 1;
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(isZw).getPushQueryResultUrl().concat(receiveTaskEntity.getRequestId()), "{}");
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            return null;
        }
        JSONObject result = JSONObject.parseObject(pullResult);
        if (result.get("requestId") == null) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            return null;
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");

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

    /**
     * description：调用摆渡工具服务，上传摆渡包文件
     * author：linchunpeng
     * date：2024/9/19
     */
    public boolean postToBaiduutilServerUploadFile(FerryReceiveTaskEntity receiveTaskEntity, File file) {
        Map<String, Object> param = new HashMap<>();
        param.put("fileBase64", Base64Util.fileToBase64(file, false));
        param.put("requestId", receiveTaskEntity.getRequestId());
        boolean isZw = receiveTaskEntity.getIsPushZw() != null && receiveTaskEntity.getIsPushZw() == 1;
        String pullResult = HttpUtil.post(baiduutilServerConfig.getRequestApi(isZw).getPushUploadUrl(), JSONObject.toJSONString(param));
        if ("fail".equals(pullResult)) {
            //调用摆渡工具服务接口失败
            log.error("调用摆渡工具服务接口失败");
            return false;
        }
        //调用摆渡工具服务接口成功
        log.info("调用摆渡工具服务接口成功");

        return true;
    }
}
