package com.yidianling.consultant

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.appbar.AppBarLayout
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.config.SimpleImageOpConfiger
import com.ydl.ydl_image.listener.YDLImageRecyclerOnScrollListener
import com.ydl.ydl_image.manager.YDLImageCacheManager
import com.ydl.ydlcommon.base.BaseMvpFragment
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.ui.LogoLoadingView
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.DisplayUtils
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.listener.EndlessRecyclerViewScrollListener
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.adapter.ExpertSearchAdapter
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.listener.OnCategoriesSelectedListener
import com.yidianling.consultant.listener.OnFilterConfirmListener
import com.yidianling.consultant.listener.OnSortItemSelectedListener
import com.yidianling.consultant.model.bean.*
import com.yidianling.consultant.modular.singlton.ConsultAssistantDialogUtils
import com.yidianling.consultant.router.ConsultantIn
import com.yidianling.consultant.ui.view.AreaPopupWindow
import com.yidianling.consultant.ui.view.CategoryPopupWindow
import com.yidianling.consultant.ui.view.FilterPopupWindow
import com.yidianling.consultant.ui.view.SortPopupWindow
import com.yidianling.consultant.ui.view.topView.RecommendListView
import kotlinx.android.synthetic.main.consultant_activity_expert_search_list.*
import kotlinx.android.synthetic.main.consultant_item_filter_online.view.*
import kotlinx.android.synthetic.main.consultant_layout_search_content.*
import kotlinx.android.synthetic.main.consultant_layout_search_toolbar.*
import org.json.JSONObject
import java.util.concurrent.Executors

@Route(path = "/consultant/consultant")
class ExpertSearchFragment : BaseMvpFragment<IExpertSearchView, ExpertSearchPresenter>(),
    View.OnClickListener, IExpertSearchView,
    OnCategoriesSelectedListener, OnSortItemSelectedListener, OnFilterConfirmListener,
    SwipeRefreshLayout.OnRefreshListener {
    private lateinit var mContext: Context
    private lateinit var mActivity: FragmentActivity
    var startTime =0L
    var endTime =0L

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

    override fun initDataAndEvent() {
        mContext = requireContext()
        mActivity = requireActivity()
        val statusBarHeight = StatusBarUtils.getStatusBarHeight(mContext)
        rootView.setPadding(0, statusBarHeight, 0, 0)
        btn_back.visibility = View.GONE
        title_layout.setPadding(DisplayUtils.dp2px(context, 15), 0, 0, 0)
        initViews()
        initData()

        val ffrom = PlatformDataManager.getRam().getChannelName()
        if (!TextUtils.isEmpty(ffrom) &&
            (ffrom.startsWith("ATK_android_yyjlcs"))
        ) {
            rl_hot_fix_for_huawei.visibility = View.GONE
        } else {
            rl_hot_fix_for_huawei.visibility = View.VISIBLE
        }

    }

    override fun initDataAndEventLazy() {

    }

    override fun showImage(url: String?, imgView: ImageView) {
        if (isAdded) {
            YDLImageCacheManager.showImage(activity, url, imgView)
        }
    }

    override fun showImage(url: String?, imgView: ImageView, ops: SimpleImageOpConfiger) {
        if (isAdded) {
            YDLImageCacheManager.showImage(activity, url, imgView, ops)
        }
    }

    override fun showImage(
        url: String?,
        imgView: ImageView,
        width: Int,
        heigh: Int,
        ops: SimpleImageOpConfiger
    ) {
        if (isAdded) {
            YDLImageCacheManager.showImage(activity, url, imgView, width, heigh, ops)
        }
    }
//
//    override fun getStatusViewOptions(): StatusBarOptions {
//        return StatusBarOptions(true,true)
//    }

    companion object {
        const val EXTRA_CATEGORY = "category"
        const val EXTRA_CATEGORY_NAME = "category_name"
        const val EXTRA_SHOW_TYPE = "showType"
        const val EXTRA_FROM_PAGE = "fromPage"
        const val HOT_SEARCH_DOCTOR_NAME = "hot_search_doctor_name"
        private const val EXTRA_IS_SHOW_HOT = "isInitShowHot"
        private const val EXTRA_SEARCH_WORD = "searchWord"
        private const val EXTRA_IS_FROM_SPLASH = "isFromSplash"
        private const val FILTER_STATUS_NORMAL = 0 //默认筛选状态
        private const val FILTER_STATUS_FILTERED = 1 //非默认筛选状态
        private const val FILTER_STATUS_OPEN = 2 //筛选窗打开状态
        const val FROM_HOME_SREARCH = 0
        const val FROM_FIND_EXPERT = 1
        const val FROM_ONLINE_EXPERT = 2
        const val PAGE_SIZE = 15
    }

    private val allFilter = AllFilter() //当前筛选
    private val tempFilter = AllFilter() //临时筛选，未确认状态
    private var curPage = 1
    private val doctorList = ArrayList<DoctorServiceItem>()
    private val serviceList = ArrayList<DoctorServiceItem>()
    private var hasMore = true
    private var initCategory = "0"
    private var initShowType: Int = 0
    private lateinit var doctorAdapter: ExpertSearchAdapter
    private lateinit var onScrollListener: EndlessRecyclerViewScrollListener
    private var headData: HeadData? = null //筛选数据
    private val props1 = JSONObject() //筛选标题埋点参数
    private var fromPageType: Int = 0 //从哪个页面跳转过来的
    private val fromPages = arrayOf("首页", "搜索页面", "在线专家")
    private var isRecommend = false //埋点数据
    private var keyWord: String? = null //埋点数据
    private var isDoSearch: Boolean = false //埋点判断是否通过搜索进入埋点的
    private val bannerList = ArrayList<String>()
    private var hasSelectedArea = false  //是否选择过地区
    private var hasSelectedSort = false  //是否选择过排序


    override fun createPresenter(): ExpertSearchPresenter = ExpertSearchPresenter()

    private fun initViews() {
        srlContainer.isEnabled = true
        tvSubject.setOnClickListener(this)
        tvArea.setOnClickListener(this)
        tvSort.setOnClickListener(this)
        tvFilter.setOnClickListener(this)
        btn_call.setOnClickListener(this)
        tv_guide.setOnClickListener(this)
        rl_search.setOnClickListener(this)
        srlContainer.setColorSchemeColors(
            ContextCompat.getColor(
                mActivity,
                R.color.platform_main_theme
            )
        )
        srlContainer.setProgressViewOffset(false, 0, 200)
        srlContainer.setOnRefreshListener(this)
        initNetLossView()

        recommendListView.addViewPagerScrollStateListener(object :
            RecommendListView.ViewPagerScrollStateCallback {
            override fun viewPagerScroll(isScrolling: Boolean) {
                //如果viewpager正在滚动，则禁止下拉刷新
                srlContainer.isEnabled = !isScrolling
            }
        })

        appbar_layout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, i ->
            srlContainer.isEnabled = i >= 0
        })


