package com.jld.vod.view.fragment

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jld.kotilntest.room.adapter.CategoryFatherAllAdapter
import com.jld.kotilntest.room.adapter.CategorySonAllAdapter
import com.jld.kotilntest.room.adapter.MovieListAdapter
import com.jld.vod.R
import com.jld.vod.base.BaseFragment
import com.jld.vod.model.bean.*
import com.jld.vod.utils.ClickDelayTime
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.viewmodel.MainViewModel
import com.jld.vod.viewmodel.MovieFragmentViewModel
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.enums.CoreAnim
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xui.widget.statelayout.StatefulLayout
import kotlinx.coroutines.flow.collectLatest
import java.util.*


@Page(anim = CoreAnim.none)
class MovieFragment : BaseFragment() {
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mRecyclerView1: RecyclerView

    private lateinit var moviet1ViewModel: MovieFragmentViewModel
    private lateinit var sfl_device_loading: StatefulLayout
    private lateinit var mBackPage: ImageView
    private var flag:Boolean = true

    override fun getLayoutId(): Int {
        return R.layout.fragment_movie
    }

    override fun initViews() {
        mRecyclerView = findViewById(R.id.rv_moviet1)
        mRecyclerView1 = findViewById(R.id.rv1_movie_list)

        sfl_device_loading = findViewById(R.id.sfl_device_loading)
        //初始化viewmodel
        moviet1ViewModel = ViewModelProviders.of(this)
            .get(MovieFragmentViewModel::class.java)

        //电影分类一级列表
        val adapterFather = CategoryFatherAllAdapter()
        //初始化一级分类列表recyclerview
        val LinearlayoutManager = LinearLayoutManager(activity)
        mRecyclerView1!!.layoutManager = LinearlayoutManager
        //添加一级Android自带的分割线
        //  mRecyclerView1.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
        mRecyclerView1!!.adapter = adapterFather

        //二级分类列表
        val adapterSon = CategorySonAllAdapter()

        //电影列表初始化recyclerview
        val gridlayoutManager = GridLayoutManager(activity, 3)
        mRecyclerView!!.layoutManager = gridlayoutManager
        val adapter = MovieListAdapter()
        mRecyclerView!!.adapter = adapter

      //  moviet1ViewModel.moviebymidList.observe(this, Observer(adapter::submitList))


        val lid = SharedPrefUtils.getString(activity,"language_lid")
        val mid = SharedPrefUtils.getString(activity,"RES_MOVIE")

        //点击返回上一级分类列表
        val activity = activity as AppCompatActivity?
        mBackPage = activity!!.findViewById<ImageView>(R.id.iv_back_page)
        mBackPage.setOnClickListener {
            if (ClickDelayTime.isFastClick())
            {

                if (flag)
                {
                    activity.onBackPressed()
                }else{
                    flag = true
                    //获取第一级分类列表请求
                    if (lid != "" && mid !="") {
                        mRecyclerView1!!.adapter = adapterFather
                        //电影分类一级列表
                        lifecycleScope.launchWhenCreated {
                            moviet1ViewModel.getCategoryFatherAllByMid(mid.toLong(), lid.toLong())
                                .collectLatest { pagingData ->
                                    adapterFather.submitData(pagingData)
                                }
                        }
                        //获取全部电影列表
                        lifecycleScope.launchWhenCreated {
                            moviet1ViewModel.getMovieAllList(mid.toLong(), lid.toLong())
                                .collectLatest { pagingData ->
                                    adapter.submitData(pagingData)
                                }
                        }
                    }
                }
            }
        }

        //获取第一级分类列表请求
        if (lid != "" && mid !="") {
            //获取一级列表
            lifecycleScope.launchWhenCreated {
                moviet1ViewModel.getCategoryFatherAllByMid(mid.toLong(), lid.toLong())
                    .collectLatest { pagingData ->
                        adapterFather.submitData(pagingData)
                    }
            }
            //获取全部电影列表
            lifecycleScope.launchWhenCreated {
                moviet1ViewModel.getMovieAllList(mid.toLong(), lid.toLong())
                    .collectLatest { pagingData ->
                        adapter.submitData(pagingData)
                    }
            }
        }
        adapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.Error -> {
                    finishLoading()
                }
                is LoadState.Loading -> {
                    showLoading()
                }
                is LoadState.NotLoading -> {
                    finishLoading()
                }
            }
        }
        //列表一级监听
        adapterFather.setOnCategorySonClickListener(object : CategoryFatherAllAdapter.ICategorySonItemClickListener{
            override fun onItemClickListener(cid: Long,mid: Long) {

                flag = false
                adapterFather.setSelectItem()//清除一级选中状态

                //电影分类二级列表
                mRecyclerView1.adapter = adapterSon
                //获取一级列表
                lifecycleScope.launchWhenCreated {
                    moviet1ViewModel.getategorySonAllByMid(cid,lid.toLong()).collectLatest { pagingData ->
                        adapterSon.submitData(pagingData)
                    }
                }

                //获取分类电影列表
                lifecycleScope.launchWhenCreated {
                    moviet1ViewModel.getMovieCidList(cid,mid,lid.toLong()).collectLatest { pagingData ->
                        adapter.submitData(pagingData)
                    }
                }
            }
        })
        //二级分类列表
        adapterSon.setOnCategorySonClickListener(object : CategorySonAllAdapter.ICategorySonItemClickListener{
            override fun onItemClickListener(cid: Long , mid: Long) {
                //获取分类电影列表
                lifecycleScope.launchWhenCreated {
                    moviet1ViewModel.getMovieCidList(cid,mid,lid.toLong()).collectLatest { pagingData ->
                        adapter.submitData(pagingData)
                    }
                }
            }
        })




        adapter.setOnMovieClickListener(object : MovieListAdapter.IMovieItemClickListener{
            override fun onItemClickListener(movie: MovieByMidBean) {
                var args = Bundle()
                args.putSerializable("movie",movie)
                openPage("MovieDetailsFragment",args,CoreAnim.none)
            }
        })
    }

    /**
     * 空数据
     *
     */
    private fun showNullMovieList() {
        sfl_device_loading!!.showEmpty()
    }

    override fun initTitle(): TitleBar? {
        return null
    }
}