package com.gh.common.xapk

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.SpannableStringBuilder
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.text.underline
import androidx.core.view.updateLayoutParams
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.activityresult.ActResultRequest
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.SimpleGameEntity
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils
import java.lang.ref.WeakReference

object XapkDialogHelper {

    private var mUnzipFailureDialogRef: WeakReference<Dialog>? = null

    fun showUnzipFailureDialog(context: Context, downloadEntity: DownloadEntity, isManualAction: Boolean) {
        val trigger = if (isManualAction) "手动触发" else "自动触发"
        NewFlatLogUtils.logXApkUnzipFailedDialogShowed(trigger, downloadEntity.gameId, downloadEntity.name)

        SensorsBridge.trackGameDecompressionFailedDialogShow(
            downloadEntity.gameId,
            downloadEntity.name,
            downloadEntity.categoryChinese
        )

        val previousShowedDialog = mUnzipFailureDialogRef?.get()

        val useRebootStyle = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S

        val content = if (useRebootStyle) {
            "未授权允许未知来源安装、数据包格式、设备兼容性…等均可能导致解压失败。"
        } else {
            "未授权允许未知来源安装、数据包格式、设备兼容性…等均可能导致解压失败。\n如果开启权限后仍未能解决，请提交反馈帮助我们改进。"
        }

        if (previousShowedDialog != null
            && previousShowedDialog.isShowing
            && context == previousShowedDialog.ownerActivity
        ) {
            // 上一个解压失败弹窗还在显示，当前 activity 不用再显示新的弹窗了
            return
        }

        val dialog = DialogHelper.showGuideDialog(
            context = context,
            title = "",
            content = content,
            confirmText = "开启权限",
            cancelText = if (useRebootStyle) "重启助手" else "提交反馈",
            confirmClickCallback = {
                if (context is AppCompatActivity) {
                    val intent = PermissionHelper.getToInstallPermissionSettingIntent(context)

                    NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                        "开启权限",
                        false,
                        downloadEntity.gameId,
                        downloadEntity.name
                    )

                    SensorsBridge.trackGameDecompressionFailedDialogClick(
                        buttonName = "开启权限",
                        downloadEntity.gameId,
                        downloadEntity.name,
                        downloadEntity.categoryChinese
                    )

                    // 记录应用重启前需要重解压的信息
                    SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, context.javaClass.name)
                    SPUtils.setString(Constants.SP_XAPK_URL, downloadEntity.url)

                    ActResultRequest(context).startForResult(intent) { resultCode, _ ->
                        if (resultCode == Activity.RESULT_OK) {
                            NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                                "开启权限",
                                true,
                                downloadEntity.gameId,
                                downloadEntity.name
                            )

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                                restart(context)
                            } else {
                                XapkInstaller.install(context, downloadEntity, true)
                            }
                        } else if (resultCode == Activity.RESULT_CANCELED) {
                            Utils.log("授予未知应用安装权限失败")
                        }
                    }
                } else if (context is Activity) {
                    PermissionHelper.toInstallPermissionSetting(context)
                }
            },
            cancelClickCallback = {
                if (useRebootStyle) {
                    // 记录应用重启前需要重解压的信息
                    SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, context.javaClass.name)
                    SPUtils.setString(Constants.SP_XAPK_URL, downloadEntity.url)

                    SensorsBridge.trackGameDecompressionFailedDialogClick(
                        buttonName = "重启助手",
                        downloadEntity.gameId,
                        downloadEntity.name,
                        downloadEntity.categoryChinese
                    )

                    restart(context)
                } else {
                    doFeedback(context, downloadEntity)
                }
            },
            uiModificationCallback = { binding ->
                binding.headIv.setBackgroundResource(R.drawable.dialog_unzip_failure_head_background)
                binding.titleTv.visibility = View.GONE
                // VectorDrawable 的动态颜色设置只在支持 Vector 的系统版本上生效，为了能方便复用资源不支持的就用默认颜色，又不是不能用！
                binding.closeIv.setColorFilter(Color.WHITE)
                binding.contentTv.setLineSpacing(5.0F.dip2px().toFloat(), 1.0F)
                binding.closeContainer.setOnClickListener {
                    binding.markDismissByTouchInside()

                    NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                        "关闭",
                        false,
                        downloadEntity.gameId,
                        downloadEntity.name
                    )

                    SensorsBridge.trackGameDecompressionFailedDialogClick(
                        buttonName = "关闭",
                        downloadEntity.gameId,
                        downloadEntity.name,
                        downloadEntity.categoryChinese
                    )
                    binding.dismiss()
                }
                if (useRebootStyle) {
                    val spannableString = SpannableStringBuilder()
                        .append("未能解决问题？点击 ")
                        .underline { append("提交反馈") }
                        .append(" ")
                    binding.alternativeCancelTv.visibility = View.VISIBLE
                    binding.alternativeCancelTv.text = spannableString
                    binding.alternativeCancelTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                    binding.alternativeCancelTv.setDrawableEnd(R.drawable.ic_right_arrow_xapk)
                    binding.alternativeCancelTv.setOnClickListener {
                        doFeedback(context, downloadEntity)
                    }

                    binding.hintTv.text = "开启权限后请务必重启光环助手，再进行安装"
                    binding.hintTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
                    binding.hintTv.setTextAppearance(com.gh.gamecenter.common.R.style.TextCaption1)
                    binding.hintTv.visibility = View.VISIBLE
                    binding.hintTv.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        topMargin = 8F.dip2px()
                    }
                    binding.confirmTv.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        topMargin = 16F.dip2px()
                    }
                }
            },
            touchOutsideCallback = {
                SensorsBridge.trackGameDecompressionFailedDialogClick(
                    buttonName = "关闭弹窗",
                    downloadEntity.gameId,
                    downloadEntity.name,
                    downloadEntity.categoryChinese
                )
            },
            extraConfig = DialogHelper.Config(showCloseIcon = true)
        )

        if (context is Activity) {
            dialog?.setOwnerActivity(context)
        }
        mUnzipFailureDialogRef = WeakReference(dialog)
    }

    private fun restart(context: Context) {
        val pm = context.packageManager
        val restartIntent = pm.getLaunchIntentForPackage(context.packageName)
        val mainIntent = Intent.makeRestartActivityTask(restartIntent!!.component)
        context.startActivity(mainIntent)
        Runtime.getRuntime().exit(0)
    }

    private fun doFeedback(context: Context, downloadEntity: DownloadEntity) {
        val hint = "游戏安装包解压失败，问题反馈："

        HelpAndFeedbackBridge.startSuggestionActivity(
            context,
            SuggestType.GAME,
            null,
            hint,
            SimpleGameEntity(downloadEntity.gameId, downloadEntity.name, downloadEntity.icon?: "")
        )
        NewFlatLogUtils.logXApkUnzipFailedDialogClick(
            "提交反馈",
            false,
            downloadEntity.gameId,
            downloadEntity.name
        )

        SensorsBridge.trackGameDecompressionFailedDialogClick(
            buttonName = "提交反馈",
            downloadEntity.gameId,
            downloadEntity.name,
            downloadEntity.categoryChinese
        )
    }

}