package com.yidianling.course.courseSearch

import android.annotation.SuppressLint
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.config.SimpleImageOpConfiger
import com.ydl.ydl_image.listener.YDLImageRecyclerOnScrollListener
import com.ydl.ydl_image.manager.YDLImageCacheManager
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.ShareData
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.CourseConstants
import com.yidianling.course.R
import com.yidianling.course.bean.Course
import com.yidianling.course.courseSearch.http.CourseSearchApiUtils
import com.yidianling.course.courseSearch.view.ICourseSearchView
import com.yidianling.course.widget.SearchBarView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_course_search.*
import org.json.JSONException
import org.json.JSONObject

/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 课程搜索页面
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/01/07
 */
@Route(path = "/course/search")
class CourseSearchActivity : BaseActivity(), CourseSearchAdapter.OnItemClick, ICourseSearchView {

    private var inputString: String = ""
    private var nowPage = 1
    private var courseList: ArrayList<Course> = ArrayList()
    private val ROUTER_PARAMS = "routerParam"

    private var courseSearchAdapter: CourseSearchAdapter? = null
    private var courseSearchAdapterWrapper: CourseSearchAdapterWrapper? = null


    override fun layoutResId(): Int {
        return R.layout.activity_course_search
    }

    override fun initDataAndEvent() {

//        showUnusualView("请输入要搜索的内容")
        getParam()
        initBackBtn()
        initSearchBar()
        initSwipeRefreshLayout()
        initRecyclerView()
    }

    /**
     * 获取路由传递的参数
     */
    private fun getParam() {
        if (null == intent || !intent.hasExtra(ROUTER_PARAMS)) {
            return
        }
        //路由传递的入参
        val json = intent.getStringExtra(ROUTER_PARAMS)
        try {
            val jsonObject = JSONObject(json)
            //搜索关键字
            inputString = jsonObject.getString(IYDLRouterConstant.EXTRA_KEYWORD)
            activity_course_search_search_bar_view.setText(inputString)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    /**
     * 初始化返回按钮
     */
    private fun initBackBtn() {
        activity_course_back_btn.setOnClickListener { finish() }
    }

    /**
     * 初始化顶部搜索框并监听键盘搜索按钮
     */
    private fun initSearchBar() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

        activity_course_search_search_bar_view.initBarType(
            SearchBarView.ENABLE_INPUT,
            object : SearchBarView.SearchCallBack {
                override fun cloase() {
                    finish()
                }

                override fun clickSearchBtn(str: String) {
                    inputString = str
                    if (TextUtils.isEmpty(str)) {
//                    showUnusualView("请输入要搜索的内容")
                        ToastUtil.toastShort("请输入要搜索的内容")
                        return
                    }
                    loadCourseList(true)
                }

            })
        activity_course_search_search_bar_view.postDelayed({
            RxKeyboardTool.showSoftInput(this, activity_course_search_search_bar_view.getEditText())
        },500)
    }

    /**
     * 设置下拉刷新
     */
    private fun initSwipeRefreshLayout() {
        activity_course_search_swipe_refresh_layout.setOnRefreshListener {
            loadCourseList(true)
        }
    }

    /**
     * 初始化列表并监听滑动到底部 footer Item加载更多
     */
    private fun initRecyclerView() {
        if (null == courseSearchAdapterWrapper) {
            courseSearchAdapter =
                CourseSearchAdapter(this, CourseSearchActicity@ this, courseList!!)
            courseSearchAdapter!!.setOnItemClickListener(this)

            activity_course_search_recycler.layoutManager = LinearLayoutManager(this)
            courseSearchAdapterWrapper = CourseSearchAdapterWrapper(
                this,
                courseSearchAdapter!!,
                20,
                activity_course_search_recycler
            )
                .setOnLoadMoreListener(object : CourseSearchAdapterWrapper.OnLoadMoreListener {
                    override fun onLoadMore() {
                        loadCourseList(false)
                    }
                })
            activity_course_search_recycler.adapter = courseSearchAdapterWrapper
            //滑动监听 图片是否加载
            activity_course_search_recycler.addOnScrollListener(
                YDLImageRecyclerOnScrollListener(
                    CourseSearchActicity@ this
                )
            )
            loadCourseList(true)
        }
    }

    /**
     * item点击事件
     */
    override fun onItemClickEvent(position: Int) {
        var courseItem = courseList[position]
        if (null != courseItem) {
            val h5Params = H5Params(CourseConstants.COURSE_DETAIL_H5 + courseItem.id, "课程详情")
            if (null != courseItem.share && !TextUtils.isEmpty(courseItem.share.share_url)) {
                val shareData = ShareData(
                    courseItem.share.share_url,
                    courseItem.share.title,
                    courseItem.share.cover,
                    courseItem.share.desc
                )
                h5Params.shareData = shareData
            }

            NewH5Activity.start(this, h5Params)
        }
    }

    /**
     * 加载图片
     */
    override fun showImage(url: String?, imageView: ImageView, width: Int, height: Int) {
        val sp = SimpleImageOpConfiger()
        sp.heigt = height
        sp.width = width
        sp.errorPic = R.drawable.course_default_img
        sp.loadingPic = R.drawable.course_default_img
        YDLImageCacheManager.showImage(CourseSearchActicity@ this, url, imageView, sp)
    }

    /**
     * 根据输入搜索专家课程
     * type true代表首次加载，false代表加载下一页
     */
    @SuppressLint("CheckResult")
    fun loadCourseList(type: Boolean) {
        if (TextUtils.isEmpty(inputString)) {
            activity_course_search_swipe_refresh_layout.isRefreshing = false
            return
        }

        when (type) {
            //如果是首次加载，则当前页面重置为1，数据清空
            true -> {
                nowPage = 1
                activity_course_search_swipe_refresh_layout.isRefreshing = true
            }
            //如果不是首次加载，则页面+1
            false -> {
                nowPage++
            }
        }

        CourseSearchApiUtils.courseSearchList(nowPage, inputString)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {

                if (it.data.list.isNotEmpty()) {
                    hideUnusualPage()
                    if (type) {
                        courseList.clear()
                        courseList.addAll(it.data.list)
                        courseSearchAdapterWrapper!!.notifyDataSetChanged()
                    } else {
                        courseList.addAll(it.data.list)
                        courseSearchAdapterWrapper!!.insertData()
                    }
                } else {
                    if (!type) {
                        courseSearchAdapterWrapper!!.noMoreData()
                    } else {
                        showUnusualView("没有搜到相关信息，换个关键词看看吧", true)
                    }
                }

                activity_course_search_swipe_refresh_layout.isRefreshing = false
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    Log.i("testtest", msg)
                    activity_course_search_swipe_refresh_layout.isRefreshing = false
                    showUnusualView("请检查你的网络设置", false)
                }
            })
    }

    /**
     * 显示异常页面
     */
    private fun showUnusualView(desc: String, isEmpty: Boolean) {
        if (!TextUtils.isEmpty(desc)) activity_course_search_unusual_layout_desc.text = desc
        activity_course_search_unusual_layout.visibility = View.VISIBLE
        activity_course_search_recycler.visibility = View.GONE
        iv_empty.setImageResource(if (isEmpty) R.drawable.course_ico_img_zixun_empty else R.drawable.course_blank)
    }

    /**
     * 隐藏异常页面
     */
    fun hideUnusualPage() {
        activity_course_search_unusual_layout.visibility = View.GONE
        activity_course_search_recycler.visibility = View.VISIBLE
    }


}