package com.docus.server.report.api.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.report.api.DownPlatformService;
import com.docus.server.report.api.dto.ReportDownDto;
import com.docus.server.report.config.ApplicationBusinessConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

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

    @Override
    public CommonResult report(ReportDownDto reportDownDto) {
        String downUrl = applicationBusinessConfig.getDownUrl();
        if (Func.isBlank(downUrl)) {
            log.warn("文件上报地址未配置！");
            return null;
        }
        String requestId = Func.randomUUID();
        String requestParam = Func.toJson(reportDownDto);
        try {
            log.info("[{}]调用下载服务，地址：{} ，参数：{}", requestId, downUrl, requestParam);
            String respBody = post(downUrl, requestParam);
            log.info("[{}]调用下载服务成功,响应参数：{}", requestId, respBody);
            return Func.readJson(respBody, CommonResult.class);
        } catch (Exception ex) {
            log.error("[" + requestId + "]调用下载服务失败" + ex.getMessage(), ex);
            return CommonResult.failed(ex.getMessage());
        }

    }

    /**
     * 文件上报加锁
     */
    private final static Lock REPORT_LOCK = new ReentrantLock();

    public String post(String url, String body) {
        REPORT_LOCK.lock();
        try {
            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();
        }finally {
            REPORT_LOCK.unlock();
        }
    }
}
