package com.hz.pm.api.external;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hz.pm.api.external.model.dto.MhFileInfoDTO;
import com.hz.pm.api.external.model.dto.MhRetDTO;
import com.ningdatech.basic.exception.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * MhFileClient
 * </p>
 *
 * @author WendyYang
 * @since 20:24 2023/12/28
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MhFileClient {

    private static final int TIMEOUT_MILLS = 5000;

    @Value("${mh.file.down-url:}")
    private String fileDownUrl;

    @Value("${mh.file.detail-url:}")
    private String fileDetailUrl;

    public void download(String fileId, HttpServletResponse response) {
        String fileUrl = fileDownUrl + "/" + fileId;
        try (ServletOutputStream stream = response.getOutputStream()) {
            long size = HttpUtil.download(fileUrl, stream, true);
            log.info("下载文件：{}，大小为：{}", fileId, size);
        } catch (IOException e) {
            log.error("信创平台文件下载异常：{}", fileId, e);
            throw BizException.wrap("下载文件失败");
        }
    }

    public List<MhFileInfoDTO> listFileInfo(String fileIds) {
        String url = fileDetailUrl + "?ids=" + fileIds;
        String body = HttpUtil.get(url, TIMEOUT_MILLS);
        MhRetDTO<List<MhFileInfoDTO>> ret = JSONUtil.toBean(body,
                new TypeReference<MhRetDTO<List<MhFileInfoDTO>>>() {
                }, false);
        if (ret.isOk()) {
            return ret.getData();
        }
        throw BizException.wrap("获取文件详情");
    }

}
