package com.docus.server.archive.rpc.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.server.archive.config.DocusServerUrlConfig;
import com.docus.server.archive.rpc.DownPlatformService;
import com.docus.server.archive.rpc.dto.ReportDownDto;
import com.docus.server.archive.rpc.dto.ReportDownScanFileDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 下载平台服务接口
 *
 * @author jiashi
 */
@Component
@Slf4j
public class DownPlatformServiceImpl implements DownPlatformService {

    @Resource
    private DocusServerUrlConfig serverUrlConfig;

    @Override
    public CommonResult report(ReportDownDto reportDownDto) {
        String downUrl = serverUrlConfig.getDownloadPlatformServerUrl() + "api/downplatform/report";
        String requestId = Func.randomUUID();
        String requestParam = Func.toJson(reportDownDto);
        ReportDownScanFileDto report = reportDownDto.getScanfiles().get(0);
        log.info("[{}]调用下载服务，地址：{} ，参数：taskid={}", requestId, downUrl, report.getTaskid());
        String respBody = post(downUrl, requestParam);
        log.info("[{}]调用下载服务成功,响应参数：{}", requestId, respBody);
        return Func.readJson(respBody, CommonResult.class);
    }

    public String post(String url, String body) {
        HttpRequest post = HttpUtil.createPost(url);
        post.setConnectionTimeout(5 * 1000);
        post.setReadTimeout(60 * 1000);
        post.header("Content-Type", "application/json; charset=utf-8");
        post.body(body);
        HttpResponse response = post.execute();
        return response.body();

    }
}
