package com.yidianling.course.courseNew.home

import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.base_module.ui.searchbarview.SearchBarView
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_router.manager.YDLRouterManager
import com.yidianling.course.R
import com.yidianling.course.bean.CourseCouponBean
import com.yidianling.course.bean.CourseHomeBodyBean
import com.yidianling.course.courseNew.BannerBean
import com.yidianling.course.courseNew.mine.MyCourseActivity
import com.yidianling.course.courseNew.sections.*
import com.yidianling.course.coursePlay.common.net.RetrofitUtils
import com.yidianling.course.model.CatogoryBean
import com.yidianling.course.model.NormalCourseBean
import com.yidianling.course.model.QulityCourseBean
import com.yidianling.course.router.CourseIn
import com.yidianling.course.widget.CourseCouponDialog
import com.yidianling.ydlcommon.adapter.section.SectionAdapter
import com.yidianling.ydlcommon.base.BaseFragment
import com.yidianling.ydlcommon.event.SelectTabCallPhoneEvent
import com.yidianling.ydlcommon.http.BaseResponse
import com.yidianling.ydlcommon.player.YDLMusicHelper
import com.yidianling.ydlcommon.remind.ToastHelper
import com.yidianling.ydlcommon.ui.LogoLoadingView
import com.yidianling.ydlcommon.utils.UMEventUtils
import com.yidianling.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.ydlcommon.utils.actionutil.BIConstants
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.fragment_course_home.*


/**
 * Created by Jim on 2018/6/21 0021.
 * 课程首页Fragment
 */
class CourseHomeFragment : BaseFragment(), ICourseHomeView, SwipeRefreshLayout.OnRefreshListener {

    private var presenter: CourseHomePresenter = CourseHomePresenter(this)
    private var adapter = SectionAdapter()
    private var dialog: CourseCouponDialog? = null

    companion object {
        private const val BANNER = 1
        private const val CATEGORY = 2
        private const val QULITY_COURSE = 3
        private const val CLASSIFIED_COURSE = 4
        private const val TOPIC = 5
        private const val LIST_END = 7
    }


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

    override fun initDataAndEvent() {

    }

    override fun initDataAndEventLazy() {
        initViews()
        initNetLossView()
        //加载本地缓存数据
        presenter.localData(context)
        presenter.fetchData()

        initCouponHintView()
    }