//        etSearch.setOnEditorActionListener { _, actionId, _ ->
//            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                doSearch()
//            }
//            true
//        }
//        etSearch.setOnClickListener { appbar_layout.setExpanded(false) }
//        etSearch.setOnFocusChangeListener { view, b -> if (b) appbar_layout.setExpanded(false) }
//        btn_back.setOnClickListener {
//            onBackPressed()
//        }
        doctorAdapter = ExpertSearchAdapter(mContext, this, doctorList)

        rvExperts.adapter = doctorAdapter
        val layoutManager = LinearLayoutManager(
            context,
            LinearLayoutManager.VERTICAL,
            false
        )
        rvExperts.layoutManager = layoutManager
        onScrollListener = object : EndlessRecyclerViewScrollListener(layoutManager) {
            private var isBtnShow: Boolean = false
            private var sIsScrolling = false
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                hideSoftInput()
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    sIsScrolling = true
                    //滚动
                    hideConsultAssistantDialog()

                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //没有滚动
                    showConsultAssistantDialog()
                    sIsScrolling = false
                }
            }

            override fun onScrollTop() {
                val alpha = PropertyValuesHolder.ofFloat("alpha", 1f, 0f)
                val scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f)
                val scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0f)
                val animator =
                    ObjectAnimator.ofPropertyValuesHolder(image_scroll_top, alpha, scaleX, scaleY)
                        .setDuration(200)
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        image_scroll_top.visibility = View.GONE
                        isBtnShow = false
                    }
                })
                animator.start()
            }

            override fun onScrollDown() {
                if (isBtnShow) {
                    return
                }
                val alpha = PropertyValuesHolder.ofFloat("alpha", 0f, 1f)
                val scaleX = PropertyValuesHolder.ofFloat("scaleX", 0f, 1f)
                val scaleY = PropertyValuesHolder.ofFloat("scaleY", 0f, 1f)
                val animator =
                    ObjectAnimator.ofPropertyValuesHolder(image_scroll_top, alpha, scaleX, scaleY)
                        .setDuration(200)
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        image_scroll_top.visibility = View.VISIBLE
                        isBtnShow = true
                    }
                })
                animator.start()
            }

            override fun onScrollUp() {
                if (!isBtnShow) {
                    return
                }
                val alpha = PropertyValuesHolder.ofFloat("alpha", 1f, 0f)
                val scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f)
                val scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0f)
                val animator =
                    ObjectAnimator.ofPropertyValuesHolder(image_scroll_top, alpha, scaleX, scaleY)
                        .setDuration(200)
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        image_scroll_top.visibility = View.GONE
                        isBtnShow = false
                    }
                })
                animator.start()
            }

            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                if (hasMore) {
                    curPage++
                    getPresenter().fetchListData(allFilter, curPage)
                }
            }
        }
//        rvExperts.addItemDecoration(ExpertItemDecoration(this))
        rvExperts.addOnScrollListener(onScrollListener)
        rvExperts.addOnScrollListener(YDLImageRecyclerOnScrollListener(activity))
//        etSearch.addTextChangedListener(object : TextWatcher {
//            override fun afterTextChanged(s: Editable?) {}
//
//            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
//
//            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//
//            }
//
//        })
        image_scroll_top.setOnClickListener(this)
