package com.gamedog.vididin.features.withdraw

import android.app.Activity
import android.content.Intent
import android.text.Spannable
import android.text.SpannableString
import android.text.method.ScrollingMovementMethod
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.ama.core.architecture.appBase.AppViewsEmptyViewModelActivity
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.CommonItemDecoration
import com.ama.core.architecture.util.DateUtil
import com.ama.core.architecture.util.ResUtil
import com.ama.core.architecture.util.setOnClickBatch
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.beans.RecordCash
import com.gamedog.vididin.beans.WatchAdNotifyBean
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.features.withdraw.dialogs.WithdrawBindBankDialog
import com.gamedog.vididin.features.withdraw.dialogs.WithdrawFailDialog
import com.gamedog.vididin.features.withdraw.dialogs.WithdrawInfoConfirmDialog
import com.gamedog.vididin.features.withdraw.dialogs.WithdrawSuccessDialog
import com.gamedog.vididin.manager.WithdrawItem
import com.gamedog.vididin.manager.WithdrawManager
import com.gamedog.vididin.manager.WithdrawManager.Companion.TRANSACTION_STATE_FAIL
import com.gamedog.vididin.manager.WithdrawManager.Companion.TRANSACTION_STATE_ONGOING
import com.gamedog.vididin.manager.WithdrawManager.Companion.TRANSACTION_STATE_SUCCESS
import com.gamedog.vididin.router.Router
import com.viddin.videos.free.R
import dagger.hilt.android.AndroidEntryPoint
import kotlin.getValue
import com.viddin.videos.free.databinding.ActivityWithdrawSubBinding as ViewBinding



@AndroidEntryPoint
class WithDrawSubActivity : AppViewsEmptyViewModelActivity<ViewBinding>() {
    private lateinit var mCurItem: WithdrawItem
    private var mSelectingIndex: Int = 0
    private var mType: Int = 0
    private val mAdapter: WithdrawSubAdapter by lazy { WithdrawSubAdapter( { itemIndex ->
        handleSubItemClicked(itemIndex)
    }) }


    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

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

