package com.zxbw.modulemain.activity

import android.content.Intent
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxbw.modulemain.R
import com.zxbw.modulemain.adapter.SearchReslutAdapter
import com.zxbw.modulemain.contract.SearchContract
import com.zxbw.modulemain.presenter.SearchPresenter
import com.zxbw.modulemain.uitls.SPUtils
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.model.qy.TbGoodsItemEntity
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.OnRecycleItemClickListener
import kotlinx.android.synthetic.main.activity_layout_search.*
import me.jessyan.autosize.utils.ScreenUtils


/**
 * @author (wangXuewei)
 * @datetime 2022-06-06 14:20 GMT+8
 * @detail :搜索
 */
class SearchActivity : BaseActivity(), SearchContract.View,
    OnRecycleItemClickListener<TbGoodsItemEntity> {
    private var mPresenter: SearchPresenter? = null
    var mGoodsAdapter: SearchReslutAdapter? = null
    override fun before() {
        super.before()
        setStatusBarBackground(resources.getColor(com.zxhl.cms.R.color.transparent))
    }

    override fun onClick(v: View?) {
        when (v) {
            id_img_back_search -> {
                finish()
            }
            id_img_clean_history -> {
                id_search_history_view.removeAllViews()
                SPUtils.getInstance(this).cleanHistory()
            }
            id_search_btn2 -> {
                val searchValue = id_edt_input_value.text.toString().trim()
                if (searchValue.isNullOrEmpty()) {
                    showToast("请输入要搜索的商品")
                } else {
                    SPUtils.getInstance(this).saveHistory(searchValue)
//                    showToast(searchValue)
//                    JumpUtils.SearchReslutJumo(searchValue, "0", "")
                    JumpUtils.SearchReslutJumo(searchValue)
                }
            }
        }
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_search
    }

    override fun init() {
        var statusBarHeight = ScreenUtils.getStatusBarHeight()
        if (statusBarHeight <= 0) {
            statusBarHeight = 40
        }
        id_sys_bar_view.layoutParams.height = statusBarHeight
        id_img_back_search.setOnClickListener(this)
//        id_search_btn.setOnClickListener(this)
        id_search_btn2.setOnClickListener(this)
        id_img_clean_history.setOnClickListener(this)

        mGoodsAdapter = SearchReslutAdapter(this, this)
        id_rck_goods_list.layoutManager = LinearLayoutManager(this)
        id_rck_goods_list.adapter = mGoodsAdapter


        mPresenter = SearchPresenter(this)

        mPresenter?.getSearchHistory()
        mPresenter?.getBestGoodsList()

        id_edt_input_value.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_UP) {
                hideKeyBoard()
//                id_search_btn.callOnClick()
                id_search_btn2.callOnClick()
            }
            false
        }
        EventUtils.onEvent("SearchPageShow")
    }

    override fun onResume() {
        super.onResume()
        id_edt_input_value.setText("")
        id_edt_input_value.requestFocus()
        showKeyBoard(id_edt_input_value)
    }

    override fun setSearchHistory() {
        val historyList = SPUtils.getInstance(this).historyList
        if (historyList.size == 1 && historyList[0].isNullOrEmpty()) {

        } else {
            initHistoryView(historyList.toList())
        }
    }

    override fun setBestGoodsList(result: List<TbGoodsItemEntity>?) {
        if (result.isNullOrEmpty()) {
            id_tv_title2.visibility = View.GONE
            id_rck_goods_list.visibility = View.GONE
        } else {
            id_tv_title2.visibility = View.VISIBLE
            id_rck_goods_list.visibility = View.VISIBLE
            mGoodsAdapter?.clear()
            mGoodsAdapter?.appendToList(result)
        }
    }

    private var mViewList: MutableList<View> = ArrayList()
    fun initHistoryView(mData: List<String>) {
        mViewList.clear()
        for (i in mData.indices) {
            var mTv = LayoutInflater.from(this)
                .inflate(
                    R.layout.item_view_search_history,
                    id_search_history_view,
                    false
                ) as TextView
            mTv.text = mData[i]
            mViewList.add(mTv);
        }
        id_search_history_view.setChildren(mViewList)
        id_search_history_view.viewTreeObserver.addOnGlobalLayoutListener(object :
            OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                id_search_history_view.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount = id_search_history_view.lineCount
                val twoLineViewCount = id_search_history_view.twoLineViewCount
                val expandLineViewCount = id_search_history_view.expandLineViewCount
                if (lineCount > 2) {
                    initHistoryClose(twoLineViewCount, expandLineViewCount, mData)
                }
            }
        })

        id_search_history_view.setOnTagClickListener { view, position ->
//            JumpUtils.SearchReslutJumo(mData[position], "0", "")
            JumpUtils.SearchReslutJumo(mData[position])
        }

    }


    fun initHistoryClose(twoLineViewCount: Int, expandLineViewCount: Int, mData: List<String>) {
        mViewList.clear();
        for (i in 0 until twoLineViewCount) {
            var mTv = LayoutInflater.from(this)
                .inflate(
                    R.layout.item_view_search_history,
                    id_search_history_view,
                    false
                ) as TextView
            mTv.text = mData[i]
            mViewList.add(mTv);
        }
        //展开按钮
        var mCloseBtn = LayoutInflater.from(this)
            .inflate(
                R.layout.item_view_search_history_btn_img,
                id_search_history_view,
                false
            ) as ImageView
        mCloseBtn.setImageResource(R.drawable.icon_xialajiantou);
        mCloseBtn.setOnClickListener {
            initHistoryOpen(twoLineViewCount, expandLineViewCount, mData);
        }
        mViewList.add(mCloseBtn)
        id_search_history_view.setChildren(mViewList)
        id_search_history_view.viewTreeObserver.addOnGlobalLayoutListener(object :
            OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                id_search_history_view.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount = id_search_history_view.lineCount
                val twoLineViewCount = id_search_history_view.twoLineViewCount
                if (lineCount > 2) {
                    initHistoryClose(
                        twoLineViewCount - 1,
                        id_search_history_view.expandLineViewCount,
                        mData
                    )
                }
            }
        })
    }

    fun initHistoryOpen(twoLineViewCount: Int, expandLineViewCount: Int, mData: List<String>) {
        mViewList.clear();
        for (i in mData.indices) {
            var mTv = LayoutInflater.from(this)
                .inflate(
                    R.layout.item_view_search_history,
                    id_search_history_view,
                    false
                ) as TextView
            mTv.text = mData[i]
            mViewList.add(mTv);
        }
//        //收起按钮
//        var mCloseBtn = LayoutInflater.from(this)
//            .inflate(
//                R.layout.item_view_search_history_btn_img,
//                id_search_history_view,
//                false
//            ) as ImageView
//        mCloseBtn.setImageResource(R.drawable.icon_xialajiantou);
//        mCloseBtn.setOnClickListener {
//            initHistoryClose(twoLineViewCount, expandLineViewCount, mData);
//        }
//        mViewList.add(mCloseBtn);
        id_search_history_view.setChildren(mViewList)
    }

    override fun onItemClick(view: View?, position: Int, data: TbGoodsItemEntity?) {
        EventUtils.onEvent("SearchGoodsClick", data?.id ?: "-1")
        if (data?.bannerType.equals("blindBox")) {
//            if (!Constant.Switch.isOpenVip) {
//                JumpUtils.MemberOrderJump()
//            }else{
//                JumpUtils.goodsDetailJump(data?.boxId)
//            }
        } else {
            var intent = Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtra("goods", data)
            intent.setClass(this, TbGoodsDetailActivity().javaClass)
            startActivity(intent)
        }
    }

}