package com.yidianling.home.ui.view

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import com.google.android.material.tabs.TabLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.text.Layout
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
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_confide_view.view.*
import java.lang.Exception
import kotlin.math.ceil

/**
 * @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_confide_view, this)
        homeModuleConfideViewHomeCommonTitleView.setTitle("心理咨询")
        homeModuleConfideViewHomeCommonTitleView.setMoreText("更多咨询")
        homeModuleConfideViewHomeCommonTitleView.setTopMargin(-4)
        homeModuleConfideViewHomeCommonTitleView.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
            if (textView != null && textView is TextView) {

                updateText(textView, true)
            }
        } catch (e: Exception) {}
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            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 0 until list!!.size) {
                //设置数据
                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 0 until list!!.size) {
                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

            if (textView != null && textView is TextView) {
                updateText(textView, false)
            }
        }

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

            if (textView != null && textView is 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("#999999"))
            txtView.setPadding(dp10, dp5, dp10, dp7)
            txtView.setBackgroundResource(R.drawable.home_consult_tab_item_unselected_bg)
        } else {
            txtView.textSize = 12f
            txtView.setTextColor(Color.parseColor("#FD9B0A"))
            txtView.setPadding(dp10, dp5, dp10, dp7)
            txtView.setBackgroundResource(R.drawable.home_consult_tab_item_selected_bg)

        }
        return txtView
    }
}
