package com.gamedog.vididin.features.withdraw

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
import com.ama.core.architecture.appBase.AppViewsEmptyViewModelActivity
import com.ama.core.architecture.highlightpro.HighlightPro
import com.ama.core.architecture.highlightpro.parameter.Constraints
import com.ama.core.architecture.highlightpro.parameter.HighlightParameter
import com.ama.core.architecture.highlightpro.parameter.MarginOffset
import com.ama.core.architecture.highlightpro.shape.RectShape
import com.ama.core.architecture.util.ResUtil
import com.ama.core.architecture.util.ResUtil.dp
import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.setOnClickBatch
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.beans.RecordCash
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.features.withdraw.widget.WithDrawItemView
import com.gamedog.vididin.manager.GuideManager
import com.gamedog.vididin.manager.TaskManager
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 dagger.hilt.android.AndroidEntryPoint
import com.viddin.videos.free.databinding.ActivityWithdrawBinding as ViewBinding



@AndroidEntryPoint
class WithDrawActivity : AppViewsEmptyViewModelActivity<ViewBinding>() {
    private val mItemViewList: MutableList<WithDrawItemView> = mutableListOf()


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

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

    override fun ViewBinding.initViews() {
        titlebar.setTitleText(R.string.sacar)

        mItemViewList.add(withdraw01)
        mItemViewList.add(withdraw10)
        mItemViewList.add(withdraw20)
        mItemViewList.add(withdraw50)
        mItemViewList.add(withdraw100)
        mItemViewList.add(withdraw300)

        withdraw01.setNumAndAction(0, 0.1,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdraw10.setNumAndAction(1, 10.0,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdraw20.setNumAndAction(2, 20.0,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdraw50.setNumAndAction(3, 50.0,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdraw100.setNumAndAction(4, 100.0,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdraw300.setNumAndAction(5, 300.0,
            { itemIndex->
                handleGotoWithdraw(itemIndex)
            })

        withdrawPix2.setIconAndText(R.mipmap.pix2_big, R.string.pix2, {
            WithdrawBindBankDialog(this@WithDrawActivity, null).setWithDrawCashNum(0.0).show()
        })

        withdrawPix2.setSelectedState(true)

        setOnClickBatch(withdrawRecord) {
            when(this) {
                withdrawRecord -> {
                    Router.WithdrawRecord.startActivity(this@WithDrawActivity)
                }
            }
        }

        updateUICashTotal()

        if (TaskManager.instance().newbieFirstWithdrawStatus().getStatusBean().hasWithdrawed) {
            withdraw01.isVisible = false
        }

        StatisticUtil.reportEvents(StatisticUtil.KEY_Withdrawal_Show)
    }


    private fun handleGotoWithdraw(itemIndex: Int) {
        val cashNum = mItemViewList.get(itemIndex).getCashNum()
        if (cashNum > 1.0) {
            WithdrawManager.instance().setItemStarted(itemIndex)
            gotoWithdrawSubActivity(itemIndex)
        } else {
            val hasBindBank = AccountManager.hasValidBankInfo()
            if (!hasBindBank) {
                WithdrawBindBankDialog(this@WithDrawActivity, ::startRealWithdraw ).setWithDrawCashNum(cashNum).show()
            } else {
                WithdrawInfoConfirmDialog(this@WithDrawActivity, ::startRealWithdraw).setWithDrawCashNum(cashNum).show()
            }
        }

        StatisticUtil.reportEvents(StatisticUtil.KEY_Withdrawal_finsh, mapOf("Withdrawal_Position" to cashNum))
    }


    private fun startRealWithdraw(cashNum: Double) {
        // payCashNum: Double, payItemId: Int, paySubItemId: Int, payItemLoopIndex: Int
        WithdrawManager.instance().startWithdrawReal(cashNum, 0, 0, 1)
        WithdrawManager.instance().setItemStarted(0)
    }

    private fun updateUICashTotal() {
        binding.tvCashTotal.text = String.format("%.2f", AccountManager.getCash())
        binding.tvAllCashHasWithdrawed.text = buildString {
            append(ResUtil.getString(R.string.cash))
            append(" ")
            append(WithdrawManager.instance().getHasWithdrawSuccessCashCount())
        }
    }

    private fun udpateItemListUI() {
        mItemViewList.forEach {
            it.updateProgressAndButUI()
        }
    }


    override fun ViewBinding.initListeners() {
        registerEvents({ data->
            when (data?.mEventType) {
                VididinEvents.Event_Account_Cash_Changed -> {
                    updateUICashTotal()
                }

                VididinEvents.EVENT_AD_WATCHED_FOR_WITHDRAW_SMALL -> {
                    /*val notifyData: WatchAdNotifyBean<Float> = data.mData as WatchAdNotifyBean<Float>
                    requestInit(notifyData.extraData)*/
                }

                VididinEvents.EVENT_WITHDRAW_RESULT_UPDATED -> {
                    try {
                        val record = data.mData as RecordCash
                        if (record.withdrawItemIndex == 0) {
                            showTransactionResultDialog(record)
                        }
                        updateUICashTotal()
                        mItemViewList[record.withdrawItemIndex].updateProgressAndButUI()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                VididinEvents.EVENT_WITHDRAW_ITEM_LIST_CHANGED -> {
                    udpateItemListUI()
                }

                VididinEvents.EVENT_BANK_INFO_CHANGED -> {
                    withdrawPix2.updateBankAccountInfo()
                }
            }

        }, VididinEvents.Event_Account_Cash_Changed,
            VididinEvents.EVENT_AD_WATCHED_FOR_WITHDRAW_SMALL,
            VididinEvents.EVENT_WITHDRAW_RESULT_UPDATED,
            VididinEvents.EVENT_WITHDRAW_ITEM_LIST_CHANGED,
            VididinEvents.EVENT_BANK_INFO_CHANGED)

        readTransactionsAndShowResult()

        if (needShowGuide()) {
            binding.tvCashTotal.postDelayed({
                showGuide()
            }, 5)
        }
    }


    override fun ViewBinding.initObservers() {
        //TODO("Not yet implemented")
    }

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

    private fun showFailDialog(failHintRes: Int) {
        WithdrawFailDialog(this@WithDrawActivity, failHintRes).show()
    }

    private fun gotoWithdrawSubActivity(selectedIndex: Int) {
        Router.WithdrawSub.startActivity(this, selectedIndex)
    }



    // ------------------------ new added -------------------------//

    private fun readTransactionsAndShowResult() {
        val recordList = WithdrawManager.instance().getClonedRecordList()
        recordList.forEach {
            showTransactionResultDialog(it)
        }
    }

    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 needShowGuide(): Boolean {
        return GuideManager.instance().getCurGuideIndex() == VidiConst.GUIDE_INDEX_CASH_GOLD
    }

    private fun saveGuideState() {
        GuideManager.instance().setGuideIndex(VidiConst.GUIDE_INDEX_WITHDRAW)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private fun showGuide() {
        HighlightPro.with(this@WithDrawActivity)
            .setHighlightParameter {
                HighlightParameter.Builder()
                    .setHighlightView(mItemViewList.get(0), {
                    })
                    .setTipsViewId(R.layout.guide_step_withdraw)
                    .setHighlightShape(RectShape(10.dp, 10.dp, 10.dp))
                    .setHighlightHorizontalPadding(0.dp)
                    .setConstraints(Constraints.TopToBottomOfHighlight + Constraints.EndToEndOfHighlight)
                    .setMarginOffset(MarginOffset(top = -40.dp.toInt(), end = 0.dp.toInt()))
                    .build()
            }
            .setBackgroundColor("#cc000000".toColorInt())
            .setOnShowCallback { index ->

            }
            .setOnDismissCallback {
                saveGuideState()
                handleGotoWithdraw(0)
            }
            .interceptBackPressed(true)
            .show()

        StatisticUtil.reportEvents(StatisticUtil.KEY_Guide, mapOf("Guide" to 3))

    }


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

}