package com.example.chemical.utils

import okhttp3.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object FileDownloader {
    private val client: OkHttpClient = OkHttpClient()

    interface ProgressListener {
        fun onProgress(progress: Int)
    }

    fun downloadFile(url: String, savePath: String, fileName: String, listener: ProgressListener? = null) {
        val request: Request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 下载失败处理逻辑
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                if (!response.isSuccessful) {
                    // 下载失败处理逻辑
                    throw IOException("Unexpected code $response")
                }

                val fileDir = File(savePath)
                if (!fileDir.exists()) {
                    fileDir.mkdirs()
                }

                val filePath = "$savePath/$fileName"
                val file = File(filePath)
                val outputStream = FileOutputStream(file)
                val inputStream = response.body()?.byteStream()

                inputStream?.use { input ->
                    outputStream.use { output ->
                        val buffer = ByteArray(4096)
                        var totalBytesRead: Long = 0
                        var bytesRead: Int
                        while (input.read(buffer).also { bytesRead = it } != -1) {
                            output.write(buffer, 0, bytesRead)
                            totalBytesRead += bytesRead
                            listener?.onProgress((totalBytesRead * 100 / response.body()!!.contentLength()).toInt())
                        }
                        output.flush()
                    }
                }

                response.body()?.close()

                // 下载完成后的处理逻辑
            }
        })
    }
}