package com.swago.room.hongbao

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.gyf.immersionbar.ImmersionBar
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.dialog.PayDialog
import com.swago.baseswago.model.live.RoomConfig
import com.swago.baseswago.util.*
import com.swago.room.R
import com.swago.room.databinding.DialogRedEnvelopeBinding
import com.swago.room.dialog.UnReachLevelDialog
import com.swago.room.vm.RoomOtherVm
import com.swago.room.vm.RoomVm

/**
 *@date 2022/4/9 15:32
 *description:
 */
class RedEnvelopeDialog : BaseXDFragment<DialogRedEnvelopeBinding>() {

    init {
        setGravity(Gravity.BOTTOM)
        setCanCancel(true)
        setDimAmount(0f)
    }

    private val roomOtherVm by viewModels<RoomOtherVm>()

    companion object {
        fun newInstance(roomConfig: RoomConfig?): RedEnvelopeDialog {
            val args = Bundle()
            args.putParcelable("roomConfig", roomConfig)
            val fragment = RedEnvelopeDialog()
            fragment.arguments = args
            return fragment
        }
    }

    private var roomConfig: RoomConfig? = null
    private var coinIsAchieve = false
    private var redEnvelopeNumIsAchieve = false

    private var coin: String = "0"
    private var num = "0"

    override fun initOther() {
        activity?.let {
            KeyboardUtils.registerSoftInputChangedListener(it.window, listener)
        }

        binding.ivHelp.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                binding.clRedEnvelope.visibility = View.INVISIBLE
                binding.clRule.visibility = View.VISIBLE
            }
        })

        binding.ivBack.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                binding.clRedEnvelope.visibility = View.VISIBLE
                binding.clRule.visibility = View.INVISIBLE
            }
        })

        arguments?.let { bundle ->
            roomConfig = bundle.getParcelable("roomConfig")
            roomConfig?.let {
                if (it.red_package != null) {
                    binding.tvRule.text = it.red_package.rule
                    binding.etInputCoin.hint =
                        AppContext.getContext().resources.getString(R.string.not_less_coin)
                            .format(it.red_package.total_min_coins)
                    binding.etInputCount.hint =
                        AppContext.getContext().resources.getString(R.string.at_last_red_num)
                            .format(it.red_package.total_min_num)
                    binding.tvDescribe.text =
                        AppContext.getContext().resources.getString(R.string.broadcast_red_envelope)
                            .format(it.red_package.all_notice_coins)
                }
            }
        }

        binding.etInputCoin.addTextChangedListener(coinTextWatcher)
        binding.etInputCount.addTextChangedListener(countTextWatcher)

        binding.tvSendRedEnvelope.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                SwagoLoading.showLoadingDialog(ActivityManagerUtil.get().currentActivity())
                roomOtherVm.sendRedEnvelope(coin, num.toInt())
            }
        })
    }

    override fun initLiveData() {
        roomOtherVm.sendSuccessLiveData.observe(this) {
            activity?.let {
                KeyboardUtils.hideSoftInputByToggle(it)
            }
            dismissAllowingStateLoss()
        }

        roomOtherVm.sendGiftCodeLiveData.observe(this) {
            when (it.code) {
                517 -> {
                    binding.tvNotEnough.visibility = View.VISIBLE
                    Toast.makeText(AppContext.getContext(), it.msg, Toast.LENGTH_SHORT).show()
                }
                542, 543 -> {
                    UnReachLevelDialog.newInstance(it.msg)
                        .show(parentFragmentManager, "UnReachLevelDialog")
                }
                else -> {
                    Toast.makeText(AppContext.getContext(), it.msg, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    private var coinTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            roomConfig?.let {
                coin = binding.etInputCoin.text.toString().trim()
                coinIsAchieve = if (coin.isEmpty()) {
                    false
                } else {
                    coin.toInt() >= it.red_package.total_min_coins
                }
                setTvSendRedEnvelopeState()
            }
        }
    }

    private var countTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            roomConfig?.let {
                num = binding.etInputCount.text.toString().trim()
                redEnvelopeNumIsAchieve = if (num.isEmpty()) {
                    false
                } else {
                    num.toInt() >= it.red_package.total_min_num
                }
                setTvSendRedEnvelopeState()
            }
        }

    }

    private fun setTvSendRedEnvelopeState() {
        if (coinIsAchieve && redEnvelopeNumIsAchieve) {
            if (coin.toInt() / num.toInt() >= 100) {
                binding.tvSendRedEnvelope.setBackgroundResource(R.drawable.shape_ff56b7_37)
            } else {
                binding.tvSendRedEnvelope.setBackgroundResource(R.drawable.shape_80ff56b7_all_38)
            }
        } else {
            binding.tvSendRedEnvelope.setBackgroundResource(R.drawable.shape_80ff56b7_all_38)
        }
    }

    override fun onDestroyView() {
        activity?.let {
            KeyboardUtils.unregisterSoftInputChangedListener(it.window)
        }
        binding.etInputCoin.removeTextChangedListener(coinTextWatcher)
        binding.etInputCount.removeTextChangedListener(countTextWatcher)
        super.onDestroyView()
    }

    var listener = KeyboardUtils.OnSoftInputChangedListener {
        val params = binding.clRedEnvelope.layoutParams as ConstraintLayout.LayoutParams
        params.bottomMargin = it
        binding.clRedEnvelope.layoutParams = params
    }
}