package com.cheng.blzb.ui.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.FileProvider
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.cheng.blzb.R
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.DialogUpdateVerisonBinding
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.utils.DownLoadUtils
import com.cheng.blzb.utils.PermissionUtils
import com.cheng.blzb.utils.UIUtils
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.visible
import com.example.base.utils.ScreenUtils
import com.cheng.blzb.common.Constants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class UpdateVersionDialog : DialogFragment() {
    private var mOnBackListener: ((DialogEnum) -> Unit)? = null     //回调事件

    var apkFilePath = ""

    lateinit var binding: DialogUpdateVerisonBinding

    override fun onStart() {
        super.onStart()
        val window = dialog?.window
        val windowParams = window?.attributes
        windowParams?.dimAmount = 0.7f
        windowParams?.width = (ScreenUtils.getWindowSize().x * 0.7).toInt()
        dialog?.window?.attributes = windowParams
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = layoutInflater.inflate(R.layout.dialog_update_verison, null)

        binding = DialogUpdateVerisonBinding.bind(view)

        binding.tvUpdateTitle.typeface = Constants.douyinsansB

        val versionEntity = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("versionEntity", com.cheng.blzb.bean.VersionEntity::class.java)
        } else {
            arguments?.getSerializable("versionEntity") as com.cheng.blzb.bean.VersionEntity?
        }

        binding.cancelBtn.onClick {
            dismiss()
            EventReportManager.eventReport(EventConstants.PKG_CANCEL, "", "升级的版本号${versionEntity?.version}")
        }

        versionEntity?.apply {
            binding.tvVersionName.text = version
            binding.tvUpdateTitle.text = title
            binding.tvUpdateDesc.text = description
            if (force) {
                binding.cancelBtn.gone()
            } else {
                binding.cancelBtn.visible()
            }
        }

        binding.ivClose.onClick {
            val f = TipDialog.newInstance("提示", "确定取消下载？")
            f.setOnSelectListener {
                if (it == DialogEnum.CLICK_OK) {
                    DownLoadUtils.getInstance().cancel()
                    dismiss()
                }
            }
            f.show(childFragmentManager, TipDialog::class.java.simpleName)
        }

        binding.updateBtn.onClick {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (binding.updateBtn.text.toString() == "立即安裝" && !TextUtils.isEmpty(apkFilePath)) {
                    install()
                } else {
                    versionEntity?.apply {
                        download(url, force)
                        EventReportManager.eventReport(EventConstants.PKG_UPDATE, "", "升级的版本号${versionEntity.version}")
                    }
                }
            } else {
                PermissionUtils.checkStoragePermission(requireActivity(), childFragmentManager) { isGranted ->
                    if (isGranted) {
                        if (binding.updateBtn.text.toString() == "立即安裝" && !TextUtils.isEmpty(apkFilePath)) {
                            install()
                        } else {
                            versionEntity?.apply {
                                download(url, force)
                                EventReportManager.eventReport(EventConstants.PKG_UPDATE, "", "升级的版本号${versionEntity.version}")
                            }
                        }
                    }
                }
            }
        }

        isCancelable = false

        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        return dialog
    }

    @SuppressLint("SetTextI18n")
    private fun download(url: String, force: Boolean) {

        if (force) {
            binding.ivClose.gone()
        } else {
            binding.ivClose.visible()
        }
        binding.cancelBtn.gone()
        binding.updateBtn.gone()
        binding.progressbar.visible()
        binding.tvProgress.visible()

        lifecycleScope.launch(Dispatchers.IO) {
            var totalProgress = 0L
            DownLoadUtils.getInstance()
                .setReadTimeOut(10L)
                .setDeleteWhenException(false)
                .initUrl(url, null)
                .setFilePath(com.cheng.blzb.utils.FileUtils.getInstance().cacheDownLoderDir.absolutePath)
                .setFileName(UIUtils.getFileNameFromUrl(url))
                .setActionCallBack(
                    { totalProgress = it },
                    {
                        val percent = it.toDouble() / totalProgress.toDouble() * 100
                        val curProgress = percent.toInt()
                        binding.tvProgress.text = "${curProgress}%"
                        binding.progressbar.progress = curProgress
                    },
                    {
                        binding.tvProgress.text = "100%"
                        apkFilePath = it.absolutePath
                        binding.updateBtn.text = "立即安裝"

                        binding.updateBtn.visible()
                        binding.progressbar.gone()
                        binding.tvProgress.gone()

                        install()
                    }, {
                        binding.updateBtn.text = "下载失败,点击重试"
                        binding.updateBtn.visible()
                        binding.progressbar.gone()
                        binding.tvProgress.gone()
                    }).down()
        }
    }

    fun setOnSelectListener(listener: ((DialogEnum) -> Unit)) {
        mOnBackListener = listener
    }

    companion object {
        fun newInstance(versionEntity: com.cheng.blzb.bean.VersionEntity): UpdateVersionDialog {
            val arg = Bundle()
            val fragment = UpdateVersionDialog()
            arg.putSerializable("versionEntity", versionEntity)
            fragment.arguments = arg
            return fragment
        }
    }

    private fun install() {
        try {
            val apkFile = File(com.cheng.blzb.utils.FileUtils.getInstance().cacheDownLoderDir, UIUtils.getFileNameFromUrl(apkFilePath))
            if (!apkFile.exists()) {
                return
            }
            val apkUri = FileProvider.getUriForFile(requireContext(), requireContext().packageName + ".fileprovider", apkFile)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}