    override fun isAddStatusView(): Boolean {
        return true
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            presenter.prepareCoupon()

            ActionCountUtils.count(BIConstants.CourseHomeEvent.POSITION_COURSE_HOME_PAGE_VISIT)
        }
    }

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

    private fun initViews() {
        iv_back.setOnClickListener {
            EventBus.getDefault().post(SelectTabCallPhoneEvent(0))
        }
        swl?.setOnRefreshListener(this)
        swl?.setColorSchemeResources(R.color.google_green)
        rcv?.layoutManager = LinearLayoutManager(activity)
        rcv?.adapter = adapter


        activity_course_search_bar.initBarType(SearchBarView.JUMP_TO_SEARCH_COURSE, null)
        GlideApp.with(activity).load(R.drawable.music).into(img_music)

        img_music.setOnClickListener {
            if (YDLMusicHelper.isCoursePlaying()) {
                //课程播放页
                YDLMusicHelper.startCoursePlayActivity(activity, 1)
            } else {
                img_music.visibility = View.GONE
            }
        }
        tv_left_menu.setOnClickListener {

            ActionCountUtils.count(BIConstants.CourseHomeEvent.POSITION_COURSE_HOME_MY_COUSE_CLICK)

            if (CourseIn.isLogin()) {
                MyCourseActivity.start(activity)
            } else {
                startActivity(CourseIn.loginWayIntent(activity))
            }
        }
    }

    private fun initNetLossView() {
        v_loading.visibility = View.VISIBLE
        v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
        v_loading.setListener(object : LogoLoadingView.LogoLoadingListener {
            override fun onDataResetClick() {
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
                presenter.fetchData()
            }

            override fun onBackClick() {
                EventBus.getDefault().post(SelectTabCallPhoneEvent(0))
            }
        })
    }

    override fun showBody(resultBeans: List<ResultBean>) {
        if (resultBeans.isEmpty()) {
            return
        }
        v_loading.visibility = View.GONE

        rcv?.visibility = View.VISIBLE
        adapter.clearData()
        for (resultBean in resultBeans) {
            when (resultBean.type) {
                BANNER -> {
                    val bannerMap = resultBean.body
                    val banners = ArrayList<BannerBean>()
                    for (map in bannerMap) {
                        val banner = BannerBean()
                        banner.image = map.image
                        banner.title = map.title
                        banner.linkUrl = map.linkUrl
                        banners.add(banner)
                    }
                    adapter.addSection(BannerSection(banners))
                }
                CATEGORY -> {
                    val categoryMap = resultBean.body
                    val categorys = ArrayList<CatogoryBean>()
                    for (map in categoryMap) {
                        val category = CatogoryBean()
                        category.image = map.image
                        category.title = map.title
                        category.linkUrl = map.linkUrl
                        categorys.add(category)
                    }
                    adapter.addSection(CategorySection(categorys))
                }
                QULITY_COURSE -> {
                    val totalCourse = ArrayList<ArrayList<CourseHomeBodyBean>>()
                    val coursesLeft = ArrayList<CourseHomeBodyBean>()
                    val coursesRight = ArrayList<CourseHomeBodyBean>()
                    for (result in resultBean.body) {
                        if (TextUtils.equals(result.type, "1")) {
                            coursesLeft.add(result)
                        }
                        if (TextUtils.equals(result.type, "2")) {
                            coursesRight.add(result)
                        }
                    }
                    totalCourse.add(coursesLeft)
                    totalCourse.add(coursesRight)

                    val course = QulityCourseBean().apply {
                        this.diviLine = resultBean.diviLine
                        this.head = resultBean.head
                        this.footer = resultBean.footer
                        this.body = totalCourse
                    }
                    adapter.addSection(QulityCourseSection(activity, course, adapter))
                }

                CLASSIFIED_COURSE -> {
                    val classifiedMap = resultBean.body
                    val normal = NormalCourseBean().apply {
                        this.head = resultBean.head
                        this.footer = resultBean.footer
                        this.diviLine = resultBean.diviLine
                        this.body = classifiedMap
                    }
                    adapter.addSection(ClassifiedCourseSection(activity, normal))
                }

                TOPIC -> {
                    val topicMap = resultBean.body
                    val normal = NormalCourseBean().apply {
                        this.head = resultBean.head
                        this.footer = resultBean.footer
                        this.diviLine = resultBean.diviLine
                        this.body = topicMap
                    }
                    adapter.addSection(TopicsCoursesSection(context, normal))
                }

                LIST_END -> {
                    val head = resultBean.head
                    adapter.addSection(ListEndSection(head.title))
                }

            }

        }
        adapter.notifyDataSetChanged()
    }


    /**
     * 可领取的优惠券列表
     */
    override fun couponDataResponse(data: List<CourseCouponBean>) {
        if (dialog == null) {
            dialog = CourseCouponDialog(activity, data, object : CourseCouponDialog.OnClickEnsureListener {
                override fun clickUse(toLink: String) {
                    YDLRouterManager.router(toLink)
                    dialog!!.dismiss()
                }

                override fun clickEnsure(status: Int) {
                    if (status == CourseCouponDialog.STATUS_RECEIVER) {
                        presenter.receiveCoupon(data)
                    } else {
                        dialog!!.dismiss()

                        //查看我的卡券
                        ARouter.getInstance().build("/mine/redpacket")
                                .withString("is_from_main", "1")
                                .navigation()
                    }
                }
            })
        }
        dialog!!.show()
    }

    /**
     * 优惠券领取成功
     */
    override fun receiveCouponResponse(data: BaseResponse<List<String>>) {
        if (data.code == 200) {
            dialog?.updateStatus(CourseCouponDialog.STATUS_GET, data.data)
        } else {
            ToastHelper.show(data.msg)
        }
    }

    override fun showLoadErrorView(throwable: Throwable?) {
        RetrofitUtils.handleError(activity, throwable)
    }


    override fun hideRefreshView() {
        swl?.isRefreshing = false
    }

    override fun showRefreshView() {
        swl?.isRefreshing = true
        v_loading.visibility = View.VISIBLE
        v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
    }


    override fun onRefresh() {
        swl?.isRefreshing = true
        presenter.fetchData()
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter?.onDestroy()
    }
}
