package com.gamedog.vididin.features.benefit

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.activity.viewModels
import com.ama.core.architecture.appBase.AppViewsActivity
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.ResUtil
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.viddin.videos.free.R
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.features.benefit.widget.BenefitTaskItemView
import com.gamedog.vididin.main.fragments.task.DailySignDialog
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.gamedog.vididin.manager.TaskManager
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_AD
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_VIDEO
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_SIGN
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_ZERO_BUY
import dagger.hilt.android.AndroidEntryPoint
import kotlin.getValue
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_FINISH
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_CLAIMED
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_EXPIRED
import com.gamedog.vididin.router.Router
import com.viddin.videos.free.databinding.ActivityBenefitBinding as ViewBinding
import com.gamedog.vididin.main.MainUiState as UiState
import com.gamedog.vididin.main.MainViewModel as ViewModel


@AndroidEntryPoint
class BenefitActivity : AppViewsActivity<ViewBinding, UiState, ViewModel>(), OnTabStyleListener {

    private val mSubTaskViewList = mutableListOf<BenefitTaskItemView>()


    override val mViewModel: ViewModel by viewModels()
    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(contentRoot)
    }


    override fun ViewBinding.initViews() {
        titlebar.setTitleText(R.string.benefit)
        initViewsByTaskState()
    }


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

        val boxStatus = TaskManager.instance().boxTaskStatus()
        val curSubBoxState = boxStatus.getCurrentBoxState()
        val subTaskCount = curSubBoxState!!.tasks.size
        val reward = curSubBoxState.reward_value
        StatisticUtil.reportEvents(StatisticUtil.KEY_Welfare_Show, mapOf(
            "total_amount" to reward,
            "chest_count" to subTaskCount,
            "task_type" to boxStatus.getCurrentBoxIndex().toString(),
            "task_progress" to boxStatus.getCurrentBoxTotalProgress(),
        ))
    }


    override fun ViewBinding.initListeners() {
        registerEvents({ data->
            when (data?.mEventType) {
                VididinEvents.EVENT_BOX_TASK_STATE_CHANGED -> {
                    updateUI()
                }
            }
        }, VididinEvents.EVENT_BOX_TASK_STATE_CHANGED)
    }

    override fun ViewBinding.initObservers() {

    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {

    }

    override fun onTabIsDarkFont(isDarkFont: Boolean) {

    }


    private fun initViewsByTaskState() {
        initAddSubTaskViews()
        updateSubTasksUI()
        updateTopBoxesUI()
    }

    private fun updateUI() {
        updateSubTasksUI()
        updateTopBoxesUI()
        binding.counterdownTv.restartTimer()
    }

    private fun initAddSubTaskViews() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        var subTaskIndex = taskStateHelper.getCurrentBoxIndex()
        if (subTaskIndex >= 0) {
            val currentBoxState = taskStateHelper.getStatusBean().boxList[subTaskIndex]
            currentBoxState.tasks.forEachIndexed { index, subTask ->
                val separateLine = View(this@BenefitActivity)
                separateLine.setBackgroundResource(R.color.gray_f2)
                binding.llSubTaskContainer.addView(separateLine, ViewGroup.LayoutParams.MATCH_PARENT, ResUtil.getPixelSize(R.dimen.dp1))

                val subTaskView = BenefitTaskItemView(this@BenefitActivity)
                subTaskView.setActionFun { handleActionButClicked(subTask.task_type) }
                val subViewParam = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                subViewParam.topMargin = ResUtil.getPixelSize(R.dimen.dp10)
                subViewParam.bottomMargin = ResUtil.getPixelSize(R.dimen.dp10)
                binding.llSubTaskContainer.addView(subTaskView, subViewParam)

                mSubTaskViewList.add(subTaskView)
            }
        }

    }

    private fun handleActionButClicked(taskType: Int) {
        when (taskType) {
            BOX_SUB_TASK_TYPE_AD -> {
                Router.WatchAd.startActivity(this@BenefitActivity, VidiConst.WATCH_AD_FOR_BOX_TASK)
            }

            BOX_SUB_TASK_TYPE_SIGN -> {
                DailySignDialog(this@BenefitActivity).show()
            }

            BOX_SUB_TASK_TYPE_VIDEO -> {
                finish()
                NotifyMan.instance().sendEvent(VididinEvents.EVENT_JUMP_2_VIDEO, null)
            }

            BOX_SUB_TASK_TYPE_ZERO_BUY -> {
                Router.ZeroBuy.startActivity(this@BenefitActivity)
            }
        }

    }

    private fun updateSubTasksUI() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        val currentBoxIndex = taskStateHelper.getCurrentBoxIndex()
        val subTaskStateList = taskStateHelper.getStatusBean().boxList[currentBoxIndex].tasks

        if (subTaskStateList.size == mSubTaskViewList.size) {
            mSubTaskViewList.forEachIndexed { index, view ->
                view.updateUIByState(subTaskStateList[index], currentBoxIndex,index)
            }
        }
    }

    private fun updateTopBoxesUI() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        val boxStateList = taskStateHelper.getStatusBean().boxList

        with (binding) {
            boxStateList.forEachIndexed { index, curBoxState ->
                val stateEnum = taskStateHelper.getBoxStateEnum(index)
                if (index == 0) {
                    ivSubtask1.setImageResource(getIconResByState(stateEnum))
                    tvSubtask1State.setText(getStrResByState(stateEnum))
                    tvSubtask1State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask1Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawablesWithIntrinsicBounds(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                        //setText(ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value)
                    }
                }

                if (index == 1) {
                    ivSubtask2.setImageResource(getIconResByState(stateEnum))
                    tvSubtask2State.setText(getStrResByState(stateEnum))
                    tvSubtask2State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask2Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_FINISH || stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawablesWithIntrinsicBounds(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                    }
                }

                if (index == 2) {
                    ivSubtask3.setImageResource(getIconResByState(stateEnum))
                    tvSubtask3State.setText(getStrResByState(stateEnum))
                    tvSubtask3State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask3Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_FINISH || stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawablesWithIntrinsicBounds(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                    }
                }
            }

            val couldClaimCashNum = taskStateHelper.getCouldClaimCashNum()
            with (tvResgatar) {
                if (couldClaimCashNum > 0) {
                    setBackgroundResource(R.mipmap.bg_but_green_long)
                    isClickable = true
                } else {
                    setBackgroundResource(R.mipmap.but_bg_grady)
                    isClickable = false
                }

                setOnClickListener {
                    if (taskStateHelper.executeClaimCash()) {
                        //AndroidUtil.showToast(String.format(ResUtil.getString(R.string.has_claim_box_cash_hint), couldClaimCashNum))
                        AndroidUtil.showCustomToast(String.format(ResUtil.getString(R.string.has_claim_box_cash_hint), couldClaimCashNum))
                    }
                }
            }


            // 总进度条, 奖励金额
            val totalProgress = taskStateHelper.getCurrentBoxTotalProgress()
            progressTasks.setProgress(totalProgress)
            tvProgressNum.text = "($totalProgress%)"
            tvHintRewardNum.text = buildString {
                append(ResUtil.getString(R.string.cash))
                append(" ")
                append(taskStateHelper.getStatusBean().boxList[taskStateHelper.getCurrentBoxIndex()].reward_value)
            }
        }
    }

    private fun getIconResByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.mipmap.benefit_item_expired
            STATE_FINISH, STATE_CLAIMED -> return R.mipmap.benefit_item_finished
            else -> return R.mipmap.benefit_item_ongoing
        }
    }

    private fun getStrResByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.string.expired
            STATE_FINISH, STATE_CLAIMED -> return R.string.finished
            else -> return R.string.ongoing
        }
    }

    private fun getStrColorByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.color.gray_60
            STATE_FINISH, STATE_CLAIMED -> return R.color.green_39
            else -> return R.color.red_5c
        }
    }

    private fun getRewardTvDrawableRes(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.mipmap.icon_cash_s_disable
            STATE_CLAIMED -> return R.mipmap.icon_check_mark
            else -> return R.mipmap.icon_cash_s
        }
    }


    companion object {
        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, BenefitActivity::class.java))
        }
    }

}