package com.hh.hhomc.utils;

import static com.hh.hhomc.BuildConfig.BASE_URL;

import android.content.Context;
import android.text.TextUtils;

import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.utils.log.AppLogUtils;
import com.hh.hhomc.http.HttpManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Description:切片上传
 * @author xwh
 * time 2024/7/11
 **/
public class ChunkedUploadExample {

    private static String mTAG=ChunkedUploadExample.class.getName();
    private static final String UPLOAD_URL = BASE_URL+ "middle-management/api/v1/file/upload/chunk";
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/octet-stream");
    private static final int CHUNK_SIZE = 5 * 1024 * 1024; // 5MB chunks

    private static final String downLoadUrl = BASE_URL+ "middle-management/file/";


    /**
     * Description: 分片上传
     *
     * @author xwh
     * Time 2024/7/11
     **/
    public static String uploadFile(Context context, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            AppLogUtils.e("uploadFile--分片上传--filePath=" + filePath);
            return "";
        }
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] fileContent = new byte[(int) file.length()];
        try {
            String md5 = getFileMD5(file.getAbsolutePath());

            fis = new FileInputStream(file);
            // 读取文件内容到字节数组
            fis.read(fileContent);
            int fileSize = fileContent.length;//文件大小
            long chunkTotal = (fileSize + (CHUNK_SIZE - 1)) / CHUNK_SIZE; // 向上取整,切片总数
            int index = 1; //当前切片
            for (int offset = 0; offset < fileSize; offset += CHUNK_SIZE) {
                int length = Math.min(CHUNK_SIZE, fileSize - offset);
                // Create RequestBody for multipart
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("md5", md5)
                        .addFormDataPart("chunkSize", "" + CHUNK_SIZE)
                        .addFormDataPart("chunkTotal", "" + chunkTotal)
                        .addFormDataPart("fileSize", "" + fileSize)
                        .addFormDataPart("fileName", file.getName())
                        .addFormDataPart("index", "" + index)
                        .addFormDataPart("chunk", file.getName(),
                                RequestBody.create(MEDIA_TYPE, fileContent, offset, length))
                        .build();

                // Create Request
                Request request = new Request.Builder()
                        .url(UPLOAD_URL)
                        .header("Content-Range", "bytes "
                                + offset + "-" + (offset + length) + "/" + fileSize)
                        .post(requestBody)
                        .build();

                // Execute the request
                OkHttpClient client = HttpManager.getInstance(context).getmOkHttpClient();
                Response response = client.newCall(request).execute();
                if (index==chunkTotal&&response.isSuccessful()){


                }else if(!response.isSuccessful()){
                    throw new IOException("Unexpected code " + response);
                }
                // Handle response for each chunk
                //  System.out.println(response.body().string());
                index++;
            }

            AppLogUtils.i("_____________123" +
                    " 路径："+filePath+" "+"MD5:"+md5+" chunkSize:"+CHUNK_SIZE
                    +"  chunkTotal:"+chunkTotal+"    fileSize:"+fileSize+"   fileName:"+file.getName()
                    +"   index:"+index);

            return downLoadUrl+md5+".zip";
        } catch (IOException e) {
            AppLogUtils.e(mTAG+"--uploadFile--分片上传--IOException=" + e.getMessage());
        } catch (Exception e2) {
            AppLogUtils.e(mTAG+"--uploadFile--分片上传--Exception=" + e2.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    AppLogUtils.e(mTAG+"--uploadFile--分片上传--fis.close--IOException="
                            + e.getMessage());
                }
            }
            if(file!=null&&file.exists()) {
                file.delete();
            }
        }
        return "";
    }


    public static String getFileMD5(String filePath) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(filePath);
            byte[] dataBytes = new byte[1024];
            int nread;
            while ((nread = fis.read(dataBytes)) != -1) {
                md5.update(dataBytes, 0, nread);
            }
            ;
            byte[] mdbytes = md5.digest();
            //转换MD5摘要为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte mdbyte : mdbytes) {
                hexString.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
            }
            fis.close();
            return hexString.toString();
        } catch (IOException e) {
            AppLogUtils.e(mTAG+"--getFileMD5--IOException="
                    + e.getMessage());
            return null;
        } catch (OutOfMemoryError e) {
            AppLogUtils.e(mTAG+"--getFileMD5--OutOfMemoryError="
                    + e.getMessage());
            return null;
        } catch (Exception e) {
            AppLogUtils.e(mTAG+"--getFileMD5--Exception="
                    + e.getMessage());
            return null;
        }
    }

    public interface UploadFileListener{
        public void onSuccess(String re);
    }
   /* public static void main(String[] args) {
        try {
            uploadFile(cnew File("path_to_your_file"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}
