package com.yidianling.consultant

import android.content.Context
import android.graphics.Rect
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.*
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.banner.GlideImageLoader
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.consultant.adapter.SearchWordsAdapter
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.consultant.bean.*
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.SEARCH_BANNERWORD_CLICK
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.YDL_USER_CONSULT_SEARCH_CONFIRM_CLICK
import com.yidianling.consultant.contract.IHotSearchContract
import com.yidianling.consultant.model.bean.FunctionWordBean
import com.yidianling.consultant.modular.utils.ConsultAssistantEntryUtils
import com.yidianling.consultant.modular.utils.TempH5RouteUtils
import com.yidianling.consultant.presenter.HotSearchPresenterImpl
import kotlinx.android.synthetic.main.consultant_activity_hot_search.*
import kotlinx.android.synthetic.main.consultant_item_expert_hot_search.view.*

@Route(path = "/consult/hot_search")
class HotSearchActivity : BaseMvpActivity<IHotSearchContract.View, IHotSearchContract.Presenter>(),
    IHotSearchContract.View {

    private lateinit var searchWordsAdapter: SearchWordsAdapter
    private val searchSuggestList: ArrayList<SearchSuggestListBean> = ArrayList()
    private var mSearchContent: String = ""

    private var historyList: FixSizeLinkedList<String> = FixSizeLinkedList(15)
    private val bannerList = ArrayList<String>()

    private var lenovoResultSuccess = false     // 联想结果 联想前false 联想成功后true

    companion object {
        private const val CACHE_CONSULT_SEARCH_HISTORY_DATA = "cache_consult_search_history_data"
        private const val HOT_SEARCH_DOCTOR_NAME = "hot_search_doctor_name"
        private const val JUMP_WORD = "jump_word"
    }

    //历史搜索内容的最大宽度
    private var maxWidth: Int = 0

    //历史搜索实际宽度
    private var historyCurrentWidth: Int = 0

    //热门专家搜索实际宽度
    private var expertWidth: Int = 0

    private var dp42: Int = 0


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

    override fun createPresenter(): IHotSearchContract.Presenter {
        return HotSearchPresenterImpl()
    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true)
    }

    override fun initDataAndEvent() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        getDataFromIntent()
        initViews()
        initData()
    }

    private fun getDataFromIntent() {
        val doctorName = intent.getStringExtra(HOT_SEARCH_DOCTOR_NAME)
        if (!TextUtils.isEmpty(doctorName)) {
            etSearch.hint = doctorName
            iv_delete_icon.visibility = View.VISIBLE
        }
    }

    private fun initViews() {
        StatusBarUtils.statusBarLightMode(this)
        maxWidth =
            (2 * RxDeviceTool.getScreenWidth(this@HotSearchActivity)) - RxImageTool.dip2px(60f)
        dp42 = RxImageTool.dip2px(60f)

        iv_delete_icon.setOnClickListener {
            etSearch.setText("")
        }
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //埋点
                ActionCountUtils.count(
                    YDL_USER_CONSULT_SEARCH_CONFIRM_CLICK,
                    etSearch.text.toString(),
                    etSearch.hint.toString()
                )
                // 搜索的关联词
                var relatedWords = ""
                var isRecommendWords = false
                if (!lenovoResultSuccess && !etSearch.text.toString()
                        .isNullOrEmpty()
                ) {   // 如果每次输入内容后联想词结果还没返回结果则直接进行搜索
                    doSearch(etSearch.text.toString(), relatedWords, isRecommendWords)
                } else if (searchSuggestList.isNotEmpty() && searchSuggestList.size > 0) {
                    if (searchSuggestList[0].suggest_relations.size > 0) {
                        relatedWords = searchSuggestList[0].suggest_relations[0]
                        isRecommendWords = true
                    }
                    if (TextUtils.isEmpty(relatedWords) && !TextUtils.isEmpty(searchSuggestList[0].suggest_content)) {
                        relatedWords = searchSuggestList[0].suggest_content
                    }

                    if (searchSuggestList[0].suggest_types.contains(JUMP_WORD)) {
                        NewH5Activity.start(this, H5Params(searchSuggestList[0].jump_url!!, null))
                    } else {
                        if (etSearch.text.toString().isNullOrEmpty()) {
                            doSearch(etSearch.hint.toString(), relatedWords, isRecommendWords)
                        } else {
                            doSearch(etSearch.text.toString(), relatedWords, isRecommendWords)
                        }
                    }
                } else {
                    val searchWords = etSearch.text.toString()
                    if (TextUtils.isEmpty(searchWords)) {
                        getSearchWords(etSearch.hint.toString(), true)
                    } else {
                        getSearchWords(etSearch.text.toString(), true)
                    }
                }
            }
            true
        }
        tv_search_cancle.setOnClickListener {
            finish()
        }
        iv_delete_history.setOnClickListener {
            SharedPreferencesEditor.putString(CACHE_CONSULT_SEARCH_HISTORY_DATA, "")
            initHistoryData()
        }

        val data = ModularServiceManager.provide(IConsultantService::class.java).getGuideImage(5)
        if (data?.size ?: 0 > 0) {
            val imageUrl = data?.get(0)?.pic
            iv_daoyi_image.visibility = View.VISIBLE

            GlideApp.with(mContext)
                .load(imageUrl)
                .into(iv_daoyi_image)

            iv_daoyi_image.setOnClickListener {
                LogUtil.e("跳转导医:location=${data?.get(0)!!.location},title=${data[0].title}")
                ConsultAssistantEntryUtils.jumpConsultAssistant(
                    this,
                    data[0].location.toInt(),
                    "learning"
                )
            }
        }

        searchWordsAdapter = SearchWordsAdapter(searchSuggestList)
        rv_search_words.layoutManager = LinearLayoutManager(this)
        rv_search_words.adapter = searchWordsAdapter
        searchWordsAdapter.setOnItemClickListener { adapter, view, position ->
            // 搜索的关联词
            var relatedWords = ""
            var isRecommendWords = false
            if (searchSuggestList.isNotEmpty() && searchSuggestList.size > 0) {
                if (searchSuggestList[position].suggest_relations.size > 0) {
                    relatedWords = searchSuggestList[position].suggest_relations[0]
                    isRecommendWords = true
                }
                if (TextUtils.isEmpty(relatedWords) && !TextUtils.isEmpty(searchSuggestList[position].suggest_content)) {
                    relatedWords = searchSuggestList[position].suggest_content
                }
            }
            if (searchSuggestList[position].suggest_types.contains(JUMP_WORD)) {
                NewH5Activity.start(this, H5Params(searchSuggestList[position].jump_url!!, null))
            } else {
                doSearch(
                    searchSuggestList[position].suggest_content,
                    relatedWords,
                    isRecommendWords
                )
            }

            // 埋点
            ActionCountUtils.baiDuCountSign3(
                ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                ConsultBIConstants.POSITION_YDL_USER_ASSOCIATE_WORD_CLICK,
                etSearch.text.toString(),
                searchSuggestList[position].suggest_content,
                "app"
            )
        }
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    iv_delete_icon.visibility = View.INVISIBLE
                    rv_search_words.visibility = View.GONE
                    getSearchWords("", false)
                } else {
                    iv_delete_icon.visibility = View.VISIBLE
                    getSearchWords(s.toString(), false)
                }

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
    }


    /**
     * 获取搜索联想词
     * @param isClickWords 是否是点击历史搜索、热门搜索等进行搜索
     */
    private fun getSearchWords(searchContent: String, isClickWords: Boolean) {
        if (!TextUtils.isEmpty(searchContent)) {
            lenovoResultSuccess = false
            mSearchContent = searchContent
            val map = HashMap<String, Any>()
            map["content"] = searchContent
            mPresenter.getSearchWords(map, searchContent, isClickWords)
        } else {
            rv_search_words.visibility = View.GONE
        }
    }

    override fun getSearchWordsSuccess(
        searchWordsBean: SearchWordsBean,
        searchContent: String,
        isClickWords: Boolean
    ) {
        lenovoResultSuccess = true
        if (isClickWords) {
            //判断 suggest_classify_types 有值则通过 jump_url跳转
            // 搜索的关联词
            var relatedWords = ""
            var isRecommendWords = false
            if (!searchWordsBean.search_suggests.isNullOrEmpty() && searchWordsBean.search_suggests.size > 0) {
                if (searchWordsBean.search_suggests[0].suggest_relations.size > 0) {
                    relatedWords = searchWordsBean.search_suggests[0].suggest_relations[0]
                    isRecommendWords = true
                }
                if (TextUtils.isEmpty(relatedWords) && !TextUtils.isEmpty(searchWordsBean.search_suggests[0].suggest_content)) {
                    relatedWords = searchWordsBean.search_suggests[0].suggest_content
                }
            }
            if (!searchWordsBean.search_suggests.isNullOrEmpty() && searchWordsBean.search_suggests.get(
                    0
                ).suggest_types.contains(JUMP_WORD)
            ) {
                //将数据增加到历史搜索中
                if (!TextUtils.isEmpty(searchContent)) {
                    historyList.remove(searchContent)
                    historyList.add(searchContent)
                    SharedPreferencesEditor.putString(
                        CACHE_CONSULT_SEARCH_HISTORY_DATA,
                        Gson().toJson(historyList)
                    )
                }
                NewH5Activity.start(
                    this,
                    H5Params(searchWordsBean.search_suggests[0].jump_url!!, null)
                )
                finish()
            } else {
                doSearch(searchContent, relatedWords, isRecommendWords)
            }
        } else {
            searchSuggestList.clear()
            if (!searchWordsBean.search_suggests.isNullOrEmpty()) {
                rv_search_words.visibility = View.VISIBLE
                searchSuggestList.addAll(searchWordsBean.search_suggests)
                searchWordsAdapter.notifyDataAndSetSearchWord(mSearchContent)

                // 埋点
                val sign2 = searchSuggestList.joinToString(",") { it.suggest_content }
                ActionCountUtils.baiDuCountSign3(
                    ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                    ConsultBIConstants.POSITION_YDL_USER_ASSOCIATE_WORD_VISIT,
                    searchContent,
                    sign2,
                    "app"
                )
            } else {
                rv_search_words.visibility = View.GONE
            }
        }
    }

    private fun initData() {
        initHistoryData()
        mPresenter.localData(this)
        val mapType = HashMap<String, Any>()
        mapType["type"] = 1
        mPresenter.searchHotWordData(mapType)
        if (etSearch.requestFocus()) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val isShowing = imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT)
            if (!isShowing) {
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
            }
        }
    }

    override fun searchDataResponse(hotSearchBean: HotSearchBean) {
        //刷新 热门搜索
        refreshHotSearchData(hotSearchBean.keywordData)
        //刷新 本周热门专家
        refreshHotExpertData(hotSearchBean.popularDoctors)
        //刷新 banner
        refreshBanner(hotSearchBean.focusList)
    }

    override fun searchHotWordData(wordList: MutableList<FunctionWordBean>) {
        //热门词搜索结果
        if (wordList.isEmpty()) {
            llHotSearch.visibility = View.GONE
            return
        }
        llHotSearch.visibility = View.VISIBLE
        flHotSearch.removeAllViews()
        for (index in wordList.indices) {
            val view = LayoutInflater.from(this)
                .inflate(R.layout.consultant_item_expert_hot_search, flHotSearch, false)
            view.tvHotSearch.text = wordList[index].word
            view.setOnClickListener {
                ActionCountUtils.count(SEARCH_BANNERWORD_CLICK, wordList[index].word!!, "热门搜索")
                getSearchWords(wordList[index].word!!, true)
            }
            flHotSearch.addView(view)
        }
    }

    override fun requestFail() {
        refreshBanner(null)
    }


    //刷新 热门搜索
    private fun refreshHotSearchData(keywordData: MutableList<HotSearchKeyWordDataBean>?) {
        //旧的热门搜索
    }

    //刷新 本周热门专家
    private fun refreshHotExpertData(hotSearchExpert: MutableList<HotSearchPopularDoctorBean>?) {
        if (null == hotSearchExpert || hotSearchExpert.isEmpty()) {
            llHotExpert.visibility = View.GONE
            return
        }
        llHotExpert.visibility = View.VISIBLE
        expertWidth = 0
        flHotExpert.removeAllViews()
        for (index in hotSearchExpert.indices) {
            val view = LayoutInflater.from(this)
                .inflate(R.layout.consultant_item_expert_hot_search, flHotSearch, false)
            view.tvHotSearch.text = hotSearchExpert[index].name
            if (!TextUtils.isEmpty(hotSearchExpert[index].name)) {
                expertWidth += getTextContentWidth(
                    view.findViewById(R.id.tvHotSearch),
                    if (hotSearchExpert[index].name!!.length > 7) hotSearchExpert[index].name!!.substring(
                        0,
                        8
                    ) else hotSearchExpert[index].name!!
                ) + dp42
                if (expertWidth > maxWidth) {
                    break
                }
            }
            view.setOnClickListener {
                ActionCountUtils.count(
                    SEARCH_BANNERWORD_CLICK,
                    hotSearchExpert[index].name.toString(),
                    "本周热门专家"
                )
                getSearchWords(hotSearchExpert[index].name.toString(), true)
            }
            flHotExpert.addView(view)
        }
    }

    //刷新 banner
    private fun refreshBanner(focusList: MutableList<HotSearchFocusItemBean>?) {
        if (null == focusList) {
            card_view.visibility = View.GONE
        }
        if (null != focusList && focusList.isNotEmpty()) {
            for (item in focusList) {
                if (!TextUtils.isEmpty(item.imageUrl)) {
                    bannerList.add(item.imageUrl!!)
                }
            }
        }
        banner.setOnBannerListener {
            if (null == focusList || focusList.isEmpty()) {
                TempH5RouteUtils.tempH5Route(
                    IYDLRouterConstant.ROUTER_H5_H5,
                    YDLRouterParams().putExtra(
                        IYDLRouterConstant.EXTRA_URL,
                        "https://h2.yidianling.com/ct/list"
                    ), ""
                )
            } else {
                TempH5RouteUtils.tempH5Route(focusList[it].linkUrl)
            }
        }
        banner.setImageLoader(GlideImageLoader(R.drawable.consultant_expert_banner_default))
            .setImages(bannerList).start()
        banner.setIndicatorBottomPadding(5)
    }

    private fun initHistoryData() {
        fl_search_history.removeAllViews()
        historyList.clear()
        val cacheHomeData = SharedPreferencesEditor.getString(CACHE_CONSULT_SEARCH_HISTORY_DATA)
        if (!TextUtils.isEmpty(cacheHomeData)) {
            ll_search_history.visibility = View.VISIBLE
            val list = Gson().fromJson<MutableList<String>>(
                cacheHomeData,
                object : TypeToken<MutableList<String>>() {
                }.type
            )
            historyList.addAll(list)
            if (historyList.size > 0) {
                for (historyStr in historyList.reversed()) {

                    val view = LayoutInflater.from(this)
                        .inflate(R.layout.consultant_item_expert_hot_search, flHotSearch, false)
                    view.tvHotSearch.text = historyStr
                    historyCurrentWidth += getTextContentWidth(
                        view.findViewById(R.id.tvHotSearch),
                        if (historyStr.length > 7) historyStr.substring(0, 8) else historyStr
                    ) + RxImageTool.dp2px(50f)
                    if (historyCurrentWidth > maxWidth) {
                        break
                    }
                    view.setOnClickListener {
                        //历史搜索
                        ActionCountUtils.count(SEARCH_BANNERWORD_CLICK, historyStr, "历史搜索")
                        getSearchWords(historyStr, true)
                    }
                    fl_search_history.addView(view)
                }
            }
        } else {
            ll_search_history.visibility = View.GONE
        }
    }

    private fun getTextContentWidth(textView: TextView, text: String): Int {
        val rect = Rect()
        textView.paint.getTextBounds(text, 0, text.length, rect)
        return rect.width()//文字宽
    }

    /**
     *  搜索
     *  @param isRecommendWords 是否是推荐词
     */
    private fun doSearch(searchWords: String, relatedWords: String, isRecommendWords: Boolean) {
        val view = this.currentFocus
        if (view != null) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }

        ActionCountUtils.count(ConsultBIConstants.UserMainEvent.YDL_USER_SEARCH_CLICK, searchWords)
        if (!TextUtils.isEmpty(searchWords)) {
            historyList.remove(searchWords)
            historyList.add(searchWords)
            SharedPreferencesEditor.putString(
                CACHE_CONSULT_SEARCH_HISTORY_DATA,
                Gson().toJson(historyList)
            )
        }
        ExpertSearchActivity.startSearch(this, searchWords, "14", relatedWords, isRecommendWords)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        historyCurrentWidth = 0
        expertWidth = 0
    }
}