    override fun ViewBinding.initViews() {
        mType = intent.getIntExtra(EXTRA_TYPE, 0)
        titlebar.setTitleText(R.string.title_withdraw_sub)
        titlebar.setTitleTextSize(17F)
        recyclerView.layoutManager = LinearLayoutManager(this@WithDrawSubActivity, LinearLayoutManager.HORIZONTAL, false)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(CommonItemDecoration.create(18, 0, false))

        tvHint.movementMethod = ScrollingMovementMethod.getInstance()
        tvHint.isSelected = true

        val foreColorSpan = ForegroundColorSpan(ResUtil.getColor(R.color.green_39))
        val ssb = SpannableString(tvTopHint.text).apply {
            setSpan(foreColorSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
        tvTopHint.text = ssb


        setOnClickBatch(flAction) {
            when(this) {
                flAction -> {
                    when (mCurItem.subItemList[mSelectingIndex].withdrawState) {
                        WithdrawManager.STATE_NEED_WATCH_AD -> {
                            gotoWatchAd()
                            sendClickStatistic()
                        }

                        WithdrawManager.STATE_COULD_WITHDRAW -> {
                            tryRequestWithdraw()
                        }
                    }
                }
            }
        }
    }

    private fun tryRequestWithdraw() {
        val subBean = mCurItem.subItemList[mSelectingIndex]
        if (AccountManager.isBankAccountExist()) {
            WithdrawInfoConfirmDialog(this@WithDrawSubActivity, { cashNum -> startRealWithdraw(cashNum) }).setWithDrawCashNum(subBean.cashTotal).show()
        } else {
            WithdrawBindBankDialog(this@WithDrawSubActivity, { cashNum -> startRealWithdraw(cashNum) }).setWithDrawCashNum(subBean.cashTotal).show()
        }
    }


    private fun startRealWithdraw(cashNum: Double) {
        val withdrawItemIndex = mCurItem.index
        val withdrawSubItemIndex = mCurItem.subItemList[mSelectingIndex].dayIndex
        WithdrawManager.instance().startWithdrawReal(cashNum, withdrawItemIndex, withdrawSubItemIndex, mCurItem.loopIndex)
        WithdrawManager.instance().setItemStarted(0)
    }


    private fun showSuccessDialog(cashNum: Double) {
        WithdrawSuccessDialog(this, cashNum).show()
    }

    private fun showFailDialog(errorHintRes: Int) {
        WithdrawFailDialog(this, errorHintRes).show()
    }

    private fun handleSubItemClicked(itemIndex: Int) {
        val mMaxDayIndex = DateUtil.getDaysPassed(mCurItem.startMs)
        if (itemIndex >= 0 && itemIndex <= mMaxDayIndex) {
            mSelectingIndex = itemIndex
            updateUI()
        }
    }

    private fun gotoWatchAd() {
        Router.WatchAd.startActivity(this, VidiConst.WATCH_AD_FOR_WITHDRAW_BIG, AndroidUtil.object2Json(mCurItem))
    }

    override fun ViewBinding.initListeners() {
        registerEvents({ data->
            when (data?.mEventType) {
                VididinEvents.EVENT_AD_WATCHED_FOR_WITHDRAW_BIG -> {
                    handleAdWatched(data.mData as WatchAdNotifyBean<WithdrawItem>)
                }

                VididinEvents.EVENT_WITHDRAW_SUB_ITEM_PROGRESS_UPDATED -> {
                    if ((data.mData as Int) == mSelectingIndex) {
                        updateProgressUI()
                    }
                }

                VididinEvents.EVENT_WITHDRAW_SELECTED_SUB_ITEM_CHANGED -> {
                    updateUI()
                }

                VididinEvents.EVENT_WITHDRAW_RESULT_UPDATED -> {
                    try {
                        val record = data.mData as RecordCash
                        if (record.withdrawItemIndex > 0) {
                            showTransactionResultDialog(record)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }, VididinEvents.EVENT_AD_WATCHED_FOR_WITHDRAW_BIG,
            VididinEvents.EVENT_WITHDRAW_SUB_ITEM_PROGRESS_UPDATED,
            VididinEvents.EVENT_WITHDRAW_SELECTED_SUB_ITEM_CHANGED,
            VididinEvents.EVENT_WITHDRAW_RESULT_UPDATED )


        mCurItem = WithdrawManager.instance().getItem(mType)
        if (mCurItem.startMs <= 0L) {
            WithdrawManager.instance().startItem(mCurItem)
        }
        mSelectingIndex = DateUtil.getDaysPassed(mCurItem.startMs)
        updateUI()
    }

    private fun showTransactionResultDialog(record: RecordCash) {
        if (!record.hasShowResultDialog && record.withdrawState != TRANSACTION_STATE_ONGOING) {
            WithdrawManager.instance().updateRecordHasNotifyState(record.uuid)
            when (record.withdrawState) {
                TRANSACTION_STATE_SUCCESS -> {
                    showSuccessDialog(record.amountNum)
                }

                TRANSACTION_STATE_FAIL -> {
                    showFailDialog(WithdrawManager.instance().getFailHintStrRes(record.withdrawFailType))
                }
            }
        }
    }

    private fun handleAdWatched(adNotifyBean: WatchAdNotifyBean<WithdrawItem>) {
        val withdrawItemBean = adNotifyBean.extraData
        if (WithdrawManager.instance().addAdEarnForSubBean(withdrawItemBean.index,
                mSelectingIndex, adNotifyBean.earnMoneyNum * VidiConst.WITHDRAW_REWARD_AD_REVENUE_PERCENT)) {
            updateUI()
        }
    }

    private fun updateUI() {
        with(binding) {
            mAdapter.mSelectedSubIndex = mSelectingIndex
            mAdapter.submitList(mCurItem.subItemList)
            mAdapter.notifyDataSetChanged()
            recyclerView.scrollToPosition(mSelectingIndex)

            tvCashTotal.text = mCurItem.totalCashNum.toString()
            progressBar.enableTouch(false)
            progressBar.setBarColor(forColor = R.color.green_ce)
            updateProgressUI()
        }
    }

    private fun updateProgressUI() {
        with(binding) {
            val subBean = mCurItem.subItemList[mSelectingIndex]
            val curProgress = subBean.currentAdProgress
            progressBar.setProgress(curProgress)
            tvProgress.text = "$curProgress%"

            ivAction.isVisible = curProgress < 100
            if (curProgress < 100) {
                tvAction.setText(R.string.withdraw_cash_out)
                flAction.isClickable = true
                flAction.alpha = 1F

                sendShowStatistic()
            } else {
                var actionText = R.string.withdraw_cash_out
                when(subBean.withdrawState) {
                    WithdrawManager.STATE_COULD_WITHDRAW -> {
                        actionText = R.string.withdraw_cash_out
                        flAction.isClickable = true
                        flAction.alpha = 1F
                    }

                    WithdrawManager.STATE_WITHDRAWING -> {
                        actionText = R.string.pending
                        flAction.isClickable = false
                        flAction.alpha = 0.6F
                    }

                    WithdrawManager.STATE_HAS_WITHDRAWED -> {
                        actionText = R.string.withdraw_success
                        flAction.isClickable = false
                        flAction.alpha = 0.6F
                    }
                }
                tvAction.setText(actionText)
            }
        }
    }

    private fun sendShowStatistic() {
        StatisticUtil.reportEvents(StatisticUtil.KEY_RV_Button_Show, mapOf("Position" to "RV_Accelerate2"))
    }

    private fun sendClickStatistic() {
        StatisticUtil.reportEvents(StatisticUtil.KEY_RV_Button_Click_Game, mapOf("Position" to "RV_Accelerate2"))
    }

    override fun ViewBinding.initObservers() {

    }


    companion object {
        const val EXTRA_TYPE = "EXTRA_TYPE"
        internal fun startActivity(activity: Activity, withdrawType: Int) {
            activity.startActivity(Intent(activity.applicationContext,
                WithDrawSubActivity::class.java).apply { putExtra(EXTRA_TYPE, withdrawType) })
        }
    }
}

