package com.yidianling.course.courseNew.courseList

import `in`.srain.cube.views.loadmore.LoadMoreContainer
import `in`.srain.cube.views.loadmore.LoadMoreHandler
import `in`.srain.cube.views.ptr.PtrDefaultHandler
import `in`.srain.cube.views.ptr.PtrFrameLayout
import `in`.srain.cube.views.ptr.PtrHandler
import `in`.srain.cube.views.ptr.header.MaterialHeader
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import androidx.core.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.ShareData
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.ui.LogoLoadingView
import com.ydl.ydlcommon.utils.NetworkParamsUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxImageTool
import com.yidianling.course.CourseConstants
import com.yidianling.course.CourseNewListAdapter
import com.yidianling.course.R
import com.yidianling.course.bean.Course
import com.yidianling.course.constants.CourseBIConstants
import com.yidianling.course.courseNew.LoadMoreView
import com.yidianling.course.courseNew.courseList.widget.CourseFilterPopupWindow
import com.yidianling.course.courseNew.courseList.widget.CourseGoodPopupWindow
import com.yidianling.course.courseNew.courseList.widget.CourseSortPopupWindow
import com.yidianling.course.model.CourseCategoryBean
import com.yidianling.course.net.CourseRetrofitUtils
import com.yidianling.course.widget.SearchBarView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_courses.*
import kotlinx.android.synthetic.main.item_hot_search_view.view.*
import org.json.JSONException
import org.json.JSONObject

/**
 * 课程分类列表
 */
@Route(path = "/course/list")
class CourseListContainerActivity : BaseActivity(), PtrHandler, LoadMoreHandler {

    private var currentType: String = ""
    private var currentValue: String = ""
    private var childType: Int = 0
    private var adapter: CourseNewListAdapter? = null
    private var hasMore = true
    private var page = 0
    private var keyList = ArrayList<String>()
    private var valueList = ArrayList<String>()
    //免费1-是 2-否,其他则全部展示
    private var isFree = 0
    //是否返利 1是 2否,不传则全部
    private var isInvite = 0
    //是否促销 1是 2否,不传则全部
    private var isPromotion = 0
    //综合排序字段  默认综合排序
    private var selectedSort = "synthesize"
    //选定的课程分类
    private var selectedCourseList = ArrayList<CourseCategoryBean>()
    //所有课程分类
    private var allCourseList = ArrayList<CourseCategoryBean>()
    //所有的筛选数据
    private var allCategoryBean: CourseCategoryBean? = null
    //热门筛选数据
    private var hotSearchList = ArrayList<CourseCategoryBean>()

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    companion object {
        const val PARAMS_LISTTYPE = "listType"
        const val PARAMS_ISFREE = "isFree"
        fun start(context: Context, type: Int) {
            var i = Intent(context, CourseListContainerActivity::class.java)
            i.putExtra(PARAMS_LISTTYPE, type)
            context.startActivity(i)
        }

        fun start(context: Context, type: Int, childType: Int) {
            var i = Intent(context, CourseListContainerActivity::class.java)
            i.putExtra(PARAMS_LISTTYPE, type)
            i.putExtra(PARAMS_ISFREE, childType)
            context.startActivity(i)
        }
    }

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

    override fun initDataAndEvent() {
        if (intent.hasExtra(PARAMS_LISTTYPE)) {
            currentType = intent.getStringExtra(PARAMS_LISTTYPE)
        }
        isFree = intent.getIntExtra(PARAMS_ISFREE, 0)

        if (!TextUtils.isEmpty(intent.getStringExtra("routerParam"))) {
            try {
                val jsonObject = JSONObject(intent.getStringExtra("routerParam"))
                currentType = jsonObject.getString(PARAMS_LISTTYPE)
                isFree = jsonObject.getInt(PARAMS_ISFREE)
            } catch (e: JSONException) {
                LogUtil.e("--json解析错误" + e.message)
            }
        }
        if (TextUtils.equals("0", currentType)) {
            currentType = "10"
        }

        search_view.initBarType(SearchBarView.JUMP_TO_SEARCH_COURSE, null)
        iv_back.setOnClickListener {

            ActionCountUtils.count(CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_RETURN_CLICK)

            finish()
        }
        search_view.setTextVisibility()
        search_view.setTextTitle("搜索")

        init()
        initCouponHintView()
        setClick()

        initNetLossView()

        if (this@CourseListContainerActivity.isFree != 0 || this@CourseListContainerActivity.isInvite != 0 || this@CourseListContainerActivity.isPromotion != 0) {
            filter_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            filter_layout.setTextColor(
                ContextCompat.getColor(
                    this@CourseListContainerActivity,
                    R.color.platform_main_theme
                )
            )
        } else {
            filter_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            filter_layout.setTextColor(
                ContextCompat.getColor(
                    this@CourseListContainerActivity,
                    R.color.course_color_242424
                )
            )
        }
    }

