package com.gh.common.dialog

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.common.exposure.IExposable
import com.gh.gamecenter.DownloadManagerActivity
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.FixLinearLayoutManager
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.DialogReserveBinding
import com.gh.gamecenter.databinding.DialogReserveItemBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.ReserveOnlineEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.mygame.MyGameActivity
import com.halo.assistant.HaloApp
import com.lightgame.adapter.BaseRecyclerAdapter

class ReserveDialog : BaseDialogFragment() {

    private lateinit var reserveOnlineEntity: ReserveOnlineEntity
    val games: List<GameEntity>
        get() = reserveOnlineEntity.games

    private var mDismissListener: (() -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {
            dismiss()
            return
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val binding: DialogReserveBinding = DialogReserveBinding.inflate(layoutInflater, null, false)

        reserveOnlineEntity = arguments?.getParcelable(RESERVE_ONLINE) ?: ReserveOnlineEntity()

        binding.tvTitle.text =
            resources.getString(R.string.dialog_reserve_title, reserveOnlineEntity.gamesTotal).fromHtml()
        binding.tvViewAllAppointment.setOnClickListener {
            SensorsBridge.trackAppointmentGameOnlineDialogClick(buttonName = "查看全部预约")
            val intent = MyGameActivity.getIntentWithConfig(requireContext(), MyGameActivity.RESERVATION_INDEX)
            startActivity(intent)
        }

        val adapter = ReserveDialogAdapter(requireContext(), games)
        binding.rvGames.layoutManager = FixLinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.rvGames.adapter = adapter

        val exposureListener = ExposureListener(this, adapter)
        binding.rvGames.addOnScrollListener(exposureListener)

        binding.ivClose.setOnClickListener {
            dismissAllowingStateLoss()
        }

        checkHasAutoDownload(binding)

        dialog?.setCanceledOnTouchOutside(true)
        return binding.root
    }

    private fun checkHasAutoDownload(binding: DialogReserveBinding) {
        if (reserveOnlineEntity.wifiAutoDownloadTotal > 0) {
            // 开启自动下载
            binding.tvAutoDownloadTips.goneIf(false)
            var firstAutoDownloadGameName =
                reserveOnlineEntity.games.find { it.wifiAutoDownload && !it.isLandPageAddressDialog() }?.name

            if(!firstAutoDownloadGameName.isNullOrBlank() && firstAutoDownloadGameName.length > GAME_NAME_SHOW_MAX_LENGTH){
                firstAutoDownloadGameName = "${firstAutoDownloadGameName.take(GAME_NAME_SHOW_MAX_LENGTH-1)}..."
            }
            val isWifiOpen = NetworkUtils.isWifiConnected(HaloApp.getInstance())
            binding.tvAutoDownloadTips.text =
                if (isWifiOpen) {
                    if (firstAutoDownloadGameName.isNullOrBlank()) {
                        getString(
                            R.string.reserve_reminder_auto_download,
                            "${reserveOnlineEntity.wifiAutoDownloadTotal}"
                        )
                    } else {
                        getString(
                            R.string.reserve_reminder_auto_download_with_name,
                            firstAutoDownloadGameName,
                            "${reserveOnlineEntity.wifiAutoDownloadTotal}"
                        )
                    }
                } else {
                    if (firstAutoDownloadGameName.isNullOrBlank()) {
                        getString(
                            R.string.reserve_reminder_wait_for_wifi_to_auto_download,
                            "${reserveOnlineEntity.wifiAutoDownloadTotal}"
                        )
                    } else {
                        getString(
                            R.string.reserve_reminder_wait_for_wifi_to_auto_download_with_name,
                            firstAutoDownloadGameName,
                            "${reserveOnlineEntity.wifiAutoDownloadTotal}"
                        )
                    }
                }

            binding.tvAutoDownloadTips.setOnClickListener {
                SensorsBridge.trackAppointmentGameOnlineDialogClick(buttonName = "查看进度")
                val intent = DownloadManagerActivity.getDownloadMangerIntent(requireContext(), "")
                startActivity(intent)
            }
        } else {
            binding.tvAutoDownloadTips.goneIf(true)
        }
    }


    fun setOnDismissListener(dismissListener: () -> Unit) {
        mDismissListener = dismissListener
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        SensorsBridge.trackAppointmentGameOnlineDialogClick(buttonName = "关闭弹窗")
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let {
            it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val params = it.attributes
            params.width = DisplayUtils.dip2px(300F)
            it.attributes = params
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mDismissListener?.invoke()
    }

    companion object {
        const val RESERVE_ONLINE = "reserve_online"
        private const val GAME_NAME_SHOW_MAX_LENGTH = 8

        @JvmStatic
        fun getInstance(reserveOnlineEntity: ReserveOnlineEntity?) = ReserveDialog().apply {
            arguments = Bundle().apply {
                putParcelable(RESERVE_ONLINE, reserveOnlineEntity)
            }
        }
    }
}

class ReserveDialogAdapter(
    context: Context,
    private val games: List<GameEntity>
) :
    BaseRecyclerAdapter<ReserveDialogItemViewHolder>(context), IExposable {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReserveDialogItemViewHolder {
        return ReserveDialogItemViewHolder(parent.toBinding())
    }

    override fun getItemCount(): Int {
        return if (games.size > 8) 8 else games.size
    }

    override fun onBindViewHolder(holder: ReserveDialogItemViewHolder, position: Int) {
        val entity = games[position]
        holder.binding.icon.displayGameIcon(entity)
        holder.binding.gameNameTv.text = entity.name
        holder.itemView.setOnClickListener {
            SensorsBridge.trackAppointmentGameOnlineDialogClick(
                "游戏",
                entity.id,
                entity.name ?: "",
                entity.categoryChinese,
            )
            GameDetailActivity.startGameDetailActivity(mContext, entity.id, "(预约弹窗)", entity.exposureEvent)
        }
        entity.exposureEvent = ExposureEvent.createEvent(
            entity,
            listOf(ExposureSource("预约上线弹窗", ""))
        )
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return games.getOrNull(pos)?.exposureEvent
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return null
    }

}

class ReserveDialogItemViewHolder(val binding: DialogReserveItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)