package com.swago.room.hongbao

import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.fragment.app.viewModels
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.im.ImConstant
import com.swago.baseswago.model.im.RoomChatMsgBean
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.UserInfo
import com.swago.loadUrl
import com.swago.room.R
import com.swago.room.databinding.DialogRedEnvelopeResultBinding
import com.swago.room.util.IMSender
import com.swago.room.vm.RoomOtherVm
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import org.json.JSONObject

class RedEnvelopResultDialog : BaseXDFragment<DialogRedEnvelopeResultBinding>() {

    init {
        setGravity(Gravity.CENTER)
        setCanCancel(false)
        setDimAmount(0.5f)
    }

    private val roomOtherVm by viewModels<RoomOtherVm>()
    private var name = ""

    var openGiftDialog:(()->Unit)? = null
    var addSenderMsgToRoomChatList: ((roomChatMsgBean: RoomChatMsgBean) -> Unit)? = null

    companion object {
        fun newInstance(id: String, avatar: String, name: String): RedEnvelopResultDialog {
            val args = Bundle()
            args.putString("id", id)
            args.putString("avatar", avatar)
            args.putString("name", name)
            val fragment = RedEnvelopResultDialog()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initOther() {
        arguments?.let {
            val id = it.getString("id", "")
            val avatar = it.getString("avatar", "")
            name = it.getString("name", "")
            context?.let {
                binding.ivAvatar.loadUrl(it, avatar)
            }
            binding.tvFromUser.text =
                AppContext.getContext().resources.getString(R.string.from_who_red_envelope)
                    .format(name)
            roomOtherVm.getRedEnvelopeCoin(id)

            binding.tvReceive.setOnClickListener(object:NoDoubleClickListener(){
                override fun onClick() {
                    dismissAllowingStateLoss()
                }
            })

            binding.tvToSendGift.setOnClickListener(object:NoDoubleClickListener(){
                override fun onClick() {
                    openGiftDialog?.invoke()
                    dismissAllowingStateLoss()
                }
            })
        }
    }

    override fun initLiveData() {
        roomOtherVm.receiveRedEnvelopeResultLiveData.observe(this) {
            binding.tvCoin.visibility = View.VISIBLE
            binding.tvCoin.text = it
            binding.tvCongratulation.text = AppContext.getContext().resources.getString(R.string.congratulation)
            binding.tvReceive.text = AppContext.getContext().resources.getString(R.string.receive_red_envelope_coin)
            binding.tvToSendGift.visibility = View.VISIBLE
            val content =  AppContext.getContext().resources.getString(R.string.thank_for_boss).format(it,name)
            UserInfo.getUserInfo()?.let {
                val roomChatMsgBean = RoomChatMsgBean()
                roomChatMsgBean.content = content
                roomChatMsgBean.sendName = it.user_name
                roomChatMsgBean.senderId = it.id
                roomChatMsgBean.senderLevel = it.user_wealth_level.toInt()
                roomChatMsgBean.isBenefit = it.is_benefit
                roomChatMsgBean.roomId = SwagoRoomManager.iRoomInfo?.getRoomId()?:""
                roomChatMsgBean.isPrettyAccount = it.is_pretty_account
                roomChatMsgBean.isService = it.is_service
                roomChatMsgBean.isOfficial = it.is_official
                roomChatMsgBean.isCrown = it.is_crown
                roomChatMsgBean.isCup = it.is_cup
                addSenderMsgToRoomChatList?.invoke(roomChatMsgBean)

                val jsonObject = JSONObject()
                jsonObject.put("senderId", it.id)
                jsonObject.put("sendName", it.user_name)
                jsonObject.put("senderLevel", it.user_wealth_level)
                jsonObject.put("isBenefit", it.is_benefit)
                jsonObject.put("content", content)
                jsonObject.put("roomId", SwagoRoomManager.iRoomInfo?.getRoomId()?:"")
                jsonObject.put("isPrettyAccount", it.is_pretty_account)
                jsonObject.put("isService", it.is_service)
                jsonObject.put("isOfficial", it.is_official)
                jsonObject.put("isCrown", it.is_crown)
                jsonObject.put("isCup", it.is_cup)

                val jsonObjectType = JSONObject()
                jsonObjectType.put("type", ImConstant.room_chat_text)
                jsonObjectType.put("data", jsonObject)
                val toByteArray = jsonObjectType.toString().encodeToByteArray()
                SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                    IMSender.sendGroupCusMessage(
                        toByteArray,
                        iRoomInfo.getRoomGroupId(),
                        object : V2TIMValueCallback<V2TIMMessage> {
                            override fun onSuccess(t: V2TIMMessage?) {
                                LogUtil.d("发送成功")
                            }

                            override fun onError(code: Int, desc: String?) {}

                        },
                        V2TIMMessage.V2TIM_PRIORITY_NORMAL
                    )
                }

            }

        }


        roomOtherVm.receiveErrorResultLiveData.observe(this){
            when(it){
                538 -> {
                    //被抢光了
                    binding.tvCoin.visibility = View.GONE
                    binding.tvCongratulation.text = AppContext.getContext().resources.getString(R.string.sorry_fail_to_get)
                    binding.tvReceive.text = AppContext.getContext().resources.getString(R.string.konw)
                    binding.tvToSendGift.visibility = View.GONE
                }

                540 -> {
                    //已经抢过该红包了
                    binding.tvCoin.visibility = View.GONE
                    binding.tvCongratulation.text = AppContext.getContext().resources.getString(R.string.already_receive_red_envelope)
                    binding.tvReceive.text = AppContext.getContext().resources.getString(R.string.konw)
                    binding.tvToSendGift.visibility = View.GONE
                }
            }
        }
    }
}