package com.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.file.ImageUtils;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadToServer {

    //通用上传请求（单个）
    public static Map upload(String serverAddress, String port,MultipartFile file) {
        File toFile = transferToFile(file);
        Map data = new HashMap();
        data.put("file", toFile);
        data.put("attachType", file.getContentType());
        String body = HttpRequest.post(serverAddress+":"+port+"/common/upload")
                .form(data)
                .contentType("multipart/form-data")
                .execute()
                .body();
        Map result = new HashMap();
        if (StrUtil.isNotBlank(body)) {
            result = JSON.parseObject(body, Map.class);
        }
        return result;
    }

    //用户签名
    public static Map uploadSign(String serverAddress, String port,MultipartFile file) {
        File toFile = transferToFile(file);
        Map data = new HashMap();
        data.put("file", toFile);
        data.put("attachType", file.getContentType());
        String body = HttpRequest.post(serverAddress+":"+port+"/common/sign")
                .form(data)
                .contentType("multipart/form-data")
                .execute()
                .body();
        Map result = new HashMap();
        if (StrUtil.isNotBlank(body)) {
            result = JSON.parseObject(body, Map.class);
        }
        //return R.ok().put("data", result);
        return result;
    }

    //用户头像
    public static Map uploadAvatar(String serverAddress,MultipartFile file) {
        File toFile = transferToFile(file);
        Map data = new HashMap();
        data.put("file", toFile);
        data.put("attachType", file.getContentType());
        String body = HttpRequest.post(serverAddress+"/common/avatar")
                .form(data)
                .contentType("multipart/form-data")
                .execute()
                .body();
        Map result = new HashMap();
        if (StrUtil.isNotBlank(body)) {
            result = JSON.parseObject(body, Map.class);
        }
        return result;
    }

    //故障图片
    public static Map uploadFailure(String serverAddress, MultipartFile file) {
        File toFile = transferToFile(file);
        Map data = new HashMap();
        data.put("file", toFile);
        data.put("attachType", file.getContentType());
        String body = HttpRequest.post(serverAddress+"/common/failure")
                .form(data)
                .contentType("multipart/form-data")
                .execute()
                .body();
        Map result = new HashMap();
        if (StrUtil.isNotBlank(body)) {
            result = JSON.parseObject(body, Map.class);
        }
        return result;
    }

    //获取服务器图片二进制
    public static String getPicFromServer(String serverAddress,String url) throws UnsupportedEncodingException {
        String result = "data:image/jpeg;base64,";
        //取出图片保存路径（不包含文件名，也就是取出最后一个”/“之前的内容）
        String photoUrl = url.substring(0,url.lastIndexOf("/"));
        //取出图片名称
        String name = url.substring(url.lastIndexOf("/") + 1);
        //对文件名进行编码
        name = URLEncoder.encode(name,"utf-8");
        url = serverAddress + photoUrl + "/" + name;
        byte[] b = ImageUtils.readFile(url);
        return result + Base64.encodeBase64String(b);
    }

    public static File transferToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            //originalFilename获取文件名类型，比如abc.jap
            String originalFilename = multipartFile.getOriginalFilename();
            //获取纯文件名，比如abc
            String name = originalFilename.substring(0,originalFilename.lastIndexOf("."));
            if(name.length() < 3){
                throw new ServiceException("文件名称过于简短，请检查后重新上传");
            }
            //获取文件后缀,比如.jpg
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));

            file = File.createTempFile(name, prefix);    //创建临时文件，命名有问题，待解决
            multipartFile.transferTo(file);
            //删除
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}
