package com.hz.pm.api.provincial.manage;

import com.alibaba.fastjson.JSON;
import com.ningdatech.basic.exception.BizException;
import com.hz.pm.api.common.util.CommonInputStreamResource;
import com.hz.pm.api.provincial.contants.ProvincialContant;
import com.hz.pm.api.provincial.model.res.OssApiData;
import com.hz.pm.api.provincial.model.res.OssApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.ByteArrayInputStream;
import java.util.Objects;

/**
 * @Classname ProvincialManage
 * @Description
 * @Date 2023/9/6 9:08
 * @Author PoffyZhang
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ProvincialManage {

    public static String uploadToOss(byte[] fileBytes,String fileName) {
        String url = ProvincialContant.OssUpload.OSS_UPLOAD_URL;
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
        CommonInputStreamResource commonInputStreamResource = new CommonInputStreamResource(inputStream, fileBytes.length, fileName);
        params.add("file", commonInputStreamResource);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(ProvincialContant.OssUpload.MEDIA_TYPE);
        headers.setContentType(type);
        HttpEntity<MultiValueMap> formEntity = new HttpEntity(params, headers);
        ResponseEntity<OssApiResponse> res = restTemplate.postForEntity(url, formEntity, OssApiResponse.class);
        log.info("oss res :{}", res);
        OssApiResponse body = res.getBody();
        if(Objects.isNull(body)){
            throw new BizException("上传省局oss请求失败");
        }

        if(HttpStatus.OK.value() != body.getRespCode()){
            throw new BizException("上传省局oss失败:" + body.getRespMsg());
        }

        OssApiData ossApiData = JSON.parseObject(JSON.toJSONString(body.getData()), OssApiData.class);

        return ossApiData.getAccessUrl();
    }
}
