package com.ydl.confide.intro

import android.app.Activity
import android.util.Log
import android.view.View
import android.widget.SeekBar
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.dou361.ijkplayer.widget.IjkVideoView
import com.ydl.confide.api.ConfideRoute
import com.ydl.confide.databinding.ItemExpertIntroBinding
import com.ydl.confide.home.ConfideBottomSheetDialogFragment
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.LogUtil
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.net.URLEncoder
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
    private var vm: VideoViewModel? = null

    @Volatile
    private var isTouch = false

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

    fun onBind(item: VideoViewModel) {
        vm = item
        binding.layoutCall.setOnClickListener {
            showDoctorDetail(item)
        }
        binding.btnChat.setOnClickListener {
            val aty = it.context as? Activity
            if (aty != null && !item.uid.isNullOrEmpty()) {
                findRouteService(IImService::class.java)?.startChat(aty, item.uid!!, 0, 0)
            }
        }
        binding.btnEvaluate.setOnClickListener {
            item.doctorId?.let {
                ConfideBottomSheetDialogFragment()
                    .showBottomSheetDialog(
                        itemView.context as FragmentActivity,
                        HttpConfig.MH5_URL + ConfideRoute.h5ExpertEval(it),
                        it
                    )
            }
        }
        binding.tvName.setOnClickListener {
            showDoctorDetail(item)
        }
        binding.ivAvatar.setOnClickListener {
            showDoctorDetail(item)
        }
        binding.vDisableClick.setOnClickListener { }
        binding.btnShare.setOnClickListener {
            val aty = it.context as? Activity
            if (aty != null) {
                var shareUrl = "${HttpConfig.MH5_URL}experts/${item.doctorId}"
                if (!item.confideId.isNullOrBlank()) {
                    shareUrl += "?id=${item.confideId}"
                }
                val dialog = YDLShareDialog.style8(
                    aty, "${item.name.get()}_${item.title.get()}", shareUrl, "壹点灵心理服务平台让天下人更快乐", item.avatar.get(),
                    genMinProgramPath(shareUrl), "gh_25b90294ddcc"
                )
                dialog.show(aty.fragmentManager, "share")
            }
        }
        binding.videoView.setOnClickListener {
            if (video?.canPause() == true) {
                video?.pause()
                if (item.isVideo) {
                    binding.ivPlay.visibility = View.VISIBLE
                } else {
                    binding.voicePlay.stop()
                }
            }
        }
        binding.ivPlay.setOnClickListener {
            video?.start()
            if (item.isVideo) {
                binding.ivPlay.visibility = View.GONE
            } else {
                binding.voicePlay.start()
            }
        }
        binding.voicePlay.setOnClickListener {
            if (video?.isPlaying == true) {
                video?.pause()
                binding.voicePlay.stop()
            } else if (video?.isPlaying == false) {
                video?.start()
                binding.voicePlay.start()
            }
        }
        binding.seekbar.progress = 0
        binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isTouch = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isTouch = false
                if (seekBar != null) {
                    video?.seekTo(seekBar.progress)
                    video?.start()
                    binding.ivPlay.visibility = View.GONE
                }
            }
        })
        binding.voicePlay.visibility =
            if (item.isVideo) View.GONE else if (item.playUrl.isNullOrBlank()) View.GONE else View.VISIBLE
    }

    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, "OnInfo:${what},${extra}")
            return@setOnInfoListener true
        }
        video?.setOnCompletionListener {
            video?.seekTo(0)
            video?.start()
        }
        video?.setOnErrorListener { player, what, extra ->
            LogUtil.e(TAG, "onError:$what,$extra")
            return@setOnErrorListener true
        }
        startTiming()
        if (vm?.isVideo == false && !vm?.playUrl.isNullOrBlank()) {
            binding.voicePlay.start()
        }
    }

    private fun startTiming() {
        disposable = Observable.interval(3, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.computation())
            .subscribe {
                val pos = (video?.mMediaPlayer as IjkMediaPlayer?)?.currentPosition ?: 0
                if (pos > 0) {
                    if (vm?.isVideo == true) {
                        binding.ivCover.visibility = View.GONE
                    }
                    if (!isTouch) {
                        binding.seekbar.progress = pos.toInt()// video.bufferPercentage
                    }
                    if (video?.isPlaying == true) {
                        when (vm?.isVideo) {
                            true -> {
                                binding.ivPlay.visibility = View.GONE
                            }
                            false -> {
                                binding.voicePlay.start()
                            }
                        }
                    }
                }
            }
    }

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

    private fun showDoctorDetail(item: VideoViewModel) {
        if (!item.linkUrl.isNullOrBlank()) {
            ConfideBottomSheetDialogFragment()
                .showBottomSheetDialog(itemView.context as FragmentActivity, item.linkUrl!!, item.doctorId!!)
        }
    }
}

class VideoViewModel {
    val name = ObservableField<String>("")
    val title = ObservableField<String>("")
    val avatar = ObservableField<String>("")
    val count = ObservableField<String>("")
    val lineStatus = ObservableInt()
    var remainingTime = ObservableField<String>("")
    val intro = ObservableField<String>("")
    val tag = ObservableField<String>("")
    var playUrl: String? = null
    val coverUrl = ObservableField<String>("")
    val showFreeTag = ObservableBoolean(false)
    var isVideo = false
    var uid: String? = null
    var doctorId: String? = null
    var confideId: String? = null
    var linkUrl: String? = null
}

private fun genMinProgramPath(url: String): String {
    val pathPrefix = "/pages/web/web?load_url="
    val encode = URLEncoder.encode(url, "UTF-8")
    return pathPrefix + encode
}

internal fun VideoViewModel.mapOf(bean: ConfideHomeBodyBean): VideoViewModel {
    name.set(bean.confidedName)
    avatar.set(bean.confidedIcon)
    count.set("倾听人次 " + bean.confideNum)
    intro.set(bean.confideContent)
    title.set(bean.title)
    val sb = StringBuilder()
    bean.confidedTag?.forEach { sb.append(it).append(" | ") }
    if (sb.isNotEmpty()) {
        sb.setLength(sb.length - 3)
    }
    tag.set(sb.toString())
    if (!bean.videoUrl.isNullOrEmpty()) {
        playUrl = bean.videoUrl
        isVideo = true
        coverUrl.set(bean.coverVideoPicture)
    } else {
        playUrl = bean.confideVoice
        isVideo = false
        coverUrl.set(bean.coverPicture)
    }
    uid = bean.uid?.toString()
    doctorId = bean.doctorId
    confideId = bean.confidedId
    doctorId?.let {
        linkUrl = HttpConfig.MH5_URL + ConfideRoute.h5ExpertEval(it)
    }
    return this
}

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