package com.xty.base.act

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.graphics.Rect
import android.graphics.drawable.AnimationDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.hjq.toast.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.BuildConfig
import com.xty.base.R
import com.xty.base.adapter.ChatMSgAdapter
import com.xty.base.databinding.ActChatMsgBinding
import com.xty.base.view.AudioRecorderButton
import com.xty.base.vm.ChatMsgVm
import com.xty.common.Const
import com.xty.common.FileUtils
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.audioUtils.RecordAudio
import com.xty.common.event.MqttReceive
import com.xty.common.getImageUrl
import com.xty.common.picture.PictureUtils
import com.xty.common.picture.VideoCompressUtils
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.weight.LoadingView
import com.xty.network.model.ChatBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 *  聊天界面
 */
@Route(path = ARouterUrl.CHAT_MSG)
class ChatMsgAct : BaseVmAct<ChatMsgVm>() {
    val audioUtils by lazy { RecordAudio() }
    val compressLoad by lazy {
        LoadingView.Builder(this).setCancelable(false).setCancelOutside(false)
            .setMessage("视频压缩中...").cteated()
    }
    val madapter by lazy { ChatMSgAdapter(chatImage) }
    val binding by lazy { ActChatMsgBinding.inflate(layoutInflater) }
    var userId = "" //
    var toUserId = ""
    var fromUserId = ""
    var oldHeight = 0  //导航栏
    var chatImage = ""
    var fileType = 0 //当前发送的文件类型 1 照片 3 视频
    var fileUrl = "" //当前选择的文件的路径

    //录音
    val audioFile by lazy { FileUtils.getCacheFile(this) + File.separator + "audio" }
    var audioTime = 1 //录制时长
    var isMedicComplete = false //是否录制完成
    var mAnimView: ImageView? = null //播放语音动画view

    var isAudio = false//是否是语音输入

    val compressUtils by lazy {
        VideoCompressUtils({
            compressLoad.dismiss()
            mViewModel.saveChatMedia(
                it,
                Const.MESSAGE_PREFIX + fromUserId,
                fileType,
                toUserId,
                fromUserId
            )
        }, {
            compressLoad.dismiss()
            ToastUtils.show("视频压缩失败")

        })
    }

