package com.yidianling.home.ui.view

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.home.R
import com.yidianling.home.event.IHomeBaseEvent
import com.yidianling.home.model.bean.HomeConsultBean
import com.yidianling.home.model.bean.HomeHeaderBean
import kotlinx.android.synthetic.xlzx.home_consult_view.view.*

/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 咨询理解模块
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/13
 */
class HomeConsultView(private val mContext: Context, private var homeEvent: IHomeBaseEvent?) :
    LinearLayout(mContext) {
    private var mLastPosition: Int = 0
    /**
     * 专家信息view缓存list
     */
    private var cacheInfoViewList: ArrayList<HomeConsultItemView>? = null
    /**
     * TabLayout.OnTabSelectedListener
     */
    private var listener: ConsultTabSelectedListener? = null

    private var dp5: Int = 0
    private var dp6: Int = 0
    private var dp7: Int = 0
    private var dp10: Int = 0
    private var dp16: Int = 0

    init {
        initView()
    }

    private fun initView() {
        dp5 = RxImageTool.dp2px(5f)
        dp6 = RxImageTool.dp2px(6f)
        dp7 = RxImageTool.dp2px(7f)
        dp10 = RxImageTool.dp2px(10f)
        dp16 = RxImageTool.dp2px(16f)

        val params = RecyclerView.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layoutParams = params
        orientation = VERTICAL
        View.inflate(mContext, R.layout.home_consult_view, this)
        homeModuleConfideViewHomeCommonFullTitleView.setTitle("心理咨询")
        homeModuleConfideViewHomeCommonFullTitleView.setMoreText("更多")
        homeModuleConfideViewHomeCommonFullTitleView.setTopMargin(-4)
        homeModuleConfideViewHomeCommonFullTitleView.setOnClickListener {
            homeEvent?.consultMoreClick()
        }
    }

    /**
     * 创建tab栏
     * @param lastPosition 上次选中的下标
     */
    fun setTitle(list: List<HomeHeaderBean.ConsultCategoryDateBean>?, lastPosition: Int) {
        if (list == null || list.isEmpty()) {
            visibility = View.GONE
            return
        }
        if (listener != null) {
            tab_layout.removeOnTabSelectedListener(listener!!)
        }
        mLastPosition = lastPosition
        tab_layout.removeAllTabs()
        for ((index, bean) in list.withIndex()) {

            val textView = updateText(TextView(mContext), index == lastPosition)
            textView.text = bean.name

            val newTab = tab_layout.newTab().setCustomView(textView)

            tab_layout.addTab(newTab, index == lastPosition)
        }
        listener = ConsultTabSelectedListener(list, tab_layout)
        tab_layout.addOnTabSelectedListener(listener!!)
        try {
            var textView = tab_layout.getTabAt(0) as TextView
            updateText(textView, true)
        } catch (e: Exception) {
        }
        tab_layout.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            LogUtil.e("scrollX=$scrollX")
            LogUtil.e("oldScrollX=$oldScrollX")
        }
    }

    /**
     * 设置数据
     */
    fun setConsultInfoView(
        list: List<HomeConsultBean.ListBean>?,
        category: HomeHeaderBean.ConsultCategoryDateBean?
    ) {
        if (list == null || list.isEmpty()) {
            ll_content.visibility = View.GONE
            return
        }
        ll_content.visibility = View.VISIBLE
        ll_content.removeAllViews()
        if (cacheInfoViewList == null) {
            cacheInfoViewList = ArrayList()
        }

        //创建HomeConsultItemView：每个tab最多显示四个专家
        if (cacheInfoViewList!!.size >= list.size) {
            for (index in list.indices) {
                //设置数据
                cacheInfoViewList!![index].setData(
                    list[index],
                    index,
                    index == list.size - 1,
                    "${category?.id}"
                )
                cacheInfoViewList!![index].layoutParams = getViewLayoutParams(index)
                //添加到布局
                ll_content.addView(cacheInfoViewList!![index])
            }
        } else {
            for (index in list.indices) {
                if (index > 3) {
                    //只取前四条数据
                    break
                }
                //数据大于缓存view数量，创建view
                if (index > cacheInfoViewList!!.size - 1) {
                    var mHomeConsultItemView = createConsultInfoView()
                    cacheInfoViewList!!.add(mHomeConsultItemView)
                }
                //设置数据
                cacheInfoViewList!![index].setData(
                    list[index],
                    index,
                    index == list.size - 1,
                    "${category?.id}"
                )
                cacheInfoViewList!![index].layoutParams = getViewLayoutParams(index)
                //添加到布局
                ll_content.addView(cacheInfoViewList!![index])
            }
        }
    }

    fun getViewLayoutParams(index: Int): MarginLayoutParams {
        var itemWidth: Int = (RxDeviceTool.getScreenWidth(mContext) - dp10 - dp10) / 2
        var itemHeight: Int = (itemWidth * 187) / 166
        var topMargin = if (index == 2 || index == 3) itemHeight else 0
        val params = LayoutParams(itemWidth, itemHeight) as MarginLayoutParams
        params.setMargins(dp10 + (itemWidth) * ((index) % 2),
            topMargin,
            0,0
            )
        return params
    }

    /**
     * 创建专家信息view
     */
    private fun createConsultInfoView(): HomeConsultItemView {
        return HomeConsultItemView(mContext, homeEvent)
    }


    inner class ConsultTabSelectedListener : TabLayout.OnTabSelectedListener {
        private var list: List<HomeHeaderBean.ConsultCategoryDateBean>? = null
        private var tabLayout: TabLayout? = null

        constructor(list: List<HomeHeaderBean.ConsultCategoryDateBean>, tabLayout: TabLayout) {
            this.list = list
            this.tabLayout = tabLayout
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            var textView = tabLayout?.getTabAt(tab?.position!!)?.customView as TextView

            updateText(textView, false)
        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (mLastPosition == tab!!.position) {
                return
            }
            var textView = tabLayout?.getTabAt(tab.position)?.customView as TextView

            updateText(textView, true)
            homeEvent!!.getConsultData(list!![tab.position], tab.position)
        }
    }

    fun updateText(txtView: TextView, isSelected: Boolean): TextView {
        if (!isSelected) {
            txtView.textSize = 12f
            txtView.setTextColor(Color.parseColor("#929292"))
            txtView.typeface = Typeface.DEFAULT
            txtView.setPadding(dp10, dp5, dp10, dp7)
        } else {
            txtView.textSize = 14f
            txtView.setTextColor(Color.parseColor("#5E5E5E"))
            txtView.typeface = Typeface.DEFAULT_BOLD
            txtView.setPadding(dp10, dp5, dp10, dp7)
        }
        return txtView
    }
}
