package com.swago.room.dialog

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.gyf.immersionbar.ImmersionBar
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.im.ImConstant.room_chat_text
import com.swago.baseswago.model.im.RoomChatMsgBean
import com.swago.baseswago.util.*
import com.swago.room.R
import com.swago.room.databinding.DialogSendMsgBinding
import com.swago.room.util.IMSender
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 *@date 2021/10/23 10:23
 *description:
 */
class SendMsgDialog : BaseXDFragment<DialogSendMsgBinding>() {

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(this).keyboardEnable(true).init()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setDimAmount(0f)
        setHeightMatchParent()
        setGravity(Gravity.BOTTOM)
    }


    override fun initOther() {
        context?.let {
            lifecycleScope.launch {
                delay(100)
                KeyboardUtils.showSoftInput(binding.et)
            }
        }

        binding.ivSend.isEnabled = false

        binding.cl.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                context?.let {
                    KeyboardUtils.hideSoftInput(binding.et)
                    dismissAllowingStateLoss()
                }

            }
        })

        binding.et.addTextChangedListener(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?) {
                val content = binding.et.text.toString()
                if (content.isNotEmpty()){
                    binding.ivSend.isEnabled = true
                    binding.ivSend.setImageResource(R.mipmap.send)
                    binding.ivSend.setBackgroundColor(ContextCompat.getColor(context!!,R.color._ff9300))
                }else{
                    binding.ivSend.isEnabled = false
                    binding.ivSend.setImageResource(R.mipmap.send_nable)
                    binding.ivSend.setBackgroundColor(ContextCompat.getColor(context!!,R.color.white))
                }
            }

        })

        binding.ivSend.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                val content = binding.et.text.toString()
                binding.et.setText("")
                if (content.isNotEmpty()) {
                    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
                        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)

                        val jsonObjectType = JSONObject()
                        jsonObjectType.put("type", 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
                            )
                        }

                    }
                }
            }
        })

    }

    override fun initLiveData() {

    }

    override fun dismiss() {
        binding.et.setText("")
        super.dismiss()
    }
}