package com.lukouguoji.module_base.util

import com.lukouguoji.module_base.http.net.Api
import com.lukouguoji.module_base.http.net.ProgressInterceptor
import com.lukouguoji.module_base.http.user.SelfLoginInterceptor
import com.lukouguoji.module_base.ktx.loge
import dev.utils.common.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.io.File
import java.util.concurrent.TimeUnit

object DownloadUtil {

    private const val timeout = 999999999L

    private val api by lazy {
        Retrofit.Builder()
            .client(
                OkHttpClient.Builder()
                    .addInterceptor(SelfLoginInterceptor)
                    .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                    .readTimeout(timeout, TimeUnit.MILLISECONDS)
                    .callTimeout(timeout, TimeUnit.MILLISECONDS)
                    .addInterceptor(ProgressInterceptor() { url, _, _, progress ->
                        map[url]?.invoke(progress)
                    })
                    .build()
            )
            .baseUrl(Api.BASE_URL)
            .build()
            .create(Api::class.java)
    }

    private val map = HashMap<String, (progress: Int) -> Unit>()

    //下载
    suspend fun download(
        url: String,
        outputFile: String,
        onProgress: (progress: Int) -> Unit = {},
        onSuccess: (file: File) -> Unit = {},
        onError: (message: String) -> Unit = {},
    ) {
        try {
            map[url] = onProgress
            val body = api.download(url)
            val file = File(outputFile)
            withContext(Dispatchers.IO) {
                val saveFile = FileUtils.saveFile(file, body.bytes())
                loge("保存文件成功与否  $saveFile : ${file.path}")
            }
            map.remove(url)
            onSuccess(file)
        } catch (e: Exception) {
            map.remove(url)
            onError(e.message ?: "下载失败:${e::class.java.simpleName}")
        }
    }
}