package com.abbidot.tracker.vm

import android.app.DownloadManager
import android.content.Context
import android.content.Context.DOWNLOAD_SERVICE
import android.net.Uri
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.bean.DFUStateBean
import com.abbidot.tracker.util.FileUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import androidx.core.net.toUri


/**
 *Created  by .yzq on 2023/3/22/022.
 * @link
 * @description:通知中心显示下载文件
 */
class DownLoadFileViewModel : ViewModel() {

    val mDownloadProgressLiveData = MutableLiveData<DFUStateBean>()
    private var mDownloadManager: DownloadManager? = null
    private var mDownloadId: Long = 0L
    private var isLoop = true

    fun downLoadFile(context: Context, fileName: String, downloadUrl: String) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return
        }
        //获取缓存的file目录context.getExternalFilesDir()
        val file = File(context.getExternalFilesDir(FileUtil.DFU_DIRECTORY_NAME), fileName)
        //文件存在就删除
        if (file.exists()) {
            file.delete()
        }
        mDownloadManager = context.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
        val uri = downloadUrl.toUri()
        val request = DownloadManager.Request(uri)
        //设置文件类型
        request.setMimeType("zip/*")
        //在通知栏中显示
        //在下载进行中时显示，在下载完成后就不显示了。可以设置如下三个值：
        //        VISIBILITY_HIDDEN 下载UI不会显示，也不会显示在通知中，如果设置该值，需要声明android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
        //        VISIBILITY_VISIBLE 当处于下载中状态时，可以在通知栏中显示；当下载完成后，通知栏中不显示
        //        VISIBILITY_VISIBLE_NOTIFY_COMPLETED 当处于下载中状态和下载完成时状态，均在通知栏中显示
        //        VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION 只在下载完成时显示在通知栏中。
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
        request.setTitle(fileName)
        request.setDescription("正在下载")

        //设置为可被媒体扫描器找到
//         request.allowScanningByMediaScanner()
        //设置公共目录，希望被其他的应用共享，比如音乐文件
//        request. setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName)

        //设置自定义目录,软件卸载后，下载的文件将随着卸载全部被删除
        request.setDestinationInExternalFilesDir(context, FileUtil.DFU_DIRECTORY_NAME, fileName)

        //注册广播，监听下载状态
//        mIntentFilter = IntentFilter()
//        mIntentFilter!!.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
//        mIntentFilter!!.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED)
//        context.registerReceiver(receiver, mIntentFilter)

        // 将下载请求放入队列
        mDownloadId = mDownloadManager!!.enqueue(request)
        isLoop = true
        updateProgress(context)
    }

    private fun updateProgress(context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            while (isLoop) {
                val query = DownloadManager.Query()
                val cursor = mDownloadManager!!.query(query.setFilterById(mDownloadId))
                if (cursor.moveToFirst()) {
                    var path = ""
                    val bytesDownloaded = cursor.getFloat(
                        cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
                    )
                    val bytesTotal = cursor.getFloat(
                        cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
                    )
                    val progress = (bytesDownloaded / bytesTotal) * 100
                    LogUtil.d("下载进度 bytesDownloaded=$bytesDownloaded 总文件大小：bytesTotal=$bytesTotal")
                    LogUtil.d(">>>下载进度$progress")
                    val columnStatus =
                        cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    if (columnStatus == DownloadManager.STATUS_SUCCESSFUL) {
                        // 成功后取消循环
                        isLoop = false
                        val localUri = cursor.getString(
                            cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)
                        )
                        val uri = Uri.parse(localUri)
                        LogUtil.i(localUri)
                        path = uri.path.toString()
                        LogUtil.i(path)
                    }
                    val dfuStateBean = DFUStateBean(
                        context.getString(R.string.txt_down_firmware), progress.toInt(), path
                    )
                    mDownloadProgressLiveData.postValue(dfuStateBean)
                }
                cursor.close()
                //延时循环
                delay(500)
            }
        }
    }

    /**
     * 广播接受者，接收下载状态
     */
//    private val receiver = object : BroadcastReceiver() {
//        override fun onReceive(context: Context, intent: Intent) {
//            val action = intent.action
//            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
//                val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0)
//                //检查下载状态
//                checkDownloadStatus(downloadId)
//            } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
//                Toast.makeText(context, "用户点击了通知栏", Toast.LENGTH_SHORT).show();
//            }
//
//        }
    /**
     * 检查下载状态
     */
//        private fun checkDownloadStatus(downloadId: Long) {
//            val query = DownloadManager.Query()
//            query.setFilterById(downloadId) //筛选下载任务，传入任务ID，可变参数
//            val cursor = mDownloadManager!!.query(query)
//            val status: Int
//            if (cursor.moveToFirst()) {
//                status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
//                when (status) {
//                    DownloadManager.STATUS_PAUSED -> LogUtil.i(">>>下载暂停")
//                    DownloadManager.STATUS_PENDING -> LogUtil.i(">>>下载延迟")
//                    DownloadManager.STATUS_RUNNING -> LogUtil.i(">>>正在下载")// 此处无法监听到
//                    DownloadManager.STATUS_SUCCESSFUL -> LogUtil.i(">>>下载完成")
//                    DownloadManager.STATUS_FAILED -> LogUtil.i(">>>下载失败")
//                }
//            }
//            val bytesDownload = cursor.getLong(
//                    cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
//            val totalSize =
//                cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
//        }
//    }


    override fun onCleared() {
        super.onCleared()
        mDownloadManager?.apply {
            //用于删除下载，如果下载中则取消下载， 同时会删除下载文件和记录
            remove(mDownloadId)
        }
        isLoop = false
    }
}