    private fun init() {
        // header
        val header = MaterialHeader(this)
        val colors = resources.getIntArray(R.array.course_colors)
        header.setColorSchemeColors(colors)
        header.layoutParams = AbsListView.LayoutParams(-1, -2)
        val padding = resources.getDimension(R.dimen.default_dis_size).toInt()
        header.setPadding(0, padding, 0, padding)
        header.setPtrFrameLayout(store_house_ptr_frame)
        store_house_ptr_frame.headerView = header
        store_house_ptr_frame.setPtrHandler(this)
        store_house_ptr_frame.addPtrUIHandler(header)

        val footerView = LoadMoreView(this)
        load_more_list_view_container.setLoadMoreView(footerView)
        load_more_list_view_container.setLoadMoreUIHandler(footerView)
        footerView.onLoading(load_more_list_view_container)
        load_more_list_view_container.setLoadMoreHandler(this)
        adapter = CourseNewListAdapter(this)
        lv_content.adapter = adapter
        lv_content.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                val course = adapter!!.dataList[position]
                if (course != null) {

                    val h5Params = H5Params(CourseConstants.COURSE_DETAIL_H5 + course.id, "课程详情")
                    if (null != course.share && !TextUtils.isEmpty(course.share.share_url)) {
                        val shareData =
                            ShareData(
                                course.share.share_url,
                                course.share.title,
                                course.share.cover,
                                course.share.desc
                            )
                        h5Params.shareData = shareData
                    }


                    NewH5Activity.start(this@CourseListContainerActivity, h5Params)
                }
            }

