package com.jld.vod.utils.http;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/8/19 10:55
 */

public class RetrofitFileUtils {


    /**
     * 上传单个文件
     * @param fileName
     * @param file 为参数字段名
     * @return
     */
    public static MultipartBody.Part uploadFile(String fileName,File file){
//        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), file); 过时
        RequestBody requestBody = getRequestBody(file);
        MultipartBody.Part part = MultipartBody.Part.createFormData(fileName, file.getName(), requestBody);

        return part;
    }



    public static RequestBody getRequestBody(File file){
        MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8");
        RequestBody fileBody=RequestBody.Companion.create(file,mediaType);

        return fileBody;
    }


    /**
     * 上传多个文件
     * @param files
     * @return
     */
    public static List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
//            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), file);
            RequestBody requestBody = getRequestBody(file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFiles", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }


    /**
     * 请求参数转化为RequestBody
     * @param value
     * @return
     */
    public static RequestBody toRequestBody(String value) {
//        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.Companion.create(value,mediaType);
        return requestBody;
    }


}
