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 com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.FixSizeLinkedList
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.view.banner.GlideImageLoader
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.consultant.bean.HotSearchBean
import com.yidianling.consultant.bean.HotSearchFocusItemBean
import com.yidianling.consultant.bean.HotSearchKeyWordDataBean
import com.yidianling.consultant.bean.HotSearchPopularDoctorBean
import com.yidianling.consultant.contract.IHotSearchContract
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 val CACHE_CONSULT_SEARCH_HISTORY_DATA = "cache_consult_search_history_data"
    private val HOT_SEARCH_DOCTOR_NAME = "hot_search_doctor_name"
    private var historyList: FixSizeLinkedList<String> = FixSizeLinkedList(15)
    private val bannerList = ArrayList<String>()
    //历史搜索内容的最大宽度
    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() {
        var doctorName = intent.getStringExtra(HOT_SEARCH_DOCTOR_NAME)
        if (!TextUtils.isEmpty(doctorName)) {
            etSearch.setText(doctorName)
            iv_delete_icon.visibility = View.VISIBLE
        }
    }

    private fun initViews() {
        iv_delete_icon.setOnClickListener {
            etSearch.setText("")
        }
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                doSearch()
            }
            true
        }
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                doSearch()
            }
            true
        }
        tv_search_cancle.setOnClickListener {
            finish()
        }
        iv_delete_history.setOnClickListener {
            SharedPreferencesEditor.putString(CACHE_CONSULT_SEARCH_HISTORY_DATA, "")
            initHistoryData()
        }
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    iv_delete_icon.visibility = View.INVISIBLE
                } else {
                    iv_delete_icon.visibility = View.VISIBLE
                }
            }

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

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

            }

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

    private fun initData() {
        initHistoryData()
        mPresenter.localData(this)

        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 requestFail() {
        refreshBanner(null)
    }

    //刷新 热门搜索
    private fun refreshHotSearchData(keywordData: MutableList<HotSearchKeyWordDataBean>?) {
        if (null == keywordData || keywordData.isEmpty()) {
            llHotSearch.visibility = View.GONE
            return
        }
        llHotSearch.visibility = View.VISIBLE
        flHotSearch.removeAllViews()
        for (index in keywordData.indices) {
            val view = LayoutInflater.from(this).inflate(R.layout.consultant_item_expert_hot_search, flHotSearch, false)
            view.tvHotSearch.text = keywordData[index].keyword
            view.setOnClickListener {
                etSearch.setText(keywordData[index].keyword)
                doSearch()
            }
            flHotSearch.addView(view)
        }
    }

    //刷新 本周热门专家
    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 {
                etSearch.setText(hotSearchExpert[index].name)
                doSearch()
            }
            flHotExpert.addView(view)
        }
    }

    //刷新 banner
    private fun refreshBanner(focusList: MutableList<HotSearchFocusItemBean>?) {
        if (null == focusList) {
//            if (bannerList.isEmpty()) {
//                bannerList.add("https://h2.yidianling.com/ct/list")
//            }
            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 {
                        etSearch.setText(historyStr)
                        doSearch()
                    }
                    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()//文字宽
    }

    //执行搜索
    private fun doSearch() {
        val view = this.currentFocus
        if (view != null) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
        val keyWord = etSearch.text.toString()
//        if (TextUtils.isEmpty(keyWord.trim())) {
//            ToastUtil.toastShort("请输入搜索内容")
//            return
//        }
        if (!TextUtils.isEmpty(keyWord)) {
            historyList.remove(keyWord)
            historyList.add(keyWord)
            SharedPreferencesEditor.putString(CACHE_CONSULT_SEARCH_HISTORY_DATA, Gson().toJson(historyList))
        }


        ExpertSearchActivity.start(this, keyWord)

        this.finish()
    }

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