package com.hh.lib_device.utils;

import android.os.Environment;
import android.text.TextUtils;

import com.blankj.utilcode.util.FileUtils;
import com.hh.lib_device.bean.DownloadFileStatusEnum;
import com.hh.lib_device.bean.action.AmpeResultDownloadFileBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Description: $ 下载保存文件
 * @author xwh
 * time 2024/11/25
 **/
public class DownloadFileUtils {

    private static volatile DownloadFileUtils instance = null;

    private volatile OkHttpClient okHttpClient;

    private  String rootFilePath= "";

    private volatile Call requestCall;

    private volatile DownloadFileStatusEnum statusEnum= DownloadFileStatusEnum.FREE;
    private volatile String currentSaveFileName="";

    public DownloadFileUtils() {
        File rootFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (rootFile != null && rootFile.exists()) {
            rootFilePath = rootFile.getAbsolutePath();
        }
    }

    public synchronized void downLoadFile(String url, String savePathName, DownloadFileListener downloadFileListener){
        if(isDownloading()){
            if(downloadFileListener!=null){
                downloadFileListener.saveFailed(-10,"当前正在保存"+ currentSaveFileName );
            }
            return;
        }
        if(TextUtils.isEmpty(url)||TextUtils.isEmpty(savePathName) || TextUtils.isEmpty(rootFilePath)){
            StringBuffer stringBuffer=new StringBuffer();
            if(TextUtils.isEmpty(url)){
                stringBuffer.append("url为空 ");
            }
            if(TextUtils.isEmpty(savePathName)){
                stringBuffer.append(" 文件名为空 ");
            }
            if(TextUtils.isEmpty(rootFilePath)){
                stringBuffer.append(" 根目录为空 ");
            }
            if(downloadFileListener!=null){
                downloadFileListener.saveFailed(-11,stringBuffer.toString());
            }
            return;
        }

        statusEnum = DownloadFileStatusEnum.DOWNLOADING;
        currentSaveFileName = savePathName;
        OkHttpClient client = getOkHttpClient();
        Request request = new Request.Builder()
                .url(url) // 替换为你的文件URL
                .build();
        try {
            if (requestCall != null) {
                requestCall.cancel();
                requestCall = null;
            }
        }catch (Exception er){}
        requestCall = client.newCall(request);
        requestCall .enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理失败情况
                reset();
                if(downloadFileListener!=null){
                    downloadFileListener.saveFailed(-12,e.toString());
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (!response.isSuccessful()) {
                    reset();
                    if(downloadFileListener!=null){
                        downloadFileListener.saveFailed(-13,"Unexpected code " + response);
                    }
                    return;
                }


                File file = new File(rootFilePath, savePathName); // 替换为你想要的文件名

                // 写入文件
                try (ResponseBody body = response.body();
                     OutputStream outputStream = new FileOutputStream(file)) {
                    byte[] buffer = new byte[2048];
                    long fileSize = response.body().contentLength();
                    long fileSizeDownloaded = 0;
                    int count;
                    while ((count = body.source().read(buffer)) != -1) {
                        outputStream.write(buffer, 0, count);
                        outputStream.flush();
                        fileSizeDownloaded += count;
                        // 这里可以添加下载进度更新的代码
                      /*  Log.i("___________123","Downloadeding:"+"当前下载："+fileSizeDownloaded
                                +"总量："+fileSize+"   "+String.format("%.2f", (float)fileSizeDownloaded/(float)fileSize));*/
                    }
                    // 文件下载完成
                    if(downloadFileListener!=null){
                        AmpeResultDownloadFileBean data=new AmpeResultDownloadFileBean();
                        data.setFileName(file.getName());
                        data.setFileType(getFileExtension(file));
                        data.setPath(file.getAbsolutePath());
                        downloadFileListener.saveSuccess(data);
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    // 处理异常
                    if(downloadFileListener!=null){
                        downloadFileListener.saveFailed(-14,e.toString());
                    }
                }finally {
                    reset();
                }
            }
        });

    }


    /**
     *
     * @author xwh
     * Time 2024/11/25
     * Description: 是否下载中....
     *
    **/
    public boolean isDownloading(){
        return statusEnum == DownloadFileStatusEnum.DOWNLOADING ;
    }

    /**
     *
     * @author xwh
     * Time 2024/11/27
     * Description: 删除文件
     * @param removePath 需要删除文件的绝对地址
     *
    **/
    public boolean deleteFile(String removePath) {
        String path = removePath;
        if(TextUtils.isEmpty(removePath)){
            return false;
        }
        File removeFile = new File(path);
        if(!removeFile.exists()){
            return true; //文件不存在，默认就是已经被删除了。
        }
        return FileUtils.delete(removeFile);
    }

    /**
     *
     * @author xwh
     * Time 2024/11/27
     * Description: 返回文件列表
     *
    **/
    public ArrayList<AmpeResultDownloadFileBean> getFileList(){
        ArrayList<AmpeResultDownloadFileBean> pathList = new ArrayList<>();
        if(TextUtils.isEmpty(rootFilePath)){
            return pathList;
        }
        File file = new File(rootFilePath);
        if(file==null|| !file.exists()){
            return pathList;
        }
        File[] files = file.listFiles();
        if (files != null) {
            for (File logFile : files) {
                if (logFile == null || !logFile.exists()) {
                    continue;
                }
                AmpeResultDownloadFileBean data=new AmpeResultDownloadFileBean();
                data.setFileName(logFile.getName());
                data.setFileType(getFileExtension(logFile));
                data.setPath(logFile.getAbsolutePath());
                pathList.add(data);
            }
        }
        return pathList;
    }


    /**
     *
     * @author xwh
     * Time 2024/11/27
     * Description: 重置状态，当有任务的时候，取消任务
     *
    **/
    private void reset(){
        statusEnum = DownloadFileStatusEnum.FREE;
        currentSaveFileName = "";
        try {
            if (requestCall != null) {
                requestCall.cancel();
                requestCall = null;
            }
        }catch (Exception er){

        }
    }


    public static String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf('.');
        if (lastIndexOf > 0 && lastIndexOf < name.length() - 1) {
            return name.substring(lastIndexOf + 1);
        } else {
            return "";
        }
    }


    private OkHttpClient getOkHttpClient() {
        if(okHttpClient==null){
            synchronized (DownloadFileUtils.class){
                if(okHttpClient == null){
                    okHttpClient = initOkhttp();
                }
            }
        }
        return okHttpClient;
    }

    private OkHttpClient initOkhttp(){

        return new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .writeTimeout(10000L, TimeUnit.MILLISECONDS).build();
    }

    public static DownloadFileUtils getInstance() {
        if (instance == null) {
            synchronized (DownloadFileUtils.class) {
                if (instance == null) {
                    instance = new DownloadFileUtils();
                }
            }
        }
        return instance;
    }

    public void release() {
        reset();
        instance = null;

    }

    public interface DownloadFileListener{

        void saveSuccess( AmpeResultDownloadFileBean data);
        void saveFailed(int code,String errMsg);

    }
}
