package com.lukouguoji.module_base.update

import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import com.lukouguoji.module_base.bean.AppUpdateResponseInfo
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.Api
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.logd
import java.io.File

class UploadUtil {
    private var downloadManager: DownloadManager? = null
    private var downloadFile:File?=null

    fun init(activity: Activity){
        downloadManager = DownloadManager(activity, NotificationUtil(activity))
    }

    suspend fun getAppUpdate(versionCode: Int, updateCallback: (updateInfo: AppUpdateResponseInfo?)->Unit ) {
        logd("==================调用APP升级==================")
        try {
            NetApply.api.getAppUpdate(versionCode)?.let {
                if(it.success){
                    it.data.let { info ->
                        if (info != null) {
                            logd("==================调用APP升级 需要升级==================")
                            updateCallback.invoke(info)
                        }else{
                            logd("==================调用APP升级 不需要升级==================")
                        }
                    }
                }else{
                    updateCallback.invoke(null)
                }
            }
        } catch (e: Exception) {
            logd("==================调用APP升级 请求异常 $e==================")
            updateCallback.invoke(null)
        }
    }

    fun startDownload(activity: Activity, updateInfo: AppUpdateResponseInfo, progressCallback:(progress: Int)->Unit = {}, onErrorCallback: (error: String)->Unit = {}) {
        downloadManager?.downloadFile(
            url = Api.BASE_URL + updateInfo.downloadAddress,
//            url = updateInfo.downloadAddress,
            fileName = "V${updateInfo.versionNo}",
            onProgress = { progress ->
                if(progressCallback!=null){
                    progressCallback?.invoke(progress)
                }
            },
            onComplete = { file ->
                downloadFile = file
                installApk(activity, file)
            },
            onError = { error ->
                onErrorCallback.invoke(error)
            }
        )
    }

    fun installApk(activity: Activity) {
        downloadFile?.let {
            installApk(activity, it)
        }
    }

    private fun installApk(activity: Activity,file: File) {
        try {
            val installIntent = Intent(Intent.ACTION_VIEW).apply {
                val uri = FileProvider.getUriForFile(
                    activity,
                    "${activity.packageName}.fileprovider",
                    file
                )
                setDataAndType(uri, "application/vnd.android.package-archive")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            activity.startActivity(installIntent)
        } catch (e: Exception) {
            Toast.makeText(activity.applicationContext, "安装失败: ${e.localizedMessage}", Toast.LENGTH_SHORT).show()
        }
    }

    fun cancelDownload(){
        downloadManager?.cancelDownload()
    }

}