package com.gh.download.dialog

import android.content.Context
import android.view.View
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.constant.Config
import com.gh.common.dialog.CertificationDialog
import com.gh.common.dialog.DeviceRemindDialog
import com.gh.common.dialog.PackageCheckDialogFragment
import com.gh.common.exposure.ExposureEvent
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils.directToLinkPage
import com.gh.common.util.DownloadDialogHelper
import com.gh.common.util.PackageInstaller
import com.gh.common.util.PackageUtils
import com.gh.download.DownloadManager
import com.gh.download.server.BrowserInstallHelper
import com.gh.gamecenter.DownloadManagerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.core.utils.SpeedUtils
import com.gh.gamecenter.databinding.DownloadDialogItemBinding
import com.gh.gamecenter.entity.ApkEntity
import com.gh.gamecenter.entity.GameCollectionEntity
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.manager.PackagesManager
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import com.lightgame.download.FileUtils
import com.lightgame.utils.AppManager
import com.lightgame.utils.Utils

class DownloadDialogItemViewHolder(val binding: DownloadDialogItemBinding) : BaseRecyclerViewHolder<Any>(binding.root) {

    fun bindItem(
        listData: List<DownloadDialogItemData>,
        position: Int,
        viewModel: DownloadViewModel,
        isCollectionPage: Boolean,
        traceEvent: ExposureEvent?,
        entrance: String,
        path: String,
        location: String
    ) {

        val apkEntity = listData[position].normal!!
        val gameEntity = viewModel.gameEntity
        val apkLink = apkEntity.apkLink
        val apkCollection = apkEntity.apkCollection

        val apk = when {
            apkLink != null -> ApkEntity(
                platformIcon = apkLink.icon,
                platformName = apkLink.name,
                remark = apkLink.remark
            )
            apkCollection != null -> ApkEntity(
                platformIcon = apkCollection.newIcon,
                platformName = apkCollection.name,
                recommend = apkCollection.recommend,
                remark = apkCollection.remark
            )
            else -> apkEntity
        }
        if (apk.getPlatformIcon().isEmpty()) {
            binding.icon.setImageURI("")
        } else {
            ImageUtils.display(binding.icon, apk.getPlatformIcon())
        }
        binding.name.text = apk.getPlatformName()
        binding.remark.text = apk.remark
        binding.recommendDesTv.goneIf(apk.recommend == null)
        binding.recommendDesTv.text = apk.recommend?.description
        binding.recommendLabel.goneIf(apk.recommend == null)
        binding.recommendLabelTv.text = apk.recommend?.subscript


        binding.containerView.setBackgroundResource(R.drawable.download_dialog_item_background)
        binding.status.removeDrawable()
        changeRecommendUI(apkEntity, listData, position)

        if (apkLink != null) {
            binding.root.visibility = View.VISIBLE
            binding.downloadStatusIcon.visibility = View.GONE
            binding.status.visibility = View.VISIBLE
            binding.progressbar.visibility = View.GONE
            binding.install.visibility = View.GONE
            binding.remark.goneIf(apkLink.remark.isEmpty())

            binding.status.text = "点击查看"
            binding.status.setDrawableEnd(R.drawable.download_dialog_collection_status_link)
            binding.containerView.setBackgroundResource(R.drawable.download_dialog_installed_background)
            itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.LINK)
        } else if (apkCollection != null || (!isCollectionPage && apkEntity.downloadInstruction.isNotEmpty())) {
            binding.root.visibility = View.VISIBLE
            binding.downloadStatusIcon.visibility = View.VISIBLE
            binding.progressbar.visibility = View.GONE
            binding.install.visibility = View.GONE
            binding.status.visibility = View.GONE
            if (apkCollection != null) {
                binding.remark.goneIf(apkCollection.remark.isEmpty())
            } else {
                binding.remark.goneIf(apkEntity.remark.isEmpty())
            }

            binding.downloadStatusIcon.setImageResource(if (apkEntity.recommend != null) R.drawable.download_dialog_status_collection else R.drawable.download_dialog_status_collection_gray)
            itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.COLLECTION)
        } else {
            if (apkEntity.url.isNullOrEmpty()) {
                binding.root.visibility = View.INVISIBLE
                return
            }
            binding.root.visibility = View.VISIBLE
            val downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(apkEntity.url)
            if (downloadEntity != null) {
                binding.downloadStatusIcon.visibility = View.VISIBLE
                binding.progressbar.visibility = View.VISIBLE
                binding.status.visibility = View.VISIBLE
                binding.remark.visibility = View.GONE
                binding.install.goneIf(DownloadStatus.done != downloadEntity.status)

                binding.downloadStatusIcon.setImageResource(R.drawable.download_dialog_status_pause)
                binding.progressbar.progress = downloadEntity.percent.toInt()
                binding.status.text = getDownloadingStatusText(downloadEntity)

                if (DownloadStatus.done == downloadEntity.status) {
                    itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.INSTALL)
                } else {
                    itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.DOWNLOADING)
                }
            } else {
                binding.progressbar.visibility = View.GONE
                binding.install.visibility = View.GONE
                binding.remark.goneIf(apkEntity.remark.isEmpty())

                if (PackageUtils.isCanUpdate(apkEntity, gameEntity.id)) {
                    binding.status.visibility = View.VISIBLE

                    binding.status.text = "可更新"
                    binding.status.setDrawableEnd(R.drawable.download_dialog_collection_status_update)
                    binding.downloadStatusIcon.visibility = View.GONE
                    itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.UPDATE)
                } else if (PackageUtils.getGhId(apkEntity.packageName) == gameEntity.id ||
                    PackagesManager.isInstalled(apkEntity.packageName) && Config.getSettings()?.gameDownloadBlackList?.contains(
                        apkEntity.packageName
                    ) == true
                ) {
                    binding.downloadStatusIcon.visibility = View.GONE
                    binding.status.visibility = View.VISIBLE
                    binding.containerView.setBackgroundResource(R.drawable.download_dialog_installed_background)

                    var isFilter = false
                    Config.getSettings()?.gameDownloadBlackList?.forEach { pkgName ->
                        if (pkgName == apkEntity.packageName) {
                            isFilter = true
                        }
                    }

                    if (isFilter) {
                        // 已安装
                        binding.status.text = "已安装"
                        itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.INSTALLED)
                    } else {
                        // 点击启动
                        binding.status.text = "点击启动"
                        itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.LAUNCH)
                        binding.status.setDrawableEnd(R.drawable.download_dialog_collection_status_launch)
                    }
                } else {
                    binding.downloadStatusIcon.visibility = View.VISIBLE
                    binding.status.visibility = View.GONE

                    binding.downloadStatusIcon.setImageResource(if (apkEntity.recommend != null) R.drawable.download_dialog_status_download else R.drawable.download_dialog_status_download_gray)
                    if (PackageUtils.isCanPluggable(apkEntity)) {
                        itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.PLUGGABLE)
                    } else {
                        itemView.setTag(DownloadDialogAdapter.ITEM_TAG_KEY, DownloadDialogItemStatus.DOWNLOAD)
                    }
                }
            }
        }

        setDownloadClickListener(itemView, apkEntity, viewModel, traceEvent, entrance, path, location)
    }

    private fun changeRecommendUI(apkEntity: ApkEntity, listData: List<DownloadDialogItemData>, position: Int) {
        (binding.containerView.layoutParams as RelativeLayout.LayoutParams).apply {
            topMargin = if (apkEntity.recommend != null) 4f.dip2px() else 0
            binding.containerView.layoutParams = this
        }
        (binding.root.layoutParams as RecyclerView.LayoutParams).apply {
            bottomMargin = if (apkEntity.recommend != null) {
                if ((position + 1 < listData.size && listData[position + 1].normal?.recommend == null) ||
                    (position + 2 < listData.size && listData[position + 2].normal?.recommend == null)
                ) {
                    20f.dip2px()
                } else 16f.dip2px()
            } else 8f.dip2px()
            binding.root.layoutParams = this
        }
        val downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(apkEntity.url)
        if (apkEntity.recommend != null && downloadEntity == null) {
            binding.containerView.background =
                ContextCompat.getDrawable(binding.root.context, R.drawable.bg_download_dialog_item_recommend)
        } else {
            binding.containerView.background =
                ContextCompat.getDrawable(binding.root.context, R.drawable.download_dialog_item_background)
        }
    }

    companion object {
        fun getDownloadingStatusText(downloadEntity: DownloadEntity): String {
            return when (downloadEntity.status) {
                DownloadStatus.waiting -> "等待中"
                DownloadStatus.done -> "等待安装"
                DownloadStatus.downloading -> SpeedUtils.getSpeed(downloadEntity.speed)
                else -> "已暂停"
            }
        }

        fun setDownloadClickListener(
            itemView: View,
            apkEntity: ApkEntity,
            viewModel: DownloadViewModel,
            traceEvent: ExposureEvent?,
            entrance: String,
            path: String,
            location: String
        ) {

            val gameEntity = viewModel.gameEntity
            itemView.setOnClickListener {
                var mtaValue = "未知"
                when (itemView.getTag(DownloadDialogAdapter.ITEM_TAG_KEY)) {
                    DownloadDialogItemStatus.DOWNLOAD -> {
                        createDownloadTask(it.context, apkEntity, gameEntity, "下载", traceEvent, entrance, location)
                        mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_下载"
                    }
                    DownloadDialogItemStatus.LAUNCH -> {
                        PackageUtils.launchApplicationByPackageName(it.context, apkEntity.packageName)

                        mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_启动"
                    }
                    DownloadDialogItemStatus.DOWNLOADING -> {
                        // 打开下载管理界面
                        it.context.startActivity(
                            DownloadManagerActivity.getDownloadMangerIntent(
                                it.context,
                                apkEntity.url,
                                BaseActivity.mergeEntranceAndPath(entrance, path)
                            )
                        )
                        if (AppManager.getInstance().currentActivity() is DownloadManagerActivity) {
                            viewModel.dismissLiveData.postValue(Any())
                        }

                        val downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(apkEntity.url)
                        if (downloadEntity?.status == DownloadStatus.pause) {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_暂停中"
                        } else if (downloadEntity?.status == DownloadStatus.waiting) {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_等待中"
                        } else if (downloadEntity?.status == DownloadStatus.subscribe) {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_排队中"
                        } else {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_下载中"
                        }

                    }
                    DownloadDialogItemStatus.INSTALL -> {
                        val downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(apkEntity.url)
                            ?: return@setOnClickListener

                        if (FileUtils.isEmptyFile(downloadEntity.path)) {
                            Utils.toast(it.context, R.string.install_failure_hint)
                            DownloadManager.getInstance().cancel(apkEntity.url)
                        } else {
                            if (PackageUtils.isCanPluggable(apkEntity)) {
                                DialogHelper.showPluginDialog(it.context) {
                                    PackageInstaller.uninstall(it.context, downloadEntity.path)
                                }
                            } else {
                                PackageInstaller.install(it.context, downloadEntity)
                            }
                        }

                        if (downloadEntity.isPluggable) {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_插件化安装"
                        } else {
                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_安装"
                        }
                    }
                    DownloadDialogItemStatus.PLUGGABLE -> {
                        createDownloadTask(it.context, apkEntity, gameEntity, "插件化", traceEvent, entrance, location)

                        mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_插件化"
                    }
                    DownloadDialogItemStatus.UPDATE -> {
                        createDownloadTask(it.context, apkEntity, gameEntity, "更新", traceEvent, entrance, location)

                        mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_更新"
                    }
                    DownloadDialogItemStatus.COLLECTION -> {
                        val apkCollection = apkEntity.apkCollection
                        if (apkCollection != null) {
                            viewModel.collectionLiveData.postValue(apkCollection)

                            mtaValue = gameEntity.name + "_" + apkCollection.name + "_查看合集"
                        } else if (apkEntity.downloadInstruction.isNotEmpty()) {
                            val fakeCollection = GameCollectionEntity()
                            fakeCollection.saveApkEntity = arrayListOf(apkEntity)
                            fakeCollection.name = apkEntity.getPlatformName()
                            fakeCollection.downloadInstruction = apkEntity.downloadInstruction
                            viewModel.collectionLiveData.postValue(fakeCollection)

                            mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_查看详情"
                        } else {
                            throwExceptionInDebug("合集和下载说明至少一个不为空")
                        }
                    }
                    DownloadDialogItemStatus.LINK -> {
                        directToLinkPage(it.context, apkEntity.apkLink?.getLinkEntity()!!, entrance, path)

                        mtaValue = gameEntity.name + "_" + apkEntity.apkLink?.name
                    }
                    DownloadDialogItemStatus.INSTALLED -> {
                        mtaValue = gameEntity.name + "_" + apkEntity.getPlatformName() + "_已安装"
                    }
                }
                throwExceptionInDebug("无法识别当前状态", mtaValue == "未知")
//                MtaHelper.onEvent(DownloadDialog.MTA_KEY, "点击", mtaValue)
            }
        }

        private fun createDownloadTask(
            context: Context,
            apkEntity: ApkEntity,
            gameEntity: GameEntity,
            downloadMethod: String,
            traceEvent: ExposureEvent?,
            entrance: String,
            location: String
        ) {
            // todo 有时间存储判断统一处理
            val msg = FileUtils.isCanDownload(context, apkEntity.size)
            if (msg.isNullOrEmpty()) {
                BrowserInstallHelper.showBrowserInstallHintDialog(
                    context,
                    gameEntity.isVGame(),
                    object : EmptyCallback {
                        override fun onCallback() {
                            DownloadDialogHelper.findAvailableDialogAndShow(
                                context,
                                gameEntity,
                                apkEntity,
                                object : EmptyCallback {
                                    override fun onCallback() {
                                        PackageCheckDialogFragment.show(
                                            context as AppCompatActivity,
                                            gameEntity,
                                            object : ConfirmListener {
                                                override fun onConfirm() {
                                                    CertificationDialog.showCertificationDialog(
                                                        context,
                                                        gameEntity,
                                                        object : ConfirmListener {
                                                            override fun onConfirm() {
                                                                DialogUtils.checkDownload(
                                                                    context,
                                                                    apkEntity.size
                                                                ) { isSubscribe ->
                                                                    DownloadManager.createDownload(
                                                                        context,
                                                                        apkEntity,
                                                                        gameEntity,
                                                                        downloadMethod,
                                                                        entrance,
                                                                        location,
                                                                        isSubscribe, traceEvent
                                                                    )

                                                                    DeviceRemindDialog.showDeviceRemindDialog(
                                                                        context,
                                                                        gameEntity
                                                                    )
                                                                }
                                                            }
                                                        })
                                                }
                                            })
                                    }
                                })
                        }
                    })
            } else {
                Utils.toast(context, msg)
            }
        }
    }
}