package com.yidianling.consultant.ui.view.topView

import android.annotation.SuppressLint
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.R
import com.yidianling.consultant.bean.ExpertSearchBigShotBean
import com.yidianling.consultant.bean.ExpertSearchRecommandBean
import com.yidianling.consultant.http.ExpertSearchHttpImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.consultant_expert_search_top_all_view.view.*

class RecommendListView : LinearLayout {


    constructor(context: Context) : super(context) {
        mContext = context
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        mContext = context
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        mContext = context
        initView()
    }

    private var mContext: Context? = null
    private var mSceneSpecialTopicList =
        ArrayList<ExpertSearchRecommandBean>() // viewPager的所有item数据
    private var mViewPagerList = ArrayList<LinearLayout>() //viewPager的数据
    private var mDoctorSpecialTopicsList = ArrayList<ExpertSearchBigShotBean>() //viewPager的数据
    private var minHeight: Int = 0 // viewPager最小高度
    private var maxHeight: Int = 0 // viewPager最大高度

    private var dp_10: Int = RxImageTool.dp2px(10f)
    private var dp_4: Int = RxImageTool.dp2px(4f)

    private fun initView() {

        layoutParams = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )

        orientation = VERTICAL
        View.inflate(mContext, R.layout.consultant_expert_search_top_all_view, this)


        //无数据则隐藏所有布局
        recommendViewPager.visibility = View.GONE
        recommendViewPagerIndicator.visibility = View.GONE
        itemListView.visibility = View.GONE

