package com.ydl.confide.intro

import android.app.Activity
import android.util.Log
import android.view.View
import android.widget.SeekBar
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.dou361.ijkplayer.widget.IjkVideoView
import com.ydl.confide.databinding.ItemExpertIntroBinding
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.ydlcommon.view.dialog.YDLShareDialog
import com.yidianling.im.api.service.IImService
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.util.concurrent.TimeUnit

internal class ItemIntroHolder(binding: ItemExpertIntroBinding) :
    BindingViewHolder<ItemExpertIntroBinding>(binding) {
    companion object {
        private const val TAG = "ItemIntroHolder"
    }

    private var disposable: Disposable? = null
    private var video: IjkVideoView? = null

    fun onDetach() {
        stopTiming()
        video?.release(true)
    }

    fun onBind(item: VideoViewModel) {
        binding.layoutCall.setOnClickListener { }
        binding.btnChat.setOnClickListener {
            val aty = it.context as? Activity
            if (aty != null && !item.uid.isNullOrEmpty()) {
                ARouter.getInstance().navigation(IImService::class.java)?.startChat(aty, item.uid!!, 0, 0)
            }
        }
        binding.btnEvaluate.setOnClickListener { }
        binding.vDisableClick.setOnClickListener { }
        binding.btnShare.setOnClickListener {
            val aty = it.context as? Activity
            if (aty != null) {
                val dialog = YDLShareDialog.style8(aty, "title", "url", ";sss", "head")
                dialog.show(aty.fragmentManager, "share")
            }
        }
        binding.videoView.setOnClickListener {
            video?.pause()
            binding.ivPlay.visibility = View.VISIBLE
        }
        binding.ivPlay.setOnClickListener {
            video?.start()
            binding.ivPlay.visibility = View.GONE
        }
        binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                if (seekBar != null) {
                    video?.seekTo(seekBar.progress)
                    video?.start()
                    binding.ivPlay.visibility = View.GONE
                }
            }
        })
    }

    fun onAttach(videoView: IjkVideoView) {
        this.video = videoView
        binding.videoView.addView(videoView)
        video?.setOnPreparedListener { player ->
            Log.d(TAG, "${player.videoHeight},${player.videoWidth},${player.duration}")
            val duration = player.duration.toInt()
            if (duration > 0) {
                binding.seekbar.max = duration
            } else {
                binding.seekbar.visibility = View.GONE
            }
        }
        video?.setOnInfoListener { mp, what, extra ->
            Log.d(TAG, "${what},${extra}")
            return@setOnInfoListener false
        }
        video?.setOnCompletionListener { stopTiming() }
        startTiming()
    }

    private fun startTiming() {
        disposable = Observable.interval(300, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.computation())
            .subscribe {
                val pos = (video?.mMediaPlayer as IjkMediaPlayer?)?.currentPosition ?: 0
                if (pos > 0) {
                    binding.seekbar.progress = pos.toInt()// video.bufferPercentage
                }
            }
    }

    private fun stopTiming() {
        disposable?.dispose()
    }
}

class VideoViewModel {
    val name = ObservableField<String>("")
    val avatar = ObservableField<String>("")
    val count = ObservableInt()
    val lineStatus = ObservableInt()
    val intro = ObservableField<String>("")
    val tag = ObservableField<String>("")
    var playUrl: String? = null//"https://video.ydlcdn.com/2020/04/01/ac2e4bb4e3ac8e2f0eca41e2d49c8484.mp4"
    var coverUrl = ObservableField<String>("")
    var isVideo = true
    var uid: String? = null
    var linkUrl: String? = null
}

internal fun VideoViewModel.mapOf(bean: ConfideHomeBodyBean): VideoViewModel {
    name.set(bean.confidedName)
    avatar.set(bean.confidedIcon)
//    count.set(bean.confideHearNum)
    intro.set(bean.categoryContent)
    val sb = StringBuilder()
    bean.confidedTag?.forEach { sb.append(it).append("|") }
    sb.setLength(sb.length - 1)
    tag.set(sb.toString())
    if (bean.videoUrl != null) {
        playUrl = bean.videoUrl
        isVideo = true
        coverUrl.set(bean.coverVideoPicture)
    } else {
        playUrl = bean.confideVoice
        isVideo = false
        coverUrl.set(bean.coverPicture)
    }
    uid = bean.uid?.toString()
    linkUrl = bean.linkUrl
    return this
}

open class BindingViewHolder<T : ViewDataBinding>(val binding: T) :
    RecyclerView.ViewHolder(binding.root)