package com.gh.common.dialog

import android.app.Activity.RESULT_OK
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
import com.airbnb.lottie.LottieAnimationView
import com.gh.common.constant.Config
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.xapk.XapkInstaller
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.PermissionHelper.INSTALL_PERMISSION_CODE
import com.gh.gamecenter.core.utils.SPUtils
import com.lightgame.download.DownloadEntity
import kotlin.random.Random

class InstallPermissionDialogFragment : BaseDialogFragment() {

    lateinit var mView: View
    var isXapk = false
    var url: String = ""
    var gameId: String = ""
    var gameName: String = ""
    var gameType: String = ""
    var mCallBack: ((isFromPermissionGrantedCallback: Boolean) -> Unit)? = null

    private var dismissByTouchInside = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mView = inflater.inflate(R.layout.dialog_install_permission, null, false)
        return mView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val closeTv = mView.findViewById<TextView>(R.id.closeTv)
        val closeIv = mView.findViewById<ImageView>(R.id.closeIv)
        val activateTv = mView.findViewById<TextView>(R.id.activateTv)
        val contentTv = mView.findViewById<TextView>(R.id.contentTv)
        val switchLottie = mView.findViewById<LottieAnimationView>(R.id.switchLottie)
        contentTv.text = if (isXapk) "未授权下解压XAPK可能导致解压失败" else "以保证游戏的安装和更新"

        switchLottie.setAnimation("lottie/install_permission_switch.json")
        switchLottie.playAnimation()

        if (isXapk) NewFlatLogUtils.logXApkInstallPermissionDialogShowed(gameId, gameName)

        SensorsBridge.trackInstallPermissionDialogShow(
            gameId = gameId,
            gameName = gameName,
            gameType = gameType
        )

        val randomNumber = if (isXapk) 1 else Random.nextInt(2)
        closeTv.goneIf(randomNumber == 0)
        closeIv.goneIf(randomNumber != 0)
        if (isXapk) {
            closeTv.text = "暂不，尝试解压"
            closeIv.visibility = View.VISIBLE
        }

        closeTv.setOnClickListener {
            dismissByTouchInside = true
            if (isXapk) {
                NewFlatLogUtils.logXApkInstallPermissionDialogClick("尝试解压", false, gameId, gameName)
                mCallBack?.invoke(false)
            }
            SensorsBridge.trackInstallPermissionDialogClick(
                buttonName = "尝试解压",
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
            dismiss()
        }
        closeIv.setOnClickListener {
            dismissByTouchInside = true
            if (isXapk) NewFlatLogUtils.logXApkInstallPermissionDialogClick("关闭", false, gameId, gameName)
            SensorsBridge.trackInstallPermissionDialogClick(
                buttonName = "关闭",
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
            dismiss()
        }
        activateTv.setOnClickListener {
            NewFlatLogUtils.logXApkInstallPermissionDialogClick("立即开启", false, gameId, gameName)
            SensorsBridge.trackInstallPermissionDialogClick(
                buttonName = "立即开启",
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
            PermissionHelper.toInstallPermissionSetting(requireActivity())
            if (isXapk) {
                SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, requireActivity().javaClass.name)
                SPUtils.setString(Constants.SP_XAPK_URL, url)
            }
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        if (!dismissByTouchInside) {
            SensorsBridge.trackInstallPermissionDialogClick(
                buttonName = "关闭弹窗",
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
        }
        super.onDismiss(dialog)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISSION_CODE) {
            dismissByTouchInside = true

            NewFlatLogUtils.logXApkInstallPermissionDialogClick("立即开启", true, gameId, gameName)

            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
                SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "")
                SPUtils.setString(Constants.SP_XAPK_URL, "")
            }
            mCallBack?.invoke(true)
            dismiss()
        }
    }

    companion object {
        @JvmStatic
        fun show(
            activity: AppCompatActivity,
            downloadEntity: DownloadEntity,
            callBack: ((isFromPermissionGrantedCallback: Boolean) -> Unit)?
        ) {
            val isXapk = XapkInstaller.XAPK_EXTENSION_NAME == downloadEntity.path.getExtension()
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                callBack?.invoke(false)
                return
            }
            val haveInstallPermission = activity.packageManager.canRequestPackageInstalls()
            if (haveInstallPermission) {
                callBack?.invoke(false)
                return
            }
            if (isXapk) {
                val xapkUnzipVersions = Config.getSettings()?.permissionPopupAppliedVersions?.xapkUnzip
                if (xapkUnzipVersions?.contains(Build.VERSION.SDK_INT.toString()) == false || XapkInstaller.systemHasFlaw) {
                    callBack?.invoke(false)
                    return
                }
            } else {
                val installVersions = Config.getSettings()?.permissionPopupAppliedVersions?.install
                if (installVersions?.contains(Build.VERSION.SDK_INT.toString()) == false) {
                    callBack?.invoke(false)
                    return
                }
            }
            var installPermissionDialogFragment =
                activity.supportFragmentManager.findFragmentByTag(InstallPermissionDialogFragment::class.java.name) as? InstallPermissionDialogFragment
            if (installPermissionDialogFragment != null) {
                installPermissionDialogFragment.mCallBack = callBack
                installPermissionDialogFragment.isXapk = isXapk
                installPermissionDialogFragment.url = downloadEntity.url
                installPermissionDialogFragment.gameId = downloadEntity.gameId
                installPermissionDialogFragment.gameName = downloadEntity.name
                installPermissionDialogFragment.gameType = downloadEntity.categoryChinese
                val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
                transaction.show(installPermissionDialogFragment)
                transaction.commit()
            } else {
                installPermissionDialogFragment = InstallPermissionDialogFragment().apply {
                    this.mCallBack = callBack
                    this.isXapk = isXapk
                    this.url = downloadEntity.url
                    this.gameId = downloadEntity.gameId
                    this.gameName = downloadEntity.name
                    this.gameType = downloadEntity.categoryChinese
                }
                installPermissionDialogFragment.show(
                    activity.supportFragmentManager,
                    InstallPermissionDialogFragment::class.java.name
                )
            }
        }
    }
}