        requestData()
    }

    @SuppressLint("CheckResult")
    fun requestData() {
        ExpertSearchHttpImpl.getInstance().getBigShotData()
            .subscribeOn(Schedulers.io())
            .compose(RxUtils.resultJavaData())
            .map { it }
            .filter { true }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                mSceneSpecialTopicList.clear()
                mDoctorSpecialTopicsList.clear()
                itemListView.removeAllViews()
                if (null != mContext) {
                    if (it.sceneSpecialTopics == null || it.sceneSpecialTopics.size == 0) {
                        recommendViewPager.visibility = View.GONE
                        recommendViewPagerIndicator.visibility = View.GONE
                    } else {
                        mSceneSpecialTopicList.addAll(it.sceneSpecialTopics)
                        recommendViewPager.visibility = View.VISIBLE
                        recommendViewPagerIndicator.visibility = View.VISIBLE
                    }
                    if (it.doctorSpecialTopics == null || it.doctorSpecialTopics.size == 0) {
                        itemListView.visibility = View.GONE
                    } else {
                        mDoctorSpecialTopicsList.addAll(it.doctorSpecialTopics)
                        itemListView.visibility = View.VISIBLE
                    }
                    setData()
                }

            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    ToastUtil.toastShort(msg)
                }
            })
    }

    /**
     * 设置数据
     */
    fun setData() {
        // 顶部viewpager数据
        if (mSceneSpecialTopicList.isNotEmpty()) {

            initMinHeight(mSceneSpecialTopicList.size)

            initViewPager()
        }
        //多种不同类型大咖专区
        if (mDoctorSpecialTopicsList.isNotEmpty()) {
            setBigShotViewData()
        }

    }

    private fun initViewPager() {
        mContext?.let {
            mViewPagerList.clear()
            /**
             * 渲染第一页数据
             */
            val firstPagerHeight =
                RxImageTool.dp2px(60f * (getMinData(mSceneSpecialTopicList.size + 1, 4 + 1) / 2))
            val firstPager = getLinearLayout(
                mContext!!,
                firstPagerHeight, VERTICAL
            )
            for (index in 0 until getMinData(mSceneSpecialTopicList.size, 4) step 2) {
                val ll = getLinearLayout(mContext!!, RxImageTool.dp2px(60f), HORIZONTAL)

                val item = RecommendItemView(mContext!!)

                item.setPadding(
                    RxImageTool.dp2px(15f),
                    RxImageTool.dp2px(9f),
                    RxImageTool.dp2px(15f),
                    RxImageTool.dp2px(11f)
                )

                item.setData(mSceneSpecialTopicList[index])
                ll.addView(item)
                if (index + 1 < mSceneSpecialTopicList.size) {
                    val item1 = RecommendItemView(mContext!!)

                    item1.setPadding(
                        0,
                        RxImageTool.dp2px(9f),
                        RxImageTool.dp2px(15f),
                        RxImageTool.dp2px(11f)
                    )

                    item1.setData(mSceneSpecialTopicList[index + 1])
                    ll.addView(item1)
                }
                firstPager.addView(ll)
            }
            mViewPagerList.add(firstPager)

            /**
             * 渲染第二页数据
             */
            val secondPagerHeight =
                RxImageTool.dp2px(60f * ((mSceneSpecialTopicList.size - 4 + 1) / 2))
            maxHeight = secondPagerHeight + RxImageTool.dp2px(11f)
            if (mSceneSpecialTopicList.size > 4) {
                val secondPager = getLinearLayout(
                    mContext!!,
                    secondPagerHeight, VERTICAL
                )
                for (index in 4 until mSceneSpecialTopicList.size step 2) {
                    val ll = getLinearLayout(mContext!!, RxImageTool.dp2px(60f), HORIZONTAL)

                    val item = RecommendItemView(mContext!!)

                    item.setPadding(
                        RxImageTool.dp2px(15f),
                        RxImageTool.dp2px(9f),
                        RxImageTool.dp2px(15f),
                        RxImageTool.dp2px(11f)
                    )

                    item.setData(mSceneSpecialTopicList[index])
                    ll.addView(item)
                    if (index + 1 < mSceneSpecialTopicList.size) {
                        val item1 = RecommendItemView(mContext!!)

                        item1.setPadding(
                            0,
                            RxImageTool.dp2px(9f),
                            RxImageTool.dp2px(15f),
                            RxImageTool.dp2px(11f)
                        )

                        item1.setData(mSceneSpecialTopicList[index + 1])
                        ll.addView(item1)
                    }
                    secondPager.addView(ll)
                }
                mViewPagerList.add(secondPager)
            }

            recommendViewPager.adapter = RecommendViewPagerAdapter()
            recommendViewPager.currentItem = 0

            if (mSceneSpecialTopicList.size <= 4) {
                recommendViewPagerIndicator.visibility = View.GONE
            } else {
                recommendViewPagerIndicator.visibility = View.VISIBLE
                setSelectedIndex(0) // 默认为左边选中
            }

            addListener()
        }
    }

    private fun addListener() {

        recommendViewPager.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                when (event?.action) {
                    MotionEvent.ACTION_MOVE -> {
                        mListener?.viewPagerScroll(true)
                    }
                    MotionEvent.ACTION_UP -> {
                        mListener?.viewPagerScroll(false)
                    }
                    MotionEvent.ACTION_CANCEL -> {
                        mListener?.viewPagerScroll(false)
                    }
                }
                return false
            }
        })


        recommendViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                if (position == 0) {
                    val params = recommendViewPager.layoutParams
                    params.height = (minHeight + (maxHeight - minHeight) * positionOffset).toInt()
                    recommendViewPager.layoutParams = params
                }
            }

            override fun onPageSelected(position: Int) {
                setSelectedIndex(position)
            }
        })
    }

    private fun setSelectedIndex(position: Int) {
        if (position == 0) {
            leftIndicator.layoutParams = LayoutParams(dp_10, dp_4)
            val marginParams = leftIndicator.layoutParams as MarginLayoutParams
            marginParams.rightMargin = RxImageTool.dp2px(6f)
            leftIndicator.layoutParams = marginParams
            leftIndicator.setBackgroundResource(R.drawable.consultant_indicator_selected)
            rightIndicator.layoutParams = LayoutParams(dp_4, dp_4)
            rightIndicator.setBackgroundResource(R.drawable.consultant_indicator_unselected)
        } else {
            leftIndicator.layoutParams = LayoutParams(dp_4, dp_4)
            val marginParams = leftIndicator.layoutParams as MarginLayoutParams
            marginParams.rightMargin = RxImageTool.dp2px(6f)
            leftIndicator.layoutParams = marginParams
            leftIndicator.setBackgroundResource(R.drawable.consultant_indicator_unselected)
            rightIndicator.layoutParams = LayoutParams(dp_10, dp_4)
            rightIndicator.setBackgroundResource(R.drawable.consultant_indicator_selected)
        }
    }

    private fun getMinData(a: Int, b: Int): Int {
        return if (a < b) a else b
    }

    /**
     * 初始化的高度为第一页的高度，与第二页的数据（无论有没有）没有关系
     */
    private fun initMinHeight(size: Int) {
        if (size < 4) {
            minHeight = RxImageTool.dp2px(11f + 60f * ((mSceneSpecialTopicList.size + 1) / 2))
            setViewPagerCustomHeight(minHeight)
        } else {
            minHeight = RxImageTool.dp2px(11f + 60f * ((4 + 1) / 2))
            setViewPagerCustomHeight(minHeight)
        }
    }

    /**
     * 设置布局高度
     */
    private fun setViewPagerCustomHeight(mHeight: Int) {
        val params = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        params.height = mHeight
        recommendViewPager.layoutParams = params
    }

    private fun getLinearLayout(mContext: Context, mHeight: Int, mOrientation: Int): LinearLayout {
        val params = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            mHeight
        )
        val ll = LinearLayout(mContext)
        ll.layoutParams = params
        ll.orientation = mOrientation
        return ll
    }

    internal inner class RecommendViewPagerAdapter : PagerAdapter() {

        override fun getCount(): Int {
            return mViewPagerList.size
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val view = mViewPagerList[position]
            container.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }
    }

    /**
     *  设置大咖专区数据
     */
    private fun setBigShotViewData() {
        itemListView.layoutParams = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        mContext?.let {
            if (mDoctorSpecialTopicsList.isNotEmpty()) {
                when {
                    mDoctorSpecialTopicsList.size == 1 -> {
                        val mView = BigShotOneView(mContext!!)
                        mView.setUrl(mDoctorSpecialTopicsList[0])
                        itemListView.addView(mView)
                    }
                    mDoctorSpecialTopicsList.size == 2 -> {
                        val mView = BigShotTwoView(mContext!!)
                        mView.setUrl(mDoctorSpecialTopicsList[0], mDoctorSpecialTopicsList[1])
                        itemListView.addView(mView)
                    }
                    mDoctorSpecialTopicsList.size == 3 -> {
                        val mView = BigShotThreeView(mContext!!)
                        mView.setUrl(
                            mDoctorSpecialTopicsList[0],
                            mDoctorSpecialTopicsList[1],
                            mDoctorSpecialTopicsList[2]
                        )
                        itemListView.addView(mView)
                    }
                    mDoctorSpecialTopicsList.size == 4 -> {
                        val mView = BigShotTwoView(mContext!!)
                        val params = mView.layoutParams as MarginLayoutParams
                        params.bottomMargin = RxImageTool.dp2px(10f)
                        mView.layoutParams = params
                        val mView1 = BigShotTwoView(mContext!!)

                        mView.setUrl(mDoctorSpecialTopicsList[0], mDoctorSpecialTopicsList[1])
                        mView1.setUrl(mDoctorSpecialTopicsList[2], mDoctorSpecialTopicsList[3])
                        itemListView.addView(mView)
                        itemListView.addView(mView1)
                    }
                    mDoctorSpecialTopicsList.size == 5 -> {
                        val mView = BigShotThreeView(mContext!!)
                        val params = mView.layoutParams as MarginLayoutParams
                        params.bottomMargin = RxImageTool.dp2px(10f)
                        mView.layoutParams = params
                        val mView1 = BigShotTwoView(mContext!!)

                        mView.setUrl(
                            mDoctorSpecialTopicsList[0],
                            mDoctorSpecialTopicsList[1],
                            mDoctorSpecialTopicsList[2]
                        )
                        mView1.setUrl(mDoctorSpecialTopicsList[3], mDoctorSpecialTopicsList[4])
                        itemListView.addView(mView)
                        itemListView.addView(mView1)
                    }
                    mDoctorSpecialTopicsList.size == 6 -> {
                        val mView = BigShotThreeView(mContext!!)
                        val params = mView.layoutParams as MarginLayoutParams
                        params.bottomMargin = RxImageTool.dp2px(10f)
                        mView.layoutParams = params
                        val mView1 = BigShotThreeView(mContext!!)

                        mView.setUrl(
                            mDoctorSpecialTopicsList[0],
                            mDoctorSpecialTopicsList[1],
                            mDoctorSpecialTopicsList[2]
                        )
                        mView1.setUrl(
                            mDoctorSpecialTopicsList[3],
                            mDoctorSpecialTopicsList[4],
                            mDoctorSpecialTopicsList[5]
                        )
                        itemListView.addView(mView)
                        itemListView.addView(mView1)
                    }
                }
            }
        }
    }

    private var mListener: ViewPagerScrollStateCallback? = null

    fun addViewPagerScrollStateListener(listener: ViewPagerScrollStateCallback?) {
        listener?.let {
            mListener = listener
        }
    }


    interface ViewPagerScrollStateCallback {
        fun viewPagerScroll(isScrolling: Boolean) //isScrolling
    }


}