package com.ydl.confide.intro

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.RecyclerView
import com.dou361.ijkplayer.widget.IjkVideoView
import com.ydl.confide.R
import com.ydl.confide.databinding.ItemExpertIntroBinding
import com.ydl.confide.home.http.ConfideHomeApi
import com.ydl.confide.home.util.ConfideNetworkUtil
import com.ydl.ydlcommon.ui.Loading
import com.ydl.ydlcommon.utils.TimeUtil
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.ydl.ydlnet.YDLHttpUtils
import com.yidianling.common.tools.ToastUtil
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import tv.danmaku.ijk.media.player.IMediaPlayer

internal class IntroAdapter(
    private val context: Context,
    private val data: List<VideoViewModel>,
    private val lifecycleOwner: LifecycleOwner
) : RecyclerView.Adapter<ItemIntroHolder>(), LifecycleObserver {

    private val videoViews = hashMapOf<Int, IjkVideoView>()

    private val onInfoListener = OnVideoInfo()

    private var hasAgreePlayWithoutWiFi = false

    private var curPos = 0

    private var dispose: Disposable? = null

    private val keySp = "check_network_continue"

    init {
        lifecycleOwner.lifecycle.addObserver(this)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemIntroHolder {
        val binding = DataBindingUtil.inflate<ItemExpertIntroBinding>(
            LayoutInflater.from(parent.context),
            R.layout.item_expert_intro,
            parent,
            false
        )
        return ItemIntroHolder(binding)
    }

    override fun onBindViewHolder(holder: ItemIntroHolder, position: Int) {
        val item = data[position]
        holder.onBind(item)
        holder.binding.item = item
    }


    override fun onViewAttachedToWindow(holder: ItemIntroHolder) {
        val adapterPosition = holder.adapterPosition
        val videoView = IjkVideoView(context)
        val playUrl = data[adapterPosition].playUrl
        if (!playUrl.isNullOrBlank()) {
            if (hasAgreePlayWithoutWiFi || ConfideNetworkUtil.isWifi(context)) {
                videoView.setVideoURI(Uri.parse(playUrl))
                if (curPos == adapterPosition) {
                    videoView.start()
                }
            } else {
                videoView.tag = playUrl
            }
        }
        videoView.setOnInfoListener(onInfoListener)
        videoViews.put(adapterPosition, videoView)
        holder.onAttach(videoView)
    }

    internal fun checkNetwork() {
        if (!ConfideNetworkUtil.isWifi(context)) {
            val lastCheck = context.getSharedPreferences("temp_test", Context.MODE_PRIVATE).getLong(keySp, 0)
            val duration = System.currentTimeMillis() - lastCheck
            if (duration < 24 * 60 * 60 * 1000) {
                hasAgreePlayWithoutWiFi = true
                return
            }
            val dialog = CommonDialog.create(context)
                .setTitle(context.getString(R.string.confide_tip))
                .setMessage(context.getString(R.string.confide_video_wifi_tip))
                .setLeftOnclick("继续播放") {
                    context.getSharedPreferences("temp_test", Context.MODE_PRIVATE).edit()
                        .putLong(keySp, System.currentTimeMillis()).apply()
                    hasAgreePlayWithoutWiFi = true
                    for (entry in videoViews.entries) {
                        val value = entry.value
                        val playUrl = value.tag as? String
                        if (!playUrl.isNullOrBlank()) {
                            value.setVideoURI(Uri.parse(playUrl))
                            if (curPos == entry.key) {
                                value.start()
                            }
                        }
                    }
                }
                .setLeftButton_color(R.color.platform_but_text_color_selected)
                .setRightButton_color(R.color.platform_text_bright_color)
                .setRightClick("取消") {
                    hasAgreePlayWithoutWiFi = false
                    for (entry in videoViews.entries) {
                        val value = entry.value
                        if (value.canPause()) {
                            value.pause()
                        }
                    }
                }
                .setCancelAble(true)
            dialog.setOnCancelListener {
                if (context is Activity) {
                    context.onBackPressed()
                }
            }
            dialog.show()
        }
    }

    override fun onViewDetachedFromWindow(holder: ItemIntroHolder) {
        super.onViewDetachedFromWindow(holder)
        val adapterPosition = holder.adapterPosition
        val video = videoViews.get(adapterPosition)
        video?.release(true)
        videoViews.remove(adapterPosition)
        holder.onDetach()
    }

    override fun getItemCount(): Int {
        return data.size
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onDestroy() {
        for (entry in videoViews.entries) {
            entry.value.release(true)
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun onResume() {
        val ijkVideoView = videoViews[curPos]
        ijkVideoView?.start()
        onLoadDialStatus(curPos)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private fun onPause() {
        val ijkVideoView = videoViews[curPos]
        ijkVideoView?.pause()
    }

    fun onSelect(position: Int) {
        curPos = position
        onLoadDialStatus(position)
        if (!ConfideNetworkUtil.isWifi(context) && !hasAgreePlayWithoutWiFi) {
            return
        }
        for (entry in videoViews.entries) {
            if (entry.key == position) {
//                entry.value.seekTo(0)
                entry.value.start()
            } else {
                entry.value.seekTo(0)
                entry.value.pause()
            }
        }
    }

    private fun onLoadDialStatus(position: Int) {
        val confideApi = YDLHttpUtils.obtainApi(ConfideHomeApi::class.java)
        val doctorId = data[position].doctorId
        val confideId = data[position].confideId
        val video = data[position].isVideo
        ActionCountUtils.record(
            "listen_counselor_content_play_page",
            "listen_counselor_content_play_visit",
            confideId ?: "",
            if (video) "1" else "2",
            "1"
        )
        if (doctorId != null) {
            dispose?.dispose()
            dispose = confideApi.getDialStatus(doctorId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ resp ->
                    if (resp.code == "200") {
                        val lineStatus = resp.data?.confideLine ?: 2
                        if (lineStatus == 4) {//继续倾诉4,1在线 2离线 3通话中
                            val t = resp?.data?.remainingTime?.remainingTime
                            if (t != null) {
                                val remain = TimeUtil.getElapseTimeForShow(t * 1000)
                                data[position].remainingTime.set(
                                    context.getString(
                                        R.string.confide_tip_remain_time,
                                        remain
                                    )
                                )
                            }
                        } else if (lineStatus == 3) {
                            data[position].remainingTime.set("(点击留言)")
                        } else if (lineStatus == 2) {
                            data[position].remainingTime.set("(点击邀请上线)")
                        }
                        data[position].lineStatus.set(lineStatus)
                    } else {
                        if (!resp.msg.isNullOrEmpty()) {
                            ToastUtil.toastShort(resp.msg)
                        }
                    }
                }, { throwable -> throwable.printStackTrace() })
        }
    }

    private inner class OnVideoInfo : IMediaPlayer.OnInfoListener {
        override fun onInfo(mp: IMediaPlayer?, what: Int, extra: Int): Boolean {
            Log.d("OnVideoInfo", "OnInfo:${what},${extra},${curPos}")
            if (videoViews[curPos]?.mMediaPlayer == mp && data[curPos].isVideo) {
                if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    Loading.show(context)
                } else if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    Loading.close()
                }
            }
            return true
        }
    }
}