package com.gh.gamecenter.personal

import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.*
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.ItemHaloPersonalFuncBinding
import com.gh.gamecenter.entity.AddonLinkEntity
import com.gh.gamecenter.game.upload.GameSubmissionActivity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.message.MessageUnreadRepository
import com.gh.gamecenter.savegame.GameArchiveListActivity
import com.gh.gamecenter.setting.SettingBridge
import com.gh.gamecenter.simulatorgame.SimulatorGameActivity
import com.gh.gamecenter.teenagermode.TeenagerModeActivity
import com.gh.gamecenter.toolbox.ToolBoxActivity
import com.gh.gamecenter.video.videomanager.VideoManagerActivity
import com.lightgame.adapter.BaseRecyclerAdapter

class HaloPersonalFunctionAdapter(context: Context) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private val mEntityList = ArrayList<AddonLinkEntity>()

    fun setFunctionList(functionList: List<AddonLinkEntity>) {
        val haveReadRecord: HashSet<String> =
            SPUtils.getStringSet(Constants.SP_ADDONS_FUNCS_HAVE_READ) as HashSet<String>
        functionList.forEach { entity ->
            if (entity.remind && haveReadRecord.contains(entity.id)) {
                entity.remind = false
            }
        }
        mEntityList.clear()
        mEntityList.addAll(functionList)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        ItemPersonalFunctionViewHolder(parent.toBinding())

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ItemPersonalFunctionViewHolder && mEntityList.isNotEmpty()) {
            val linkEntity = mEntityList[position]
            holder.binding.run {
                ImageUtils.display(ivAddonIcon, linkEntity.icon)
                tvName.text = linkEntity.name
                tvName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                ivMessageTips.visibility = View.GONE

                if (linkEntity.remind) {
                    ivMessageTips.visibility = View.VISIBLE
                }

                root.setOnClickListener {
                    NewFlatLogUtils.logHaloSelfClick("更多功能", linkEntity.name)
                    SensorsBridge.trackHaloSelfClick(
                        profile = "更多功能",
                        text = linkEntity.name,
                        linkType = linkEntity.link?.type ?: "",
                        linkId = linkEntity.link?.link ?: "",
                        linkText = linkEntity.link?.text ?: ""
                    )
                    directPage(linkEntity)
                }
            }
        }
    }

    private fun directPage(linkEntity: AddonLinkEntity) {
        if (linkEntity.remind) {
            val haveReadRecord: HashSet<String> =
                SPUtils.getStringSet(Constants.SP_ADDONS_FUNCS_HAVE_READ) as HashSet<String>
            val newReadRecord = hashSetOf<String>()//这里必须重新创建HashSet对象，否则重启app数据不能保存
            newReadRecord.addAll(haveReadRecord)
            newReadRecord.add(linkEntity.id)
            SPUtils.setStringSet(Constants.SP_ADDONS_FUNCS_HAVE_READ, newReadRecord)
            MessageUnreadRepository.loadMessageUnreadTotal(true)
            linkEntity.remind = false
            notifyItemRangeChanged(0, itemCount)
        }

        linkEntity.link?.let {
            when (it.type) {
                "视频投稿" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH || BuildConfig.DEBUG) {
                            mContext.startActivity(VideoManagerActivity.getIntent(mContext, "", "我的光环-视频投稿"))
                        } else {
                            DialogHelper.showDialog(
                                mContext, "提示",
                                "抱歉，您当前系统版本过低，暂不支持视频功能", "我知道了", ""
                            )
                        }
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-视频投稿") {}
                    }
                }

                "账号安全" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        mContext.startActivity(SettingBridge.getSecurityIntent(mContext, "我的光环-账号安全"))
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-账号安全") {}
                    }
                }

                "模拟器游戏" -> {
                    mContext.startActivity(SimulatorGameActivity.getIntent(mContext))
                }

                "收货信息" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        mContext.startActivity(DeliveryInfoActivity.getIntent(mContext))
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-收货信息") {}
                    }
                }

                "实名认证" -> {
                    mContext.startActivity(ShellActivity.getIntent(mContext, ShellActivity.Type.REAL_NAME_INFO, null))
                }

                "微信提醒" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        mContext.startActivity(WebActivity.getBindWechatIntent(mContext))
                        SensorsBridge.trackEvent(
                            "AppointmenWechatRemindConfigPageShow",
                            "source_entrance",
                            "我的光环-微信提醒"
                        )
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-微信提醒") { }
                    }
                }

                "游戏动态" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        DataCollectionUtils.uploadClick(mContext, "游戏动态", "发现")
                        DirectUtils.directToConcernInfo(mContext, "我的光环-更多功能")
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-游戏动态") { }
                    }
                }

                "资讯中心" -> {
                    DataCollectionUtils.uploadClick(mContext, "资讯中心", "发现")
                    mContext.startActivity(InfoActivity.getIntent(mContext))
                }

                "礼包中心" -> {
                    DataCollectionUtils.uploadClick(mContext, "礼包中心", "发现")
                    DirectUtils.directToGift(mContext, "(发现:礼包)")
                }

                "工具箱" -> {
                    DataCollectionUtils.uploadClick(mContext, "工具箱", "发现")
                    mContext.startActivity(ToolBoxActivity.getIntent(mContext, "(发现:工具箱)"))
                }

                "安装包清理" -> {
                    DataCollectionUtils.uploadClick(mContext, "安装包清理", "发现")
                    PermissionHelper.checkManageAllFilesOrStoragePermissionBeforeAction(mContext) {
                        mContext.startActivity(CleanApkActivity.getIntent(mContext))
                    }
                }

                "个人中心" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        mContext.startActivity(UserInfoActivity.getIntent(mContext))
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-个人中心") {}
                    }
                }

                "游戏投稿" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        PermissionHelper.checkStoragePermissionBeforeAction(mContext) {
                            mContext.startActivity(
                                GameSubmissionActivity.getIntent(mContext, "(我的光环)", "")
                            )
                        }
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-游戏投稿") { }
                    }
                }

                "视频数据" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        DirectUtils.directVideoData(mContext, "我的光环-视频数据")
                    } else {
                        CheckLoginUtils.checkLogin(mContext, "我的光环-视频数据") {}
                    }
                }

                "青少年模式" -> {
                    mContext.startActivity(TeenagerModeActivity.getIntent(mContext))
                }

                "游戏存档" -> {
                    mContext.startActivity(GameArchiveListActivity.getIntent(mContext))
                }

                "开服管理" -> {// 开服管理
                    DirectUtils.directToServersCalendarManagement("我的光环-更多功能")
                }

                else -> {
                    DirectUtils.directToLinkPage(mContext, it, "我的光环", "更多功能")
                }
            }
        }

    }

    override fun getItemCount() = mEntityList.size

    class ItemPersonalFunctionViewHolder(val binding: ItemHaloPersonalFuncBinding) :
        RecyclerView.ViewHolder(binding.root)
}