    override fun initData() {
        super.initData()
        isKeyBoard = false
        isDarkBar = true
        var title = intent.extras!!.getString("title")
        toUserId = intent.extras!!.getString("toUserId").toString()
        fromUserId = intent.extras!!.getString("fromUserId").toString()
        chatImage = intent.extras!!.getString("chatImage").toString()
        binding.title.mTvTitle.text = title
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.apply {
            (parent as (View)).setBackgroundColor(
                ContextCompat.getColor(
                    this@ChatMsgAct,
                    R.color.white
                )
            )
            setOnClickListener { finish() }
        }

//        getLKeyBoardHeight()

        initRecycle()
        mViewModel.getHistoryMsgList(fromUserId, toUserId)
        mViewModel.getMqttInfo()
        binding.mEdit.addTextChangedListener {
            val trim = it.toString().trim()
            var isSendStr = trim.isNotEmpty()
            binding.mSend.visibility = if (isSendStr) View.VISIBLE else View.GONE
            binding.mImageMore.visibility = if (isSendStr) View.GONE else View.VISIBLE
        }
        binding.mEdit.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                binding.mLinMore.visibility = View.GONE
            }
        }
        binding.mImageMore.setOnClickListener(onClickListener)
        binding.mSend.setOnClickListener(onClickListener)
        binding.mPhoto.setOnClickListener(onClickListener)
        binding.mVideo.setOnClickListener(onClickListener)
        binding.mAudio.setOnClickListener(onClickListener)
        binding.mPressTalk.setAudioFinishRecorderListener(object :
            AudioRecorderButton.AudioFinishRecorderListener {
            override fun onFinish(seconds: Float, filePath: String?) {//录音完成
                if (filePath!!.isNullOrEmpty()) {
                    return
                }
                audioTime = Math.ceil(seconds.toDouble()).toInt()
                fileType = 2
                fileUrl = filePath
                mViewModel.saveChatMedia(
                    fileUrl,
                    Const.MESSAGE_PREFIX + fromUserId,
                    fileType,
                    toUserId,
                    fromUserId,
                    audioTime
                )
            }
        })
    }

    private var onClickListener: View.OnClickListener = View.OnClickListener {

        when (it.id) {
            R.id.mImageMore -> {//点击显示更多操作
                RxKeyboardTool.hideSoftInput(this)
                binding.mLinMore.visibility = View.VISIBLE
                binding.mBottom.clearFocus()
            }
            R.id.mSend -> {//点击消息发送
                val trim = binding.mEdit.text.toString().trim()
                fileType = 0
                mViewModel.saveChat(fromUserId, toUserId, trim)
            }
            R.id.mPhoto -> {//点击选择图片
                fileType = 1
                PictureUtils.openCamera(this)
            }
            R.id.mVideo -> {//点击拍摄视频
                fileType = 3
                PictureUtils.openCamera(this, PictureMimeType.ofVideo())
            }
            R.id.mAudio -> {//点击切换语音
                if (isAudio) {
                    isAudio = false
                    binding.mPressTalk.visibility = View.GONE //隐藏按住说话
                    binding.mEdit.visibility = View.VISIBLE//显示文字输入框
                    binding.mAudio.setImageResource(R.mipmap.ic_audio)//设置语音图标
                } else {
                    isAudio = true
                    RxKeyboardTool.hideSoftInput(this)//隐藏软键盘
                    binding.mPressTalk.visibility = View.VISIBLE //显示按住说话
                    binding.mEdit.visibility = View.GONE//隐藏文字输入框
                    binding.mAudio.setImageResource(R.mipmap.ic_keyboard)//设置键盘图标
                }
            }
        }

    }

    private fun initRecycle() {
        binding.mRecycle.addItemDecoration(RecycleItem(this, 20))
        var layoutManager = LinearLayoutManager(this)
        //软键盘弹出RecyclerView会随之上移
        layoutManager.stackFromEnd = true
        binding.mRecycle.setHasFixedSize(true)
        binding.mRecycle.layoutManager = layoutManager
        binding.mRecycle.adapter = madapter

        madapter.addChildClickViewIds(
            R.id.mVideoRightBg,
            R.id.mVideoLeftBg,
            R.id.mAudioLeftBg,
            R.id.mAudioRightBg
        )
        madapter.setOnItemChildClickListener { adapter, view, position ->
            var bean = adapter.getItem(position) as ChatBean
            when (bean.process_type) {
                1 -> {
                    if (bean.isLocalFIle) {
                        PictureUtils.previewImage(this, 0, mutableListOf(LocalMedia().apply {
                            this.compressPath = bean.file_path
                            this.isCompressed = true
                        }))
                    } else {
                        PictureUtils.httpPreviewImage(
                            this,
                            0,
                            mutableListOf(bean.file_path),
                            BuildConfig.image_prefix
                        )
                    }
                }
                2 -> {
                    var isMine = bean.itemType == 1
                    val audioPath =
                        if (bean.file_path.contains(packageName))
                            bean.file_path
                        else {
                            getImageUrl(bean.file_path)
                        }
                    LogUtils.d("音频地址:$audioPath")
                    audioUtils.audioPlay(audioPath,
                        object : RecordAudio.AudioPlayStateListener {
                            override fun onStart() {
                                //如果第一个动画正在运行， 停止第一个播放其他的，根据tag来设置初始状态
                                if (mAnimView != null) {
                                    val playerFlag = mAnimView!!.tag as Boolean
                                    mAnimView!!.setBackgroundResource(
                                        if (playerFlag) R.drawable.play_sound_right_default else R.drawable.play_sound_left_default
                                    )
                                    mAnimView = null
                                }
                                //播放动画
                                mAnimView = view.findViewById(R.id.id_recorder_anim)
                                mAnimView!!.tag = isMine //设置tag
                                mAnimView!!.setBackgroundResource(if (isMine) R.drawable.play_right_anim else R.drawable.play_left_anim)
                                val animation = mAnimView!!.background as AnimationDrawable
                                animation.start()
                            }

                            override fun onComplet() {
                                //播放音频  完成后改回原来的background
                                mAnimView!!.setBackgroundResource(
                                    if (isMine) R.drawable.play_sound_right_default else R.drawable.play_sound_left_default
                                )
                            }

                            override fun onError() {
                                //播放音频  加载出错改回原来的background
                                mAnimView!!.setBackgroundResource(
                                    if (isMine) R.drawable.play_sound_right_default else R.drawable.play_sound_left_default
                                )
                            }

                        })
                }
                3 -> {
                    bundle.clear()
                    when (bean.isLocalFIle) {
                        true -> bundle.putString("video", bean.file_path)
                        false -> bundle.putString(
                            "video",
                            getImageUrl(  bean.file_path)
                        )
                    }
                    bundle.putBoolean("local", bean.isLocalFIle)
                    RouteManager.goAct(ARouterUrl.VIDEO_PLAY, bundle)
                }
            }

        }

        binding.mRecycle.setOnTouchListener { v, event ->
            binding.mBottom.clearFocus()
            binding.mLinMore.visibility = View.GONE
            RxKeyboardTool.hideSoftInput(this)
            false
        }

    }

    override fun setLayout() = binding.root


    override fun liveObserver() {
        mViewModel.chatList.observe(this) {
            it.data.map { it.itemType = it.is_me }
            madapter.setNewInstance(it.data)
            binding.mRecycle.post {
                binding.mRecycle.scrollToPosition(madapter.itemCount - 1)
            }
        }
        mViewModel.mqttChat.observe(this) {
            var service = RouteManager.getAny(ARouterUrl.MQTT_SERVICE) as Service
            var intent = Intent(this, service::class.java)
            it.data.appUserId = fromUserId
            intent.putExtra("bean", it.data)
            startService(intent)
            userId = it.data.appUserId
        }

        mViewModel.sendLive.observe(this) {
            it.data.itemType = it.data.is_me
            addList(it.data)
        }
        mViewModel.sendMedic.observe(this) {
            var bean = ChatBean(1).apply {
                this.fileLength = "$audioTime"
                this.file_path = fileUrl
                this.isLocalFIle = true
            }
            when (fileType) {
                1 -> bean.process_type = 1
                2 -> bean.process_type = 2
                3 -> bean.process_type = 3
            }
            addList(bean)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun reveiveMsg(event: MqttReceive) {
        var json = Gson().fromJson(event.msg, ChatBean::class.java)
        json.itemType = json.is_me
        json.isLocalFIle = false
        json.fileLength = "$audioTime"
        addList(json)
    }

    private fun addList(bean: ChatBean) {
        binding.mEdit.setText("")
        madapter.data.add(bean)
        madapter.notifyItemChanged(madapter.itemCount - 1)
        binding.mRecycle.post {
            binding.mRecycle.scrollToPosition(madapter.itemCount - 1)
        }
    }

    /**
     * 监听屏幕的可用高度
     */
    private fun getLKeyBoardHeight() {

        binding.mRecycle.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            if (madapter.itemCount > 0) {
                binding.mRecycle.scrollToPosition(madapter.itemCount - 1)
            }

        }
        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
            var rect = Rect()
            binding.root.getWindowVisibleDisplayFrame(rect)
            var nowHeight = rect.bottom - rect.top
            var param = binding.root.layoutParams as ViewGroup.LayoutParams
            param.height = nowHeight + getStatusBarHeight()
            if (binding.root.height > 0) {
                if (oldHeight == 0) {
                    oldHeight = nowHeight + getStatusBarHeight()
                    binding.root.layoutParams = param
                } else if (oldHeight != nowHeight + getStatusBarHeight()) {
                    oldHeight = nowHeight + getStatusBarHeight()
                    binding.root.layoutParams = param
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode === RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    var result = PictureSelector.obtainMultipleResult(data)
                    if (result.size > 0) {
                        if (result.isNotEmpty()) {
                            if (fileType == 1) {
                                fileUrl = result[0].compressPath
                                mViewModel.saveChatMedia(
                                    result[0].compressPath,
                                    Const.MESSAGE_PREFIX + fromUserId,
                                    fileType,
                                    toUserId,
                                    fromUserId
                                )
                            } else if (fileType == 3) {
                                compressLoad.show()
                                var destPath =
                                    externalCacheDir!!.absolutePath + File.separator + "${System.currentTimeMillis()}.mp4"
                                fileUrl = destPath
                                compressUtils.compress(result[0].realPath, destPath)
                            }
                        }
                    }
                }

            }
        }
    }

    /**
     * 根据生命周期 管理播放录音
     */
    override fun onPause() {
        super.onPause()
        audioUtils.pause()
    }

    override fun onResume() {
        super.onResume()
        audioUtils.resume()
    }

    override fun onDestroy() {
        audioUtils.release()
        FileUtils.deleteAllFile(audioFile)
        super.onDestroy()
    }
}