package com.ydl.confide.intro

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.ydl.confide.R
import com.ydl.confide.api.ConfideRoute
import com.ydl.confide.databinding.ActivityExpertIntroBinding
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.confide.home.http.ConfideHomeApi
import com.ydl.confide.router.PhoneCallIn
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.base.config.HttpConfig.Companion.YDL_H5
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlnet.YDLHttpUtils
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.api.service.IUserService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


@Route(path = ConfideRoute.R_VIDEO_SHOW)
class ExpertIntroActivity : AppCompatActivity() {
    companion object {
        private const val SOURCE_VIDEO = 10
    }

    private val tag = javaClass.simpleName

    @Autowired
    @JvmField
    var initPos: Int = 0

    @Autowired
    @JvmField
    var initData: String? = null
    private var lastSelectPos = 0
    private lateinit var binding: ActivityExpertIntroBinding
    private lateinit var adapter: IntroAdapter
    private var page = 1

    private var disposable: Disposable? = null

    private val confideApi = YDLHttpUtils.obtainApi(ConfideHomeApi::class.java)

    private val data = mutableListOf<VideoViewModel>()

    private var noMoreData = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_expert_intro)
        if (Build.VERSION.SDK_INT >= 21) {
            val decorView = window.decorView
            val option = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
            decorView.systemUiVisibility = option
            window.statusBarColor = Color.TRANSPARENT
        }
        if (initData != null) {
            val beans = JSON.parseArray(initData, ConfideHomeBodyBean::class.java)
                val isLogin = findRouteService(IUserService::class.java)?.isLogin() ?: false
            val vms = beans.map {
                VideoViewModel().mapOf(it).apply { showFreeTag.set(!isLogin) }
            }
            data.addAll(vms)
        }
        binding.ivBack.setOnClickListener { onBackPressed() }
        binding.tvConfideRecord.setOnClickListener {
            if (!PhoneCallIn.loginByOneKeyLogin(this, true)) {
                return@setOnClickListener
            }
            BuryPointUtils.getInstance().createMap()
                .put("mine_name", "倾诉记录")
                .burryPoint("mine")
            val h5Paramsqing = H5Params(YDL_H5 + "confideOrderList", null)
            NewH5Activity.start(this, h5Paramsqing)
        }
        binding.viewPager.orientation = ViewPager2.ORIENTATION_VERTICAL
        binding.viewPager.offscreenPageLimit = 1
        adapter = IntroAdapter(this, data, this)
        binding.viewPager.adapter = adapter
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                adapter.onSelect(position)
                if (position == data.size - 1 && lastSelectPos < position) {
                    loadMore()
                }
                lastSelectPos = position
            }
        })
        adapter.checkNetwork()
        binding.viewPager.currentItem = initPos
    }

    private fun loadMore() {
        if (disposable != null && !disposable!!.isDisposed) {
            return
        }
        if (noMoreData) return
        disposable = confideApi.recommendDoctor(HttpConfig.JAVA_BASE_URL + "auth/listen/nsearch?", page, SOURCE_VIDEO)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.code == "200") {
                    page++
                    val body = resp.data.body
                    val isLogin = findRouteService(IUserService::class.java)?.isLogin() ?: false
                    val map = body?.map { VideoViewModel().mapOf(it).apply { showFreeTag.set(!isLogin) } }
                    map?.let {
                        data.addAll(it)
                        adapter.notifyItemRangeInserted(data.size - it.size, it.size)
                    }
                    if (body == null || body.size == 0) {
                        noMoreData = true
                    }
                } else {
                    ToastUtil.toastShort(resp.msg)
                }
            }, { throwable ->
                LogUtil.e(tag, throwable.message)
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
    }
}