//        initStatus()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isResumed) {
            startTime=System.currentTimeMillis()
            showConsultAssistantDialog()
        } else {
            hideConsultAssistantDialog()
            if (startTime!=0L){
                endTime=System.currentTimeMillis()
                ActionCountUtils.count(ConsultBIConstants.ConsultEvent.YDL_USER_CONSULT_PAGE_STAY_VISIT,(endTime-startTime).toString())
            }
                    }
        if (isVisibleToUser && isResumed) {
            onResume()
        }
    }

    private fun showConsultAssistantDialog() {
        ConsultAssistantDialogUtils.INSTANCE.fitRequest(mActivity, "doctor_list")
    }

    private fun hideConsultAssistantDialog() {
        ConsultAssistantDialogUtils.INSTANCE.hide()
    }

    private fun initNetLossView() {
        v_loading.setListener(object : LogoLoadingView.LogoLoadingListener {
            override fun onDataResetClick() {
                rvExperts.visibility = View.GONE
                v_loading.visibility = View.VISIBLE
                ll_network_error.visibility = View.GONE
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)
                refresh(false)
            }

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

    override fun localData() {
    }

    override fun updateCache(showType: Int, searchBean: ExpertSearchBean) {
    }

    private fun initData() {
        allFilter.showType.key = initShowType
        val cat = CateItem()
        cat.cateId = initCategory
        allFilter.categories.clear()
        allFilter.categories.add(cat)
        getPresenter().fetchListHead()
        //加载本地缓存数据
        getPresenter().localData(initShowType)
        //refresh(false)

        v_loading.visibility = View.VISIBLE
        v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null)

        doctorAdapter.setEntrance(0)
    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
            StatusBarUtils.setTransparentForImageView(mActivity, null)
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(mContext)

            val lp1 = title_layout.layoutParams as LinearLayout.LayoutParams
            lp1.height = (RxImageTool.dp2px(48f) + statusBarHeight)
            title_layout.setPadding(0, statusBarHeight, 0, 0)
        }
    }

    //筛选数据获取后回调
    override fun onHeadFetched(headData: HeadData?) {
        //头部数据获取到后初始化筛选数据
        this.headData = headData
        if (initCategory != "0") {
            if (headData?.cates != null) {
                for (cate in headData.cates) {
                    if (cate.cateId == initCategory) {
                        allFilter.categories.clear()
                        allFilter.categories.add(cate)
                        if (allFilter.categories.size == 1 && !"全部".equals(allFilter.categories[0].cateName)) {
                            //显示选中标题
                            tvSubject.text = allFilter.categories[0].cateName
                        } else {
                            //显示主标题
                            tvSubject.text = "主题"
                        }
                        updateFilterTextViewStatus(tvSubject, FILTER_STATUS_FILTERED)
                        break
                    }
                }
            }
            initCategory = "0"
        } else {
            allFilter.categories.clear()
            allFilter.categories.add(headData?.cates?.get(0) ?: CateItem())
        }
        allFilter.reorder = headData?.reorder?.get(0) ?: ReorderItem()
        allFilter.showType = headData?.filters?.showType?.get(initShowType) ?: ShowTypeItem()
        if (headData?.highlighter?.size ?: 0 > 0) {
            //设置热门搜索
            initHotViews(lin_filter2, headData!!.highlighter)
        }
    }

    /**
     * 热门
     */
    private fun initHotViews(view: LinearLayout, hotData: List<HighlighterItem>) {
        if (view.childCount > 0) {
            return
        }
        val popWidth = RxDeviceTool.getScreenWidth(context)
        val mWidth = (popWidth - RxImageTool.dp2px(10f)) / hotData.size
        for ((index, hot) in hotData!!.withIndex()) {
            val tv = View.inflate(context, R.layout.consultant_item_filter_online, null) as TextView
            val textView = tv.tvFree
            val params = LinearLayout.LayoutParams(0, RxImageTool.dp2px(22f))
            params.weight = 1f
            params.setMargins(0, 0, RxImageTool.dp2px(10f), 0)
            textView.layoutParams = params

            textView.text = hot.value
            textView.setOnClickListener {
                if (textView.isSelected) {
                    dealHotSelect(hot, false)
                    textView!!.isSelected = false
                    textView.paint.isFakeBoldText = false
                } else {
                    dealHotSelect(hot, true)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                }
                filterLabelSet()
                //开始筛选数据
                refresh()
            }
            view.addView(textView)
        }
    }


    /**
     * 处理热门搜索的选中逻辑
     * * 1：主题
     * 2：省
     * 3：排序
     * 4：咨询方式
     * 5：年龄选择
     * 6：其他选择
     * 7：资质选择
     * 8.市
     *
     * @param isAdd 是否是添加
     */
    private fun dealHotSelect(hotData: HighlighterItem, isAdd: Boolean) {
        when (hotData.type) {
            "1" -> {
                if (headData?.cates!!.size > 0) {
                    for (bean in headData?.cates!!) {
                        if (TextUtils.equals(hotData.id, bean.cateId.toString())) {
                            if (isAdd) {
                                if (allFilter.categories.size == 1 && allFilter.categories[0].cateId == "0") {
                                    allFilter.categories.clear()
                                }
                                allFilter.categories.add(bean)
                                updateFilterTextViewStatus(tvSubject, FILTER_STATUS_FILTERED)
                            } else {
                                allFilter.categories.remove(bean)
                                if (allFilter.categories.size == 0) {
                                    allFilter.categories.add(headData?.cates?.get(0) ?: CateItem())
                                    updateFilterTextViewStatus(tvSubject, FILTER_STATUS_NORMAL)
                                }
                            }
                        }
                    }
                    if (allFilter.categories.size == 1 && "全部" != allFilter.categories[0].cateName) {
                        //显示选中标题
                        tvSubject.text = allFilter.categories[0].cateName
                    } else {
                        //显示主标题
                        tvSubject.text = "主题"
                    }
                }
            }
            "2" -> {//省
                if (headData?.region!!.size > 0) {
                    val bean = RegionItem()
                    if (isAdd) {
                        //热门中如果选择过地区、要把其他已选中的置位未选中
                        if (hasSelectedArea) {
                            for ((index, bean) in headData!!.highlighter.withIndex()) {
                                if (bean.type == "2" || bean.type == "8") {
                                    val textview = lin_filter2.getChildAt(index) as TextView
                                    textview.isSelected = false
                                    textview.paint.isFakeBoldText = false
                                }
                            }
                        }
                        bean.code = hotData.id
                        bean.value = hotData.value
                        for (headBean in headData!!.region) {
                            if (TextUtils.equals(headBean.code, bean.code)) {
                                bean.sub = headBean.sub
                                break
                            }
                        }
                        allFilter.region = bean
                        if (allFilter.region.value?.length ?: 0 > 4) {
                            tvArea.text = allFilter.region.value?.substring(0, 3) + "..."
                        } else {
                            tvArea.text = allFilter.region.value
                        }
                        updateFilterTextViewStatus(tvArea, FILTER_STATUS_FILTERED)

                        hasSelectedArea = true
                    } else {
                        allFilter.region = RegionItem()
                        tvArea.text = "地区"
                        updateFilterTextViewStatus(tvArea, FILTER_STATUS_NORMAL)

                        hasSelectedArea = false
                    }
                    allFilter.sub = SubItem("不限", null)
                }
            }
            "3" -> {
                //排序
                if (headData?.reorder!!.size > 0) {
                    for (bean in headData?.reorder!!) {
                        if (TextUtils.equals(hotData.id, bean.key.toString())) {
                            if (isAdd) {
                                if (hasSelectedSort) {
                                    for ((index, bean) in headData!!.highlighter.withIndex()) {
                                        if (bean.type == "3") {
                                            var textview = lin_filter2.getChildAt(index) as TextView
                                            textview.isSelected = false
                                            textview.paint.isFakeBoldText = false
                                        }
                                    }
                                }
                                allFilter.reorder = bean
                                updateFilterTextViewStatus(tvSort, FILTER_STATUS_FILTERED)

                                hasSelectedSort = true
                            } else {
                                allFilter.reorder = headData?.reorder?.get(0) ?: ReorderItem()
                                updateFilterTextViewStatus(tvSort, FILTER_STATUS_NORMAL)

                                hasSelectedSort = false
                            }
                        }
                    }
                    when {
                        allFilter.reorder.value.equals("综合排序") -> tvSort.text = "排序"
                        allFilter.reorder.value?.length ?: 0 > 4 -> tvSort.text =
                            allFilter.reorder.value?.substring(0, 3) + "..."
                        else -> tvSort.text = allFilter.reorder.value
                    }
                }
            }
            "4" -> {
                //咨询方式
                if (headData?.filters?.enquiry!!.isNotEmpty()) {
                    for (bean in headData?.filters?.enquiry!!) {
                        if (TextUtils.equals(hotData.id, bean.key.toString())) {
                            if (isAdd) {
                                allFilter.enquiries.add(bean)
                            } else {
                                allFilter.enquiries.remove(bean)
                            }
                        }
                    }
                }
                if (allFilter.others.size + allFilter.enquiries.size + allFilter.ages.size+allFilter.doctorEdu.size + allFilter.title.size+allFilter.specialityCrowd.size > 0) {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
                }
                filterLabelSet()
            }
            "5" -> {
                //年龄选择
                if (headData?.filters?.age!!.isNotEmpty()) {
                    for (bean in headData?.filters?.age!!) {
                        if (TextUtils.equals(hotData.id, bean.key.toString())) {
                            if (isAdd) {
                                allFilter.ages.add(bean)
                            } else {
                                allFilter.ages.remove(bean)
                            }
                        }
                    }
                }
                if (allFilter.others.size + allFilter.enquiries.size + allFilter.ages.size + allFilter.title.size+allFilter.specialityCrowd.size > 0) {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
                }
                filterLabelSet()
            }
            "6" -> {
                //其他选择
                if (headData?.filters?.other!!.isNotEmpty()) {
                    for (bean in headData?.filters?.other!!) {
                        if (TextUtils.equals(hotData.id, bean.key.toString())) {
                            if (isAdd) {
                                allFilter.others.add(bean)
                            } else {
                                allFilter.others.remove(bean)
                            }
                        }
                    }
                }
                if (allFilter.others.size + allFilter.enquiries.size + allFilter.ages.size + allFilter.title.size+allFilter.specialityCrowd.size > 0) {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
                }
                filterLabelSet()
            }
            "7" -> {
                //资质选择
                if (headData?.filters?.title!!.isNotEmpty()) {
                    for (bean in headData?.filters?.title!!) {
                        if (TextUtils.equals(hotData.id, bean.key.toString())) {
                            if (isAdd) {
                                allFilter.title.add(bean)
                            } else {
                                allFilter.title.remove(bean)
                            }
                        }
                    }
                }
                if (allFilter.others.size + allFilter.enquiries.size + allFilter.ages.size + allFilter.title.size+allFilter.specialityCrowd.size > 0) {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
                }
                filterLabelSet()
            }
            "8" -> {
                //市
                if (headData?.region!!.size > 0) {
                    val bean = SubItem()
                    if (isAdd) {
                        //热门中如果选择过地区、要把其他已选中的置位未选中
                        if (hasSelectedArea) {
                            for ((index, bean) in headData!!.highlighter.withIndex()) {
                                if (bean.type == "2" || bean.type == "8") {
                                    val textview = lin_filter2.getChildAt(index) as TextView
                                    textview.isSelected = false
                                    textview.paint.isFakeBoldText = false
                                }
                            }
                        }

                        bean.code = hotData.id
                        bean.value = hotData.value
                        for (headBean in headData!!.region) {
                            if (TextUtils.equals(
                                    headBean.code!!.substring(0, 2),
                                    bean.code!!.substring(0, 2)
                                )
                            ) {
                                allFilter.region = headBean
                                break
                            }
                        }
                        allFilter.sub = bean
                        if (allFilter.sub.value?.length ?: 0 > 4) {
                            tvArea.text = allFilter.sub.value?.substring(0, 3) + "..."
                        } else {
                            tvArea.text = allFilter.sub.value
                        }
                        updateFilterTextViewStatus(tvArea, FILTER_STATUS_FILTERED)

                        hasSelectedArea = true
                    } else {
                        allFilter.region = RegionItem()
                        allFilter.sub = SubItem("不限", null)

                        tvArea.text = "地区"
                        updateFilterTextViewStatus(tvArea, FILTER_STATUS_NORMAL)

                        hasSelectedArea = false
                    }
                }
            }
        }
    }


    //用于侧滑筛选过来更新快捷筛选选中状态
    private fun updateOtherViews(otherdata: List<OtherItem>) {
        if (lin_filter2.childCount > 0) {
            //清空选中
            for (i in 0.until(lin_filter2.childCount)) {
                val textView = lin_filter2.getChildAt(i) as TextView
                textView.isSelected = false
                textView.paint.isFakeBoldText = false
            }
            //重置选中状态
            for ((index, other) in otherdata.withIndex()) {
                for (i in 0 until lin_filter2.childCount) {
                    val textView = lin_filter2.getChildAt(i) as TextView
                    if (textView.text == other.value) {
                        textView.isSelected = true
                        textView.paint.isFakeBoldText = true
                    }
                }
            }
        }
    }

    //服务列表数据获取到后的回调
    override fun onServiceListFetched(
        data: MutableList<DoctorServiceItem>,
        page: Int,
        totalPage: Int
    ) {
        LogUtil.d("onServiceListFetched")
//        if (rvExperts.adapter != serviceAdapter) {
//            rvExperts.adapter = serviceAdapter
//        }

        if (page == 1) {
            if (fromPageType != -1 && isDoSearch) {
//                LogUtil.d("keyword: " + keyWord + " isRecommend: " + isRecommend + " hasResult: " + (data.size > 0 && data != null ?: false) + " location: " + fromPages[fromPageType])
            }
            serviceList.clear()
            hasMore = true
//            serviceAdapter.hasMore = true
        }
        if (fromPageType == -1) {
            bury(keyWord ?: "", data.size > 0, isRecommend, "首页分类")
        } else {
            bury(keyWord ?: "", data.size > 0, isRecommend, fromPages[fromPageType])
        }

        if (page >= totalPage) {
            hasMore = false
//            serviceAdapter.hasMore = false
        }
        serviceList.addAll(data)
//        serviceAdapter.notifyDataSetChanged()
        isRecommend = false
        isDoSearch = false

        v_loading.visibility = View.GONE
        ll_network_error.visibility = View.GONE

        rvExperts.visibility = View.VISIBLE
        srlContainer.isRefreshing = false
    }

    //专家列表数据获取到后的回调
    override fun onDoctorListFetched(
        data: MutableList<DoctorServiceItem>,
        page: Int,
        totalPage: Int
    ) {
        LogUtil.d("onDoctorListFetched")
        if (rvExperts.adapter != doctorAdapter) {
            rvExperts.adapter = doctorAdapter
        }
        LogUtil.d("data size " + data.size)

        if (page == 1) {
            if (fromPageType != -1 && isDoSearch) {
//                LogUtil.d("keyword: " + keyWord + " isRecommend: " + isRecommend + " hasResult: " + (data.size > 0 && data != null ?: false) + " location: " + fromPages[fromPageType])
            }
            doctorList.clear()
            doctorAdapter.hasMore = true
            hasMore = true
        }
        if (fromPageType == -1) {
            bury(keyWord ?: "", data != null && data.size > 0, isRecommend, "首页分类")
        } else {
            bury(keyWord ?: "", data != null && data.size > 0, isRecommend, fromPages[fromPageType])
        }
        if (page >= totalPage) {
            hasMore = false
            doctorAdapter.hasMore = false
        }
        doctorList.addAll(data)
        //咨询师列表去除重复数据start
        var linkedHashSet=LinkedHashSet(doctorList)
        doctorList.clear()
        doctorList.addAll(linkedHashSet)
        //咨询师列表去除重复数据end
        doctorAdapter.notifyDataSetChanged()
        isDoSearch = false
        isRecommend = false

        v_loading.visibility = View.GONE
        ll_network_error.visibility = View.GONE

        rvExperts.visibility = View.VISIBLE
        srlContainer.isRefreshing = false
    }

    override fun fetchListFailed(msg: String?) {
        isDoSearch = false
        isRecommend = false

        if (curPage == 1) {
            v_loading.setViewType(
                LogoLoadingView.TYPE_NET_LOSS,
                getString(R.string.consultant_reload_hint)
            )
            v_loading.visibility = View.VISIBLE

            ll_network_error.visibility = View.GONE
        } else {
            ToastHelper.show("网络不给力")
        }
        srlContainer.isRefreshing = false
    }

    override fun fetchListEmpty(msg: String?) {
        isDoSearch = false
        isRecommend = false

        tv_reload.visibility = View.GONE
        tv_reload_hint.text = msg
        ll_network_error.visibility = View.VISIBLE
        iv_exception.setImageResource(R.drawable.platform_ico_img_zixun_empty)

        rvExperts.visibility = View.GONE
        srlContainer.isRefreshing = false
    }

    override fun fetchFailed(msg: String?) {
        isDoSearch = false
        isRecommend = false
        if (msg != null) {
            ToastUtil.toastShort(msg)
        }
        v_loading.setViewType(
            LogoLoadingView.TYPE_NET_LOSS,
            getString(R.string.consultant_reload_hint)
        )
        v_loading.visibility = View.VISIBLE

        ll_network_error.visibility = View.GONE

        rvExperts.visibility = View.GONE
        appbar_layout.setExpanded(false)
    }

    override fun showRefreshLayout() {
        srlContainer.isRefreshing = true
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.image_scroll_top -> {
                scrollToTop()
            }
            R.id.tvSubject -> {
                props1.put("filtrate_first", "主题")
                hideSoftInput()
                appbar_layout.setExpanded(false)
                appbar_layout.postDelayed({
                    showSubjectPopupWindow()
                }, 300);

            }
            R.id.tvArea -> {
                props1.put("filtrate_first", "地区")
                hideSoftInput()
                appbar_layout.setExpanded(false)
                appbar_layout.postDelayed({
                    showAreaPopupWindow()
                }, 300);

            }
            R.id.tvSort -> {
                props1.put("filtrate_first", "排序")
                hideSoftInput()
                appbar_layout.setExpanded(false)
                appbar_layout.postDelayed({
                    showSortPopupWindow()
                }, 300);

            }
            R.id.tvFilter -> {
                props1.put("filtrate_first", "筛选")
                hideSoftInput()
                appbar_layout.setExpanded(false)
                appbar_layout.postDelayed({
                    showFilterPopupWindow()
                }, 300);

            }
            R.id.tv_guide -> {
                ActionCountUtils.count(ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_CONSULT_GUIDE_CLICK)

                val h5param = H5Params(HttpConfig.H5_URL + "help/consultation/", "咨询指南")
                h5param.isShowMenu = true
                NewH5Activity.start(context, h5param)
            }
            R.id.btn_call -> {
                ActionCountUtils.count(ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_ONLINE_CUSTOMER_CLICK)

                ConsultantIn.startP2PXiaoYi(mContext)
            }
            R.id.rl_search -> {
                ARouter.getInstance()
                    .build("/consult/hot_search")
                    .withString(HOT_SEARCH_DOCTOR_NAME, tv_search_content.text.toString())
                    .navigation()
            }
        }
    }

    private fun scrollToTop() {
        if ((rvExperts.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition() > 10) {
            rvExperts.scrollToPosition(10)
            rvExperts.smoothScrollToPosition(0)
        } else {
            rvExperts.smoothScrollToPosition(0)
        }
    }

    //显示筛选弹窗
    private fun showFilterPopupWindow() {
//        tempFilter.searchWord = etSearch.text.toString()
        tempFilter.categories.clear()
        tempFilter.categories.addAll(allFilter.categories)
        tempFilter.reorder = allFilter.reorder
        tempFilter.region = allFilter.region
        tempFilter.sub = allFilter.sub

        tempFilter.showType = allFilter.showType
        tempFilter.ages.clear()
        tempFilter.ages.addAll(allFilter.ages)
        //学历
        tempFilter.doctorEdu.clear()
        tempFilter.doctorEdu.addAll(allFilter.doctorEdu)
        tempFilter.enquiries.clear()
        tempFilter.enquiries.addAll(allFilter.enquiries)
        // 擅长人群添加数据
        tempFilter.specialityCrowd.clear()
        tempFilter.specialityCrowd.addAll(allFilter.specialityCrowd)
        tempFilter.others.clear()
        tempFilter.others.addAll(allFilter.others)
        tempFilter.priceRanges = allFilter.priceRanges
        tempFilter.priceRangesView = allFilter.priceRangesView

        if (headData?.filters != null) {
            val filterPopupWindow = FilterPopupWindow(mContext, headData?.filters!!, tempFilter)
            filterPopupWindow.setOnDismissListener {
                viewDim.visibility = View.INVISIBLE
                viewDim_filter.visibility = View.GONE
                if (allFilter.others.size + allFilter.enquiries.size + allFilter.ages.size + allFilter.doctorEdu.size + allFilter.title.size+allFilter.specialityCrowd.size > 0 || !TextUtils.isEmpty(
                        allFilter.priceRanges?.minPrice
                    ) || !TextUtils.isEmpty(allFilter.priceRanges?.maxPrice)
                ) {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
                }
                showConsultAssistantDialog()
            }
            filterPopupWindow.isClippingEnabled = false
            filterPopupWindow.showAsDropDown(viewSep2)
            hideConsultAssistantDialog()
            filterPopupWindow.onFilterConfirmListener = this
            updateFilterTextViewStatus(tvFilter, FILTER_STATUS_OPEN)
            viewDim.visibility = View.VISIBLE
        } else {
            ToastUtil.toastShort("数据初始化失败，请重试")
            getPresenter().fetchListHead()
        }
    }

    //筛选确认回调
    override fun onFilterConfirmed() {
        updateFilterTextViewStatus(tvFilter, FILTER_STATUS_OPEN)
        LogUtil.d(
            "filter: " + tempFilter.showType.value + "," + tempFilter.enquiries.map { it.value }
                .joinToString(
                    ","
                ) + "," + tempFilter.ages.map { it.value }
                .joinToString(",") + "," + tempFilter.others.map { it.value }.joinToString(
                ","
            )
        )
        props1.put(
            "filtrate_second",
            tempFilter.showType.value + ","
                    + tempFilter.enquiries.map { it.value }.joinToString(",") + ","
                    + tempFilter.ages.map { it.value }.joinToString(",") + ","
                    + tempFilter.doctorEdu.map { it.value }.joinToString(",") + ","
                    + tempFilter.others.map { it.value }.joinToString(",")
        )
        BuryPointUtils.buryPoint("Filtrate", props1)


        allFilter.showType = tempFilter.showType
        allFilter.enquiries.clear()
        allFilter.enquiries.addAll(tempFilter.enquiries)
        allFilter.ages.clear()
        allFilter.ages.addAll(tempFilter.ages)
        allFilter.doctorEdu.clear()
        allFilter.doctorEdu.addAll(tempFilter.doctorEdu)
        // 擅长人群
        allFilter.specialityCrowd.clear()
        allFilter.specialityCrowd.addAll(tempFilter.specialityCrowd)
        // 其它
        allFilter.others.clear()
        allFilter.others.addAll(tempFilter.others)
        allFilter.title.clear()
        allFilter.title.addAll(tempFilter.title)
        allFilter.priceRanges = tempFilter.priceRanges
        allFilter.priceRangesView = tempFilter.priceRangesView

        //判断主题选中，判断热门筛选中是否也有该主题
        Executors.newCachedThreadPool().execute {
            if (headData!!.highlighter.size > 0) {
                for (index in 0.until(headData!!.highlighter.size)) {
                    if (headData!!.highlighter[index].type == "4") {
                        val textview = lin_filter2.getChildAt(index) as TextView
                        mActivity.runOnUiThread {
                            textview.isSelected = false
                            textview.paint.isFakeBoldText = false
                        }
                        for (bean in allFilter.enquiries) {
                            if (TextUtils.equals(
                                    bean.key.toString(),
                                    headData!!.highlighter[index].id
                                )
                            ) {
                                mActivity.runOnUiThread {
                                    textview.isSelected = true
                                    textview.paint.isFakeBoldText = true
                                }
                                break
                            }
                        }
                    }
                    if (headData!!.highlighter[index].type == "5") {
                        val textview = lin_filter2.getChildAt(index) as TextView
                        mActivity.runOnUiThread {
                            textview.isSelected = false
                            textview.paint.isFakeBoldText = false
                        }
                        for (bean in allFilter.ages) {
                            if (TextUtils.equals(
                                    bean.value.toString(),
                                    headData!!.highlighter[index].id
                                )
                            ) {
                                mActivity.runOnUiThread {
                                    textview.isSelected = true
                                    textview.paint.isFakeBoldText = true
                                }
                                break
                            }
                        }
                    }
                    if (headData!!.highlighter[index].type == "6") {
                        val textview = lin_filter2.getChildAt(index) as TextView
                        mActivity.runOnUiThread {
                            textview.isSelected = false
                            textview.paint.isFakeBoldText = false
                        }
                        for (bean in allFilter.others) {
                            if (TextUtils.equals(
                                    bean.key.toString(),
                                    headData!!.highlighter[index].id
                                )
                            ) {
                                mActivity.runOnUiThread {
                                    textview.isSelected = true
                                    textview.paint.isFakeBoldText = true
                                }
                                break
                            }
                        }
                    }

                    if (headData!!.highlighter[index].type == "7") {
                        val textview = lin_filter2.getChildAt(index) as TextView
                        mActivity.runOnUiThread {
                            textview.isSelected = false
                            textview.paint.isFakeBoldText = false
                        }
                        for (bean in allFilter.title) {
                            if (TextUtils.equals(
                                    bean.key.toString(),
                                    headData!!.highlighter[index].id
                                )
                            ) {
                                mActivity.runOnUiThread {
                                    textview.isSelected = true
                                    textview.paint.isFakeBoldText = true
                                }
                                break
                            }
                        }
                    }
                }
            }
        }

        filterLabelSet()
        //刷新快捷按钮选中状态
        updateOtherViews(allFilter.others)
        refresh()
    }

    //筛选标题显示处理
    private fun filterLabelSet() {
        if ((allFilter.others.size + allFilter.ages.size + allFilter.doctorEdu.size + allFilter.enquiries.size + allFilter.title.size+allFilter.specialityCrowd.size) == 1) {
            var text: String? = ""
            when {
                allFilter.others.size == 1 -> {
                    text = allFilter.others[0].value
                }
                allFilter.ages.size == 1 -> {
                    text = allFilter.ages[0].value
                }
                allFilter.enquiries.size == 1 -> {
                    text = allFilter.enquiries[0].value
                }
                allFilter.title.size == 1 -> {
                    text = allFilter.title[0].value
                }
                allFilter.specialityCrowd.size==1 -> {
                    text = allFilter.specialityCrowd[0].value
                }
                allFilter.doctorEdu.size==1 -> {
                    text = allFilter.doctorEdu[0].value
                }
                else -> {
                    text = "筛选"
                }
            }
            if (text?.length ?: 0 > 4) {
                tvFilter.text = text?.substring(0, 3) + "..."
            } else {
                tvFilter.text = text
            }
        } else {
            tvFilter.text = "筛选"
        }
    }


    private var sortPopup: SortPopupWindow? = null

    //显示排序弹窗
    private fun showSortPopupWindow() {
        if (headData?.reorder != null) {
            sortPopup = SortPopupWindow(mActivity, headData?.reorder!!, allFilter.reorder, this)
            sortPopup!!.setOnDismissListener {
                viewDim.visibility = View.INVISIBLE
                if (allFilter.reorder != headData!!.reorder[0]) {
                    updateFilterTextViewStatus(tvSort, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvSort, FILTER_STATUS_NORMAL)
                }
            }
            if (sortPopup!!.selectedSort != allFilter.reorder) {
                sortPopup!!.selectedSort = allFilter.reorder
                sortPopup!!.notifyDataSetChanged()
            }
            sortPopup!!.showAsDropDown(viewSep2)
            updateFilterTextViewStatus(tvSort, FILTER_STATUS_OPEN)
            viewDim.visibility = View.VISIBLE
        } else {
            ToastUtil.toastShort("数据初始化失败，请重试")
            getPresenter().fetchListHead()
        }
    }

    //排序选择回调
    override fun onSortItemSelected(sortItem: ReorderItem) {
        ActionCountUtils.count(
            ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_SORT_CLICK, sortItem.value
                ?: ""
        )

        if (sortItem.value.equals("综合排序")) {
            tvSort.text = "排序"
        } else if (sortItem.value?.length ?: 0 > 4) {
            tvSort.text = sortItem.value?.substring(0, 3) + "..."
        } else {
            tvSort.text = sortItem.value
        }

        //判断排序选中，判断热门筛选中是否也有该排序
        if (headData!!.highlighter.size > 0) {
            for (index in 0.until(headData!!.highlighter.size)) {
                if (headData!!.highlighter[index].type == "3") {
                    var textview = lin_filter2.getChildAt(index) as TextView
                    if (TextUtils.equals(sortItem.value, headData!!.highlighter[index].value)) {
                        textview.isSelected = true
                        textview.paint.isFakeBoldText = true

                        hasSelectedSort = true
                    } else {
                        textview.isSelected = false
                        textview.paint.isFakeBoldText = false
                    }
                }
            }
        }

        updateFilterTextViewStatus(tvSort, FILTER_STATUS_OPEN)
        LogUtil.d("sortItem key: " + sortItem.key + " sortItem value: " + sortItem.value)
        props1.put("filtrate_second", sortItem.value)
        BuryPointUtils.buryPoint("Filtrate", props1)
        allFilter.reorder = sortItem
        sortPopup?.dismiss()
        refresh()
    }

    //显示地区弹窗
    private fun showAreaPopupWindow() {
        if (headData?.region != null) {
            val regionPopupWindow = AreaPopupWindow(mActivity, headData?.region ?: ArrayList(), allFilter.region, allFilter.sub)
            regionPopupWindow.showAsDropDown(viewSep2)
            viewDim.visibility = View.VISIBLE
            updateFilterTextViewStatus(tvArea, FILTER_STATUS_OPEN)
            regionPopupWindow.setOnDismissListener {
                viewDim.visibility = View.INVISIBLE
                if (tvArea.text != "地区") {
                    updateFilterTextViewStatus(tvArea, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvArea, FILTER_STATUS_NORMAL)
                }
            }
            regionPopupWindow.onRegionSelectedListener =
                object : AreaPopupWindow.OnRegionSelectedListener {
                    override fun onRegionSelected(region: RegionItem, sub: SubItem) {
                        updateFilterTextViewStatus(tvArea, FILTER_STATUS_OPEN)
                        allFilter.region = region
                        allFilter.sub = sub
                        if ( TextUtils.isEmpty(region.code) && TextUtils.isEmpty(sub.code)) {
                            tvArea.text = "地区"
                        } else if (!TextUtils.isEmpty(region.code) && !TextUtils.isEmpty(sub.code)) {
                            if (region.value?.length ?: 0 > 4) {
                                tvArea.text = region.value?.substring(0, 3) + "..."
                            } else {
                                tvArea.text = region.value
                            }
                        } else {
                            if (sub.value?.length ?: 0 > 4) {
                                tvArea.text = sub.value?.substring(0, 3) + "..."
                            } else {
                                tvArea.text = sub.value
                            }
                        }
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_AREA_CLICK,
                            region.value + "|" + sub.value
                        )

                        //更新热门搜索显示状态
                        if (headData!!.highlighter.size > 0) {
                            for ((index, hot) in headData!!.highlighter.withIndex()) {
                                if (hot.type == "2" || hot.type == "8") {
                                    val textview = lin_filter2.getChildAt(index) as TextView
                                    //有选择城市
                                    if (!TextUtils.isEmpty(sub.code)) {
                                        if (TextUtils.equals(sub.code, hot.id)) {
                                            textview.isSelected = true
                                            textview.paint.isFakeBoldText = true
                                            hasSelectedArea = true
                                        } else {
                                            textview.isSelected = false
                                            textview.paint.isFakeBoldText = false
                                        }
                                    } else {
                                        if (TextUtils.equals(region.code, hot.id)) {
                                            textview.isSelected = true
                                            textview.paint.isFakeBoldText = true
                                            hasSelectedArea = true
                                        } else {
                                            textview.isSelected = false
                                            textview.paint.isFakeBoldText = false
                                        }
                                    }
                                }
                            }
                        }
                        regionPopupWindow.dismiss()
                        refresh()
                    }
                }
        } else {
            ToastUtil.toastShort("数据初始化失败，请重试")
            getPresenter().fetchListHead()
        }
    }

    private var categoryPopup: CategoryPopupWindow? = null

    //显示主题弹窗
    private fun showSubjectPopupWindow() {
        tempFilter.categories.clear()
        tempFilter.categories.addAll(allFilter.categories)
        val categories = headData?.cates
        if (categories != null) {
            categoryPopup = CategoryPopupWindow(mActivity, categories, tempFilter.categories)
            categoryPopup!!.setOnDismissListener {
                viewDim.visibility = View.INVISIBLE
                if (allFilter.categories.size > 1 || (allFilter.categories.size == 1 && allFilter.categories[0] != headData!!.cates[0])) {
                    updateFilterTextViewStatus(tvSubject, FILTER_STATUS_FILTERED)
                } else {
                    updateFilterTextViewStatus(tvSubject, FILTER_STATUS_NORMAL)
                }
            }
            categoryPopup!!.onSubjectsSelectedListener = this
            categoryPopup!!.showAsDropDown(viewSep2)
            updateFilterTextViewStatus(tvSubject, FILTER_STATUS_OPEN)
            viewDim.visibility = View.VISIBLE
        } else {
            ToastUtil.toastShort("数据初始化失败，请重试")
            getPresenter().fetchListHead()
        }
    }

    /**
     * 主题选择确认回调
     *
     * 新增逻辑：当主题选择后，需要判断热门筛选中是否也有该主题，如果有，也需要同步更新选中状态
     */
    override fun onCategoriesSelected(categories: ArrayList<CateItem>) {
        ActionCountUtils.count(
            ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_THEME_CLICK,
            categories.map { it.cateName }.joinToString("|")
        )
        if (categories.size == 1 && "全部" != categories[0].cateName) {
            //显示选中标题
            tvSubject.text = categories[0].cateName
        } else {
            //显示主标题
            tvSubject.text = "主题"
        }
        //如果是亲自教育类别----->点击咨询顾问---会跳转到一个只是亲自教育的导医队列中


        //判断主题选中，判断热门筛选中是否也有该主题
        Executors.newCachedThreadPool().execute {
            if (headData!!.highlighter.size > 0) {
                for (index in 0.until(headData!!.highlighter.size)) {
                    if (headData!!.highlighter[index].type == "1") {
                        val textview = lin_filter2.getChildAt(index) as TextView
                        mActivity.runOnUiThread {
                            textview.isSelected = false
                            textview.paint.isFakeBoldText = false
                        }
                        for (bean in categories) {
                            if (TextUtils.equals(
                                    bean.cateName,
                                    headData!!.highlighter[index].value
                                )
                            ) {
                                mActivity.runOnUiThread {
                                    textview.isSelected = true
                                    textview.paint.isFakeBoldText = true
                                }
                                break
                            }
                        }
                    }
                }
            }
        }

        updateFilterTextViewStatus(tvSubject, FILTER_STATUS_OPEN)
//        LogUtil.d("theme callback: " + categories.map { it.cateName }.joinToString(","))
//        props1.put("filtrate_second", categories.map { it.cateName }.joinToString(","))
//        BuryPointUtils.buryPoint("Filtrate", props1)
        allFilter.categories.clear()
        allFilter.categories.addAll(categories)
        refresh()
        if (categories.size == 1) {
            doctorAdapter.cateId = "${categories[0].cateId}"
        } else {
            doctorAdapter.cateId = ""
        }
    }

    override fun onRefresh() {
        refresh(false)
        recommendListView.requestData()

    }

    //刷新列表
    private fun refresh(isShowRefresh: Boolean? = true) {
        srlContainer.isRefreshing = isShowRefresh!!
        val key = tv_search_content.text.toString()
        if (!TextUtils.isEmpty(key.trim())) {
            allFilter.searchWord = key.trim()
        } else {
            allFilter.searchWord = null
        }
        curPage = 1
        onScrollListener.resetState()
        getPresenter().fetchListData(allFilter, curPage)
        rvExperts.scrollToPosition(0)
    }

    //执行搜索
    private fun doSearch() {
        image_scroll_top.visibility = View.GONE
        hideSoftInput();
//        keyWord = etSearch.text.toString()
//        if (TextUtils.isEmpty(keyWord?.trim())) {
//            ToastUtil.toastShort(this, "请输入搜索内容")
//            return
//        }

        ActionCountUtils.count(
            ConsultBIConstants.UserMainEvent.YDL_USER_SEARCH_CLICK,
            keyWord ?: ""
        )
        isDoSearch = true
        resetFilter()
        refresh()

    }

    //重置所有筛选
    private fun resetFilter() {
        allFilter.categories.clear()
        allFilter.categories.add(headData?.cates?.get(0) ?: CateItem())
        allFilter.reorder = headData?.reorder?.get(0) ?: ReorderItem()
        allFilter.region = RegionItem()
        allFilter.sub = SubItem()
        allFilter.enquiries.clear()
        allFilter.ages.clear()
        allFilter.others.clear()
        updateFilterTextViewStatus(tvSubject, FILTER_STATUS_NORMAL)
        updateFilterTextViewStatus(tvArea, FILTER_STATUS_NORMAL)
        updateFilterTextViewStatus(tvSort, FILTER_STATUS_NORMAL)

        if (headData != null) {
            if (allFilter.showType != headData!!.filters.showType[1]) {
                updateFilterTextViewStatus(tvFilter, FILTER_STATUS_FILTERED)
            } else {
                updateFilterTextViewStatus(tvFilter, FILTER_STATUS_NORMAL)
            }
        }
    }

    //设置筛选点击按钮状态
    private fun updateFilterTextViewStatus(tv: TextView, status: Int) {
        when (status) {
            FILTER_STATUS_NORMAL -> {
                tv.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.platform_colorTextDefault))
                tv.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_ic_arrow_drop_down_grey_500_18dp,
                    0
                )
            }
            FILTER_STATUS_FILTERED -> {
                tv.typeface = Typeface.DEFAULT_BOLD
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.platform_main_theme))
                tv.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_ic_arrow_drop_down_grey_500_18dp,
                    0
                )
            }
            FILTER_STATUS_OPEN -> {
                tv.typeface = Typeface.DEFAULT_BOLD
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.platform_colorTextDefault))
                tv.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.platform_arrow_drop_down_en,
                    0
                )
            }
        }
    }

    private fun hideSoftInput() {
        val view = mActivity.currentFocus
        if (view != null) {
            val imm = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    /**
     * 事件埋点
     */
    fun bury(keyworks: String, isResult: Boolean, isRecommend: Boolean, location: String) {
        BuryPointUtils.getInstance().createMap()
            .put("keyWord", keyworks)
            .put("hasResult", isResult)
            .put("isRecommend", isRecommend)
            .put("location", location)
            .burryPoint("search")
    }

    override fun onResume() {
        super.onResume()
        refresh(false)
        ActionCountUtils.count(ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_PAGE_VISIT)
        ActionCountUtils.count("daoyi_advertisement_page|daoyi_advertisement_visit","6")
    }

    override fun onDestroy() {
        super.onDestroy()
        ConsultAssistantDialogUtils.INSTANCE.resetStatus()
    }
}
