package com.gh.gamecenter.personal

import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
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.ItemPersonalRecommendBinding
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 HaloPersonalRecommendAdapter(val context: Context) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private val mEntityList = ArrayList<AddonLinkEntity>()

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

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is PersonalRecommendItemViewHolder && mEntityList.isNotEmpty()) {
            val addonLinkEntity = mEntityList[position]
            holder.binding.topDivider.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(mContext))
            holder.binding.leftDivider.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(mContext))
            holder.binding.nameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
            holder.binding.descTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
            when (position) {
                0 -> {
                    holder.binding.leftDivider.visibility = View.GONE
                    holder.binding.topDivider.visibility = View.GONE
                }

                1 -> {
                    holder.binding.leftDivider.visibility = View.VISIBLE
                    holder.binding.topDivider.visibility = View.GONE
                }

                2 -> {
                    holder.binding.leftDivider.visibility = View.GONE
                    holder.binding.topDivider.visibility = View.VISIBLE
                    holder.binding.topDivider.layoutParams =
                        (holder.binding.topDivider.layoutParams as ConstraintLayout.LayoutParams).apply {
                            setMargins(12F.dip2px(), 0, 0, 0)
                        }
                }

                3 -> {
                    holder.binding.leftDivider.visibility = View.VISIBLE
                    holder.binding.topDivider.visibility = View.VISIBLE
                    holder.binding.topDivider.layoutParams =
                        (holder.binding.topDivider.layoutParams as ConstraintLayout.LayoutParams).apply {
                            setMargins(0, 0, 12F.dip2px(), 0)
                        }
                }
            }
            holder.binding.nameTv.text = addonLinkEntity.name
            holder.binding.descTv.text = addonLinkEntity.desc
            ImageUtils.display(holder.binding.iconIv, addonLinkEntity.icon)
            holder.binding.redDot.goneIf(!addonLinkEntity.remind)

            holder.binding.root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("推荐位", addonLinkEntity.name)
                SensorsBridge.trackHaloSelfClick(
                    profile = "推荐位",
                    text = addonLinkEntity.name,
                    linkType = addonLinkEntity.link?.type ?: "",
                    linkId = addonLinkEntity.link?.link ?: "",
                    linkText = addonLinkEntity.link?.text ?: ""
                )
                if (addonLinkEntity.remind) {
                    val haveReadRecord: HashSet<String> =
                        SPUtils.getStringSet(Constants.SP_ADDONS_RECOMMEND_HAVE_READ) as HashSet<String>
                    val newReadRecord = hashSetOf<String>()//这里必须重新创建HashSet对象，否则重启app数据不能保存
                    newReadRecord.addAll(haveReadRecord)
                    newReadRecord.add(addonLinkEntity.id)
                    SPUtils.setStringSet(Constants.SP_ADDONS_RECOMMEND_HAVE_READ, newReadRecord)
                    MessageUnreadRepository.loadMessageUnreadTotal(true)
                    addonLinkEntity.remind = false
                    notifyItemRangeChanged(0, itemCount)
                }
                addonLinkEntity.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, "我的光环-账号安全") {}
                            }
                        }

                        "模拟器游戏" -> {
                            NewFlatLogUtils.logSimulatorGamePageShow()
                            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 PersonalRecommendItemViewHolder(val binding: ItemPersonalRecommendBinding) :
        RecyclerView.ViewHolder(binding.root)

}