        loadData()
    }

    /**
     * 获取课程分类数据
     */
    @SuppressLint("CheckResult")
    private fun loadData() {
        CourseRetrofitUtils.getCourseListCategory()
            .subscribeOn(Schedulers.io())
            .compose(RxUtils.resultJavaData())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp?.childSample != null && resp.childSample.size > 0) {
                    allCategoryBean = resp
                    repeat(resp.childSample.size) {
                        if (resp.childSample[it].id == 2) {
                            allCourseList.addAll(resp.childSample[it].childSample)
                            return@repeat
                        }
                    }
                    if (currentType != "") {
                        for (bean in allCourseList) {
                            if (TextUtils.equals(bean.type, currentType)) {
                                currentValue = bean.value
                                selectedCourseList.add(bean)
                                break
                            }
                        }
                    }

                    getData(false)

                    if (selectedCourseList.size > 0) {
                        classify_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                        classify_layout.setTextColor(
                            ContextCompat.getColor(
                                this@CourseListContainerActivity,
                                R.color.platform_main_theme
                            )
                        )
                    } else {
                        classify_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                        classify_layout.setTextColor(
                            ContextCompat.getColor(
                                this@CourseListContainerActivity,
                                R.color.course_color_242424
                            )
                        )
                    }

                    repeat(resp.childSample.size) {
                        if (resp.childSample[it].id == 4) {
                            addHotSearchView(resp.childSample[it].childSample)
                            return@repeat
                        }
                    }
                }

            }, { t: Throwable? ->
            })
    }

    private fun initCouponHintView() {
        hint_view.initData(View.VISIBLE)
        hint_view.setCouponList()
    }

    private fun setClick() {
        //综合排序弹窗
        sort_layout.setOnClickListener {
            var popupWindow =
                CourseSortPopupWindow(
                    this,
                    selectedSort,
                    object : CourseSortPopupWindow.OnSortItemSelectedListener {
                        override fun onSortItemSelected(sortItem: String) {
                            selectedSort = sortItem
                            getData(false)

                            ActionCountUtils.count(
                                CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_SORT_CLICK,
                                selectedSort
                            )
                        }
                    })
            popupWindow.setOnDismissListener {
                sort_layout.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_arrow_drop_down_un,
                    0
                )
            }
            sort_layout.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.platform_arrow_drop_down_en,
                0
            )
            popupWindow.showAsDropDown(view_line)
        }
        //分类排序弹窗--现在是只支持单选
        classify_layout.setOnClickListener {
            var popupWindow = CourseGoodPopupWindow(
                this,
                allCourseList,
                selectedCourseList,
                object : CourseGoodPopupWindow.OnGoodSelectedListener {
                    override fun onGoodSelected(selectedGoodsList: ArrayList<CourseCategoryBean>) {//现在是只支持单选:selectedGoodsList里面最多只有一个数据
                        selectedCourseList.clear()
                        selectedCourseList.addAll(selectedGoodsList)
                        if (selectedCourseList.size > 0) {
                        }
                        if (selectedGoodsList.size == 0) {
                            //重置所有选择条件:这时候默认选择全部类型
                            currentType = "10"
                            currentValue = "listType"
                        }
                        getData(false)

                        var name =
                            if (selectedGoodsList.size == 0) "全部类型" else selectedGoodsList[0].name
                        ActionCountUtils.count(
                            CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_CLASSIFICATION_CLICK,
                            name
                        )
                    }
                })
            popupWindow.setOnDismissListener {
                if (selectedCourseList.size > 0) {
                    classify_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    classify_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.platform_main_theme
                        )
                    )
                } else {
                    classify_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    classify_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.course_color_242424
                        )
                    )
                }
                classify_layout.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_arrow_drop_down_un,
                    0
                )
            }
            classify_layout.setTextColor(
                ContextCompat.getColor(
                    this@CourseListContainerActivity,
                    R.color.platform_main_theme
                )
            )
            classify_layout.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.platform_arrow_drop_down_en,
                0
            )
            popupWindow.showAsDropDown(view_line)
        }

        //筛选
        filter_layout.setOnClickListener {
            var popupWindow = CourseFilterPopupWindow(
                this@CourseListContainerActivity,
                isFree,
                isInvite,
                isPromotion,
                object : CourseFilterPopupWindow.OnFilterSelectedListener {
                    override fun onFilterSelected(isFree: Int, isInvite: Int, isPromotion: Int) {
                        this@CourseListContainerActivity.isFree = isFree
                        this@CourseListContainerActivity.isInvite = isInvite
                        this@CourseListContainerActivity.isPromotion = isPromotion

                        getData(false)


                        var sign = if (isFree == 1) "免费" else "付费"
                        if (isInvite == 1) {
                            sign += "返利"
                        }
                        if (isPromotion == 1) {
                            sign += "促销"
                        }
                        ActionCountUtils.count(
                            CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_FILTER_CLICK,
                            sign
                        )
                    }
                })
            popupWindow.setOnDismissListener {
                if (this@CourseListContainerActivity.isFree != 0 || this@CourseListContainerActivity.isInvite != 0 || this@CourseListContainerActivity.isPromotion != 0) {
                    filter_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    filter_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.platform_main_theme
                        )
                    )
                } else {
                    filter_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    filter_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.course_color_242424
                        )
                    )
                }
                filter_layout.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_arrow_drop_down_un,
                    0
                )
            }
            filter_layout.setTextColor(
                ContextCompat.getColor(
                    this@CourseListContainerActivity,
                    R.color.platform_main_theme
                )
            )
            filter_layout.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.platform_arrow_drop_down_en,
                0
            )
            popupWindow.showAsDropDown(view_line)
        }


    }

    /**
     * 初始化无网络视图
     */
    private fun initNetLossView() {
        v_loading.setListener(object : LogoLoadingView.LogoLoadingListener {
            override fun onDataResetClick() {
                v_loading.visibility = View.VISIBLE
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
                getData(false)
            }

            override fun onBackClick() {
                finish()
            }
        })
    }

    /**
     * 获取课程具体数据
     */
    private fun getData(loadMore: Boolean) {
        if (loadMore && !hasMore) {
            load_more_list_view_container.loadMoreFinish(false, false)
            return
        }
        if (loadMore) {
            page++
        } else {
            page = 1
            hasMore = true
            if (adapter!=null){
                adapter?.refreshLatPosition()
            }
        }
        getCourses(loadMore)
    }


    @SuppressLint("CheckResult")
    private fun getCourses(loadMore: Boolean) {
        val sb = StringBuffer()
        if (selectedCourseList.size > 0) {
            currentType = selectedCourseList[0].type
            currentValue = selectedCourseList[0].value
        }
        var map = HashMap<String, Any>()
        map["&$currentValue="] = currentType
        map["&page="] = page
        map["&isFree="] = isFree
        map["&reorder="] = selectedSort
        map["&isInvite="] = isInvite
        map["&isPromotion="] = isPromotion

        if (keyList.size > 0) {
            repeat(keyList.size) {
                map["&${keyList[it]}="] = valueList[it]
            }
        }

        for (key in map.keys) {
            sb.append(key).append(map[key])
        }


        val urlParams = NetworkParamsUtils.getCommonParam() + sb.toString()

        //不是上拉加载更多，是第一次加载或者下拉刷新，且当前页面还没有数据
        if (!loadMore && adapter?.count!! <= 0) {
            lv_content.visibility = View.GONE
            v_loading.visibility = View.VISIBLE
            v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
        }

        CourseRetrofitUtils.getCourseList(urlParams).compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.list.isNotEmpty()) {

                    if (load_more_list_view_container != null) {
                        load_more_list_view_container.loadMoreFinish(false, true)
                    }
                    try {
                        val courses = ArrayList<Course>()
                        courses.addAll(resp.list)
                        if (courses.size < CourseConstants.COURSE_PAGE_SIZE) {
                            hasMore = false
                        }
                        if (!loadMore) {
                            adapter!!.dataList = courses
                            adapter!!.notifyDataSetChanged()
                            lv_content.setSelection(0)
                        } else {
                            adapter!!.addDataList(courses)
                            adapter!!.notifyDataSetChanged()
                        }

                    } catch (e: Exception) {
                        LogUtil.e(e.toString())
                    }

                    lv_content.visibility = View.VISIBLE
                    tv_course_list_empty_prompt.visibility = View.GONE
                    iv_course_list_empty_view.visibility = View.GONE
                    v_loading.visibility = View.GONE
                } else {
                    if (adapter!!.count > 0) {
//                        hasMore = false
                        load_more_list_view_container.loadMoreFinish(false, false)
                    } else {
                        lv_content.visibility = View.GONE
                        tv_course_list_empty_prompt.visibility = View.VISIBLE
                        iv_course_list_empty_view.visibility = View.VISIBLE
                        iv_course_list_empty_view.setImageResource(R.drawable.course_blank)
                        tv_course_list_empty_prompt.text = "还没有相应的课程哦~"
                        v_loading.visibility = View.GONE
                    }
                }
            }, { throwable ->
                v_loading.visibility = View.GONE
                if (adapter!!.mDataList == null || adapter!!.mDataList.size <= 0) {
                    lv_content.visibility = View.GONE

                    tv_course_list_empty_prompt.visibility = View.GONE
                    iv_course_list_empty_view.visibility = View.GONE
                    v_loading.visibility = View.VISIBLE
                    v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, "哎呦，网络开小差了")
                } else {
                    ToastHelper.show("网络不给力")
                    CourseRetrofitUtils.handleError(this@CourseListContainerActivity, throwable)
                }
            })
    }


    private fun addHotSearchView(list: List<CourseCategoryBean>) {
        hotSearchList.clear()
        hotSearchList.addAll(list)

        repeat(list.size) {
            var index = it
            val textView = View.inflate(this, R.layout.item_hot_search_view, null)
            val tv = textView.tv_hot_search
            val params = LinearLayout.LayoutParams(0, RxImageTool.dp2px(22f))
            params.weight = 1f
            params.setMargins(0, 0, RxImageTool.dp2px(10f), 0)
            tv.layoutParams = params
            tv.text = list[it].name

            tv.setOnClickListener {
                if (tv.isSelected) {
                    dealHotSelect(list[index], false)
                    tv.isSelected = false
                } else {
                    dealHotSelect(list[index], true)
                    tv.isSelected = true
                }
            }
            ll_hot_search.addView(textView)
        }
    }


    private fun dealHotSelect(bean: CourseCategoryBean, isAdd: Boolean) {
        when (bean.parentId) {
            1 -> {//排序
                if (isAdd) {
                    selectedSort = bean.type
                    //处理view选中状态
                    repeat(hotSearchList.size) {
                        if (hotSearchList[it].parentId == 1 && !TextUtils.equals(
                                hotSearchList[it].name,
                                bean.name
                            )
                        ) {
                            val textView = ll_hot_search.getChildAt(it) as TextView
                            textView.isSelected = false
                        }
                    }
                } else {
                    selectedSort = "synthesize"
                }
            }
            2 -> {//分类
                selectedCourseList.clear()
                if (isAdd) {
                    selectedCourseList.add(bean)
                } else {
                    //重置所有分类条件:这时候默认选择全部类型
                    currentValue = "listType"
                    currentType = "10"
                }

                repeat(hotSearchList.size) {
                    if (hotSearchList[it].parentId == 2 && !TextUtils.equals(
                            hotSearchList[it].name,
                            bean.name
                        )
                    ) {
                        val textView = ll_hot_search.getChildAt(it) as TextView
                        textView.isSelected = false
                    }
                }

                if (selectedCourseList.size > 0) {
                    classify_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    classify_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.platform_main_theme
                        )
                    )
                } else {
                    classify_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    classify_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.course_color_242424
                        )
                    )
                }
                classify_layout.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_arrow_drop_down_un,
                    0
                )
            }
            3 -> {//筛选
                if (isAdd) {
                    if (TextUtils.equals(bean.name, "免费") || TextUtils.equals(bean.name, "付费")) {
                        isFree += bean.type.toInt()
                    }
                    if (TextUtils.equals(bean.name, "限时促销")) {
                        isInvite = 1
                    }
                    if (TextUtils.equals(bean.name, "邀请返利")) {
                        isPromotion = 1
                    }
                } else {
                    if (TextUtils.equals(bean.name, "免费") || TextUtils.equals(bean.name, "付费")) {
                        isFree -= bean.type.toInt()
                    }
                    if (TextUtils.equals(bean.name, "限时促销")) {
                        isInvite = 0
                    }
                    if (TextUtils.equals(bean.name, "邀请返利")) {
                        isPromotion = 0
                    }
                }

                if (this@CourseListContainerActivity.isFree != 0 || this@CourseListContainerActivity.isInvite != 0 || this@CourseListContainerActivity.isPromotion != 0) {
                    filter_layout.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    filter_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.platform_main_theme
                        )
                    )
                } else {
                    filter_layout.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    filter_layout.setTextColor(
                        ContextCompat.getColor(
                            this@CourseListContainerActivity,
                            R.color.course_color_242424
                        )
                    )
                }
            }
            else -> {//热门筛选
                if (isAdd) {
                    keyList.add(bean.value)
                    valueList.add(bean.type)
                } else {
                    keyList.remove(bean.value)
                    valueList.remove(bean.type)
                }
            }
        }
        getData(false)
    }

    override fun onRefreshBegin(frame: PtrFrameLayout?) {
        frame!!.postDelayed({
            if (store_house_ptr_frame != null) {
                store_house_ptr_frame.refreshComplete()
            }
        }, 1800)
        getData(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!PlayerFloatHelper.isCanClick) {
            PlayerFloatHelper.removeResetView()
        }
    }


    override fun onResume() {
        super.onResume()
        ActionCountUtils.count(CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_PAGE_VISIT)
    }

    override fun checkCanDoRefresh(frame: PtrFrameLayout?, content: View?, header: View?): Boolean {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, lv_content, header)
    }

    override fun onLoadMore(loadMoreContainer: LoadMoreContainer?) {
        getData(true)
    }
}
