package com.zd.forward.utils;

import com.zd.common.core.exception.ServiceException;
import com.zd.forward.config.AlgorithmYml;
import com.zd.forward.domain.DataPostAnalysisRespDto;
import com.zd.forward.domain.ImgPostResponse;
import com.zd.forward.properties.FireProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author Administrator
 */
@Slf4j
public class HttpUtils {

    private HttpUtils() {
        throw new IllegalStateException("HttpUtils class");
    }

    /**
     * 构造算法文件逆流
     */
    public static HttpEntity<MultiValueMap<String, Object>> getHttpEntityMap(File file, MultiValueMap<String, Object> params) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //文件转为文件系统资源
        return getHttpEntity(file, params, headers);
    }

    private static HttpEntity<MultiValueMap<String, Object>> getHttpEntity(File file, MultiValueMap<String, Object> params, HttpHeaders headers) {
        //文件转为文件系统资源
        FileSystemResource fileSystemResource = new FileSystemResource(file);
        //设置请求体，注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = getStringObjectMultiValueMap(fileSystemResource);
        form.addAll(params);
        //用HttpEntity封装整个请求报文
        return new HttpEntity<>(form, headers);
    }

    public static File multipartFileToFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
        assert originalFilename!=null;
        String[] filename = originalFilename.split("\\.");
        File toFile = File.createTempFile(filename[0], "." + filename[1]);
        file.transferTo(toFile);
        log.info("================>{}",toFile.getAbsoluteFile());
        //toFile.deleteOnExit();//在jvm 退出时删除
        return toFile;
    }

    /**
     * 构建算法图片post请求 参数:只构建文件
     */
    public static MultiValueMap<String, Object> getStringObjectMultiValueMap(FileSystemResource fileSystemResource) {
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        return form;
    }

    private static MultiValueMap<String, Object> getStringObjectMultiValueMap(String extension) {
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        //1-同步（默认），0-异步
        form.add("sync", 1);
        form.add("timeStamp", LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000);
        form.add("extension", extension);
        return form;
    }

    /**
     * 构建算法图片post请求 参数
     */
    public static MultiValueMap<String, Object> getStringObjectMultiValueMap(AlgorithmYml.CheckValid checkValid, String extension) {
        MultiValueMap<String, Object> form = getStringObjectMultiValueMap(extension);
        form.add("algoId", checkValid.getAlgoId());
        form.add("did", checkValid.getDid());
        return form;
    }

    /**
     * 构建算法图片post请求 参数
     */
    public static MultiValueMap<String, Object> getMultiValueMap(FireProperties properties, String extension) {
        MultiValueMap<String, Object> form = getStringObjectMultiValueMap(extension);
        form.add("algoId", properties.getAlgoId());
        form.add("did", properties.getDid());
        return form;
    }

    public static ImgPostResponse<DataPostAnalysisRespDto> send(RestTemplate restTemplate, HttpEntity<MultiValueMap<String, Object>> files, AlgorithmYml algorithmYml) {
        ParameterizedTypeReference<ImgPostResponse<DataPostAnalysisRespDto>> reference = new ParameterizedTypeReference<ImgPostResponse<DataPostAnalysisRespDto>>() {
        };
        ResponseEntity<ImgPostResponse<DataPostAnalysisRespDto>> response = restTemplate.exchange(algorithmYml.getImgPostUrl(), HttpMethod.POST, files, reference);
        if (response.getStatusCode() != HttpStatus.OK) {
            log.error("算法服务请求异常，请查看算服务器");
        }
        if (response.getBody() == null) {
            log.error("算法服务接口返回异常");
        }
        return response.getBody();
    }
}
