package com.gh.gamecenter.simulatorgame

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.simulator.SimulatorDownloadManager
import com.gh.common.simulator.SimulatorGameManager
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.SimulatorGameItemBinding
import com.gh.gamecenter.databinding.SimulatorHeaderViewBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.SimulatorEntity
import com.gh.gamecenter.room.AppDatabase

class SimulatorGameListAdapter(
    context: Context,
    var simulator: SimulatorEntity,
    var fragment: SimulatorGameListFragment
) : ListAdapter<GameEntity>(context) {

    private var mCurrentOption = OPTION_MANAGER
    private var mShowSelectFlag = false
    private var mSelectList = ArrayList<Boolean>()
    private val mEntrance = "模拟器游戏"
    private lateinit var mPopWindow: PopupWindow
    private val mSimulatorGameDao = AppDatabase.getInstance().simulatorGameDao()
    var mLaunchGameFlag = false

    override fun setListData(updateData: MutableList<GameEntity>?) {
        mSelectList.clear()
        updateData?.forEach { _ ->
            mSelectList.add(false)
        }
        super.setListData(updateData)
    }

    override fun getItemCount(): Int {
        return if (mEntityList == null || mEntityList.isEmpty()) return 0 else mEntityList.size + 2
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_HEADER -> {
                SimulatorHeaderViewHolder(parent.toBinding())
            }

            ItemViewType.GAME_NORMAL -> {
                SimulatorGameViewHolder(parent.toBinding())
            }

            else -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is SimulatorHeaderViewHolder -> {
                holder.binding.btnManager.run {
                    text = when (mCurrentOption) {
                        OPTION_MANAGER -> "管理"
                        OPTION_ALL_SELECT -> "全选"
                        OPTION_CANCEL_SELECT -> "取消全选"
                        else -> "管理"
                    }
                    setOnClickListener {
                        when (mCurrentOption) {
                            OPTION_MANAGER -> {
                                mShowSelectFlag = true
                                showOptionWindow()
                                notifyDataSetChanged()
                                mCurrentOption = OPTION_ALL_SELECT
                                MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${simulator.typeAlias}+管理")
                            }

                            OPTION_ALL_SELECT -> {
                                resetSelectList(true)
                                notifyDataSetChanged()
                                mCurrentOption = OPTION_CANCEL_SELECT
                            }

                            OPTION_CANCEL_SELECT -> {
                                resetSelectList(false)
                                notifyDataSetChanged()
                                mCurrentOption = OPTION_ALL_SELECT
                            }
                        }
                    }
                }

                holder.binding.btnSimulator.run {
                    if (PackageUtils.isInstalledFromAllPackage(context, simulator.apk?.packageName)) {
//                        val versionFromInstalledApp = PackageUtils.getVersionNameByPackageName(simulator.apk?.packageName)
                        val shouldShowUpdate =
                            PackageUtils.isInstalledApkMatchedMd5(simulator.apk?.packageName, simulator.apk?.md5)
                        text = if (shouldShowUpdate) "更新模拟器" else ""
                        setTextColor(
                            if (shouldShowUpdate) R.color.theme.toColor(mContext) else R.color.text_subtitleDesc.toColor(
                                mContext
                            )
                        )
                        setOnClickListener {
                            if (shouldShowUpdate) {
                                SimulatorDownloadManager.getInstance().showDownloadDialog(
                                    context,
                                    simulator,
                                    SimulatorDownloadManager.SimulatorLocation.SIMULATOR_GAME
                                )
                                MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${simulator.typeAlias}+更新模拟器")
                            }
//                            else {
//                                DialogHelper.showDialog(
//                                    mContext,
//                                    "卸载模拟器",
//                                    "即将卸载模拟器，是否确定卸载？",
//                                    "确定",
//                                    "取消",
//                                    confirmClickCallback = {
//                                        PackageInstaller.uninstallForPackageName(mContext, simulator.apk?.packageName ?: "")
//                                    },
//                                    uiModificationCallback = { binding ->
//                                        binding.contentTv.setTextColor(R.color.text_title.toColor(mContext))
//                                    },
//                                    extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
//                            }
                        }
                    } else {
                        if (simulator.active) {
                            text = "安装模拟器"
                            setTextColor(R.color.theme.toColor(mContext))
                            setOnClickListener {
                                SimulatorDownloadManager.getInstance().showDownloadDialog(
                                    context,
                                    simulator,
                                    SimulatorDownloadManager.SimulatorLocation.SIMULATOR_GAME
                                )
                                MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${simulator.typeAlias}+下载模拟器")
                            }
                        }
                    }
                }
            }

            is SimulatorGameViewHolder -> {
                val gameEntity = mEntityList[position - 1]
                holder.binding.run {
                    (gameItemIncluded.downloadBtn.layoutParams as ConstraintLayout.LayoutParams).apply {
                        topToTop = -1
                        bottomMargin = DisplayUtils.dip2px(8F)
                    }
                    gameItemIncluded.run {
                        gameIconView.displayGameIcon(gameEntity)
                        BindingAdapters.setGameName(gameName, gameEntity, false, null)
                        BindingAdapters.setTextSize(gameRating, if (gameEntity.commentCount > 3) 12 else 10)
                        BindingAdapters.setGameTags(labelList, gameEntity)
                        gameRating.setDrawableStart(if (gameEntity.commentCount > 3) R.drawable.game_horizontal_rating.toDrawable() else null)
                        gameRating.setPadding(0, 0, if (gameEntity.commentCount > 3) 8F.dip2px() else 0, 0)
                        gameRating.text = if (gameEntity.commentCount > 3) {
                            if (gameEntity.star == 10.0F) "10" else gameEntity.star.toString()
                        } else ""
                        gameRating.setTextColor(
                            if (gameEntity.commentCount > 3) R.color.theme_font.toColor(mContext) else R.color.theme.toColor(
                                mContext
                            )
                        )
                        gameDes.text = gameEntity.decoratedDes
                        recommendStar.rating = gameEntity.recommendStar.toFloat()
                    }
                    gameItemIncluded.recentPlayedTag.goneIf(!gameEntity.isRecentlyPlayed)
                    gameItemIncluded.selectIv.setImageDrawable(DrawableView.getCheckSelectorDrawable(mContext))
                    gameItemIncluded.selectIv.goneIf(!mShowSelectFlag)
                    gameItemIncluded.selectIv.isChecked = mSelectList[position - 1]
                    gameItemIncluded.selectIv.setOnClickListener {
                        gameItemIncluded.selectIv.isChecked = !gameItemIncluded.selectIv.isChecked
                        mSelectList[position - 1] = gameItemIncluded.selectIv.isChecked

                        when (mCurrentOption) {
                            OPTION_CANCEL_SELECT -> {
                                if (mSelectList.contains(false)) {
                                    mCurrentOption = OPTION_ALL_SELECT
                                    notifyItemChanged(0)
                                }
                            }

                            OPTION_ALL_SELECT -> {
                                if (!mSelectList.contains(false)) {
                                    mCurrentOption = OPTION_CANCEL_SELECT
                                    notifyItemChanged(0)
                                }
                            }
                        }
                    }

                    DownloadItemUtils.setOnClickListener(mContext,
                        gameItemIncluded.downloadBtn,
                        gameEntity,
                        position,
                        this@SimulatorGameListAdapter,
                        "(${mEntrance})",
                        StringUtils.buildString(mEntrance, ":", gameEntity.name),
                        null,
                        object : EmptyCallback {
                            override fun onCallback() {
                                // 若当前点击为启动模拟器游戏，且当前item不是近期玩过的游戏（即未显示"近期玩过"标签），则将标志位mLaunchGameFlag置为true
                                if (gameItemIncluded.downloadBtn.text == R.string.launch.toResString()
                                    && gameItemIncluded.recentPlayedTag.visibility == View.GONE
                                ) {
                                    mLaunchGameFlag = true
                                }
                            }
                        })

                    DownloadItemUtils.updateItem(
                        mContext,
                        gameEntity,
                        GameViewHolder(holder.binding.gameItemIncluded),
                        true
                    )

                    optionsIv.setOnClickListener {
                        showSingleOptionWindow(
                            optionsIv,
                            gameItemIncluded.downloadBtn.text == mContext.getString(R.string.launch)
                        ) {
                            val gameName = gameEntity.name ?: ""
                            when (it) {
                                "添加到桌面" -> {
                                    DialogUtils.showShortCutPermissionDialog(mContext)
                                    createShortcut(gameEntity)
                                    MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${gameName}+添加到桌面")
                                    NewFlatLogUtils.logSimulatorGameCardClick("添加到桌面")
                                }
                                "游戏详情" -> {
                                    NewFlatLogUtils.logSimulatorGameCardClick("游戏详情")
                                    GameDetailActivity.startGameDetailActivity(
                                        mContext,
                                        gameEntity.id,
                                        "(${mEntrance})"
                                    )
                                }
                                "删除游戏" -> {
                                    MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${gameName}+删除游戏")
                                    NewFlatLogUtils.logSimulatorGameCardClick("删除游戏")
                                    showDeleteSingleGameDialog(gameEntity)
                                }
                            }
                        }
                    }

                    root.setOnClickListener {
                        if (mShowSelectFlag) {
                            gameItemIncluded.selectIv.performClick()
                        } else {
                            optionsIv.performClick()
                        }
                    }
                    root.setOnLongClickListener {
                        showDeleteSingleGameDialog(gameEntity)
                        true
                    }
                }
            }

            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    private fun resetSelectList(value: Boolean) {
        for (i in 0 until mSelectList.size) {
            mSelectList[i] = value
        }
    }

    private fun showOptionWindow() {
        val contentView = View.inflate(mContext, R.layout.popup_simulator_option, null)
        contentView.isFocusable = true
        contentView.isFocusableInTouchMode = true
        val deleteItem = contentView.findViewById<LinearLayout>(R.id.item_delete)
        val completeItem = contentView.findViewById<LinearLayout>(R.id.item_complete)

        mPopWindow =
            PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        mPopWindow.showAtLocation(fragment.requireActivity().window.decorView, Gravity.BOTTOM, 0, 0)

        completeItem.setOnClickListener {
            mPopWindow.dismiss()
            resetStatus()
            notifyDataSetChanged()
            MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${simulator.typeAlias}+管理+完成")
        }

        deleteItem.setOnClickListener {
            val selectItems = ArrayList<GameEntity>()
            val list = ArrayList<String>()
            val ids = ArrayList<String>()
            mSelectList.forEachIndexed { index, b ->
                if (b) {
                    list.add(mEntityList[index]?.name ?: "")
                    ids.add(mEntityList[index]?.id ?: "")
                    selectItems.add(mEntityList[index])
                }
            }

            if (list.isEmpty()) {
                ToastUtils.showToast("请选择游戏")
            } else {
                DialogHelper.showDialog(mContext, "删除游戏", "即将删除游戏记录和本地文件，是否确定删除", "确定", "取消", {
                    mPopWindow.dismiss()
                    resetStatus()
                    SimulatorGameManager.deleteLocalGames(list)
                    val isNetworkConnected = NetworkUtils.isNetworkConnected(mContext)
                    val simulatorEntities = selectItems.map { it.convertSimulatorGameRecordEntity() }.toList()
                    if (isNetworkConnected) {
                        SimulatorGameManager.deleteSimulatorGames(ids) {
                            if (list.size == mEntityList.size) {
                                (fragment.parentFragment as SimulatorGameFragment).refresh()
                            } else {
                                fragment.onLoadRefresh()
                            }
                        }
                        mSimulatorGameDao.deleteSimulatorGameList(simulatorEntities)
                    } else {
                        simulatorEntities.forEach {
                            mSimulatorGameDao.logicalDeleteSimulatorGame(it.name ?: "")
                        }
                    }

                    if (!isNetworkConnected) {
                        if (list.size == mEntityList.size) {
                            (fragment.parentFragment as SimulatorGameFragment).refresh()
                        } else {
                            fragment.onLoadRefresh()
                        }
                    }
                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
                MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${simulator.typeAlias}+管理+删除游戏")
            }
        }
    }

    private fun showSingleOptionWindow(view: View, isShowShortCut: Boolean, clickListener: (String) -> Unit) {
        val contentList = arrayListOf(
            Pair("游戏详情", R.drawable.ic_simulator_game_detail),
            Pair("删除游戏", R.drawable.ic_delete_game_blue)
        )
        if (isShowShortCut) {
            contentList.add(0, Pair("添加到桌面", R.drawable.ic_shortcut_simulator_blue))
        }
        val inflater = LayoutInflater.from(mContext)
        val layout = inflater.inflate(R.layout.layout_popup_container, null)
        val popupWindow = BugFixedPopupWindow(
            layout,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        val container = layout.findViewById<LinearLayout>(R.id.container)
        for (content in contentList) {
            val item = inflater.inflate(R.layout.layout_popup_option_icon_item, container, false)
            container.addView(item)
            val iconView = item.findViewById<ImageView>(R.id.icon)
            val hitText = item.findViewById<TextView>(R.id.hint_text)
            hitText.text = content.first
            iconView.setImageDrawable(content.second.toDrawable())
            item.setOnClickListener {
                clickListener.invoke(content.first)
                popupWindow.dismiss()
            }
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true

        popupWindow.showAutoOrientation(view)
    }

    private fun showDeleteSingleGameDialog(gameEntity: GameEntity) {
        NewFlatLogUtils.logSimulatorGameDeleteAlertShow()
        DialogHelper.showDialog(
            mContext,
            "删除游戏",
            "即将删除游戏记录和本地文件，是否确定删除",
            "确定",
            "取消",
            {
                NewFlatLogUtils.logSimulatorGameDeleteAlertClick("确定")
                val isNetworkConnected = NetworkUtils.isNetworkConnected(mContext)
                SimulatorGameManager.deleteLocalGame(gameEntity.name ?: "")
                if (isNetworkConnected) {
                    SimulatorGameManager.deleteSimulatorGame(gameEntity.id) {
                        if (mEntityList.size == 1) {
                            (fragment.parentFragment as SimulatorGameFragment).refresh()
                        } else {
                            fragment.onLoadRefresh()
                        }
                    }
                    mSimulatorGameDao.deleteSimulatorGameByName(gameEntity.name ?: "")
                } else {
                    mSimulatorGameDao.logicalDeleteSimulatorGame(gameEntity.name ?: "")
                }
                if (!isNetworkConnected) {
                    if (mEntityList.size == 1) {
                        (fragment.parentFragment as SimulatorGameFragment).refresh()
                    } else {
                        fragment.onLoadRefresh()
                    }
                }
            },
            cancelClickCallback = { NewFlatLogUtils.logSimulatorGameDeleteAlertClick("取消") },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    fun resetPageFromFragment() {
        if (mShowSelectFlag) {
            resetStatus()
            notifyDataSetChanged()
            if (::mPopWindow.isInitialized && mPopWindow.isShowing) {
                mPopWindow.dismiss()
            }
        }
    }

    private fun resetStatus() {
        mShowSelectFlag = false
        mCurrentOption = OPTION_MANAGER
        resetSelectList(false)
    }

    override fun getItemViewType(position: Int): Int {
        return when (position) {
            0 -> ItemViewType.ITEM_HEADER
            itemCount - 1 -> ItemViewType.ITEM_FOOTER
            else -> ItemViewType.GAME_NORMAL
        }
    }

    @SuppressLint("CheckResult")
    fun createShortcut(gameEntity: GameEntity) {
        val gameName = gameEntity.name ?: ""
        val gameIcon = gameEntity.icon ?: ""
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
            ImageUtils.getBitmap(gameIcon, object : BiCallback<Bitmap, Boolean> {
                override fun onFirst(first: Bitmap) {
                    // 要先压缩图片，不然图片过大再调用requestPinShortcut后，可能会报TransactionTooLargeException异常
                    val bitmap = compressImage(first)
                    val shortcutInfoIntent = Intent(mContext, MainActivity::class.java)
                    shortcutInfoIntent.run {
                        action = Intent.ACTION_VIEW
                        putExtra(EntranceConsts.KEY_REQUIRE_REDIRECT, true)
                        putExtra(EntranceConsts.KEY_TO, EntranceConsts.HOST_LAUNCH_SIMULATOR_GAME)
                        putExtra(EntranceConsts.KEY_GAME, gameEntity.toJson())
                        val info = ShortcutInfoCompat.Builder(mContext, gameName)
                            .setIcon(IconCompat.createWithBitmap(bitmap))
                            .setShortLabel(gameName)
                            .setIntent(this)
                            .build()
                        ShortcutManagerCompat.requestPinShortcut(mContext, info, null)
                    }
                }

                override fun onSecond(second: Boolean) {
                    ToastUtils.showToast("创建快捷方式失败")
                }
            })
        }
    }

    // Bitmap尺寸超过300*300就压缩
    fun compressImage(bitmap: Bitmap): Bitmap {
        return if (bitmap.byteCount > 300 * 300 * 4) {
            val width = bitmap.width.toFloat()
            val height = bitmap.height.toFloat()
            val matrix = Matrix()
            val scaleWidth = 300 / width
            val scaleHeight = 300 / height
            matrix.postScale(scaleWidth, scaleHeight)
            Bitmap.createBitmap(bitmap, 0, 0, width.toInt(), height.toInt(), matrix, true)
        } else bitmap
    }

    inner class SimulatorGameViewHolder(val binding: SimulatorGameItemBinding) : RecyclerView.ViewHolder(binding.root)
    inner class SimulatorHeaderViewHolder(val binding: SimulatorHeaderViewBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)

    companion object {
        const val OPTION_MANAGER = 100
        const val OPTION_ALL_SELECT = 101
        const val OPTION_CANCEL_SELECT = 102
    }
}