package com.yidianling.course.widget

import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.actionutil.BIConstants
import com.yidianling.common.tools.RxImageTool
import com.yidianling.course.R
import kotlinx.android.synthetic.main.common_search_bar.view.*


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述:
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/01/07
 */
class SearchBarView : LinearLayout {
    private var barType: Int = JUMP_TO_SEARCH_COURSE

    private var searchCallBack: SearchCallBack? = null

    companion object {
        /**
         * Bar功能类型
         * 0.点击跳转搜索课程页面
         * 1.点击输入文本，此时需要设置EditText为可输入状态
         */
        const val JUMP_TO_SEARCH_COURSE = 0
        const val ENABLE_INPUT = 1
    }

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        initView()
    }

    /**
     * 跳转初始化
     */
    private fun initView() {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
        setBackgroundColor(Color.WHITE)
        setPadding(0, RxImageTool.dp2px(5f), 0, RxImageTool.dp2px(5f))
        View.inflate(context, R.layout.common_search_bar, this)
        setOnClickListener {
            when (barType) {
                JUMP_TO_SEARCH_COURSE -> {//搜索课程页面
                    ActionCountUtils.count(BIConstants.CourseHomeEvent.POSITION_COURSE_HOME_SEACH_CLICK)
                    YDLRouterManager.router(IYDLRouterConstant.ROUTER_COURSE_SEARCH)
                }
            }
        }
    }

    /**
     * 使用该View组件时必须调用
     * type 一种为点击跳转，一种为点击之后输入文本进行搜索用java代码设置View宽度
     * mSearchCallBack 回调
     */
    fun initBarType(type: Int, mSearchCallback: SearchCallBack?) {
        barType = type
        common_search_bar_edit_text.clearFocus()

        when (barType) {
            //跳转时，设置输入框无法获取焦点
            JUMP_TO_SEARCH_COURSE -> {
            }
            //设置输入框能获取焦点且设置回调
            ENABLE_INPUT -> {
                setSearchCallBack(mSearchCallback)
                toggleKeyBoard(true)
                setEditTextVisibility(true)
            }
        }
    }

    fun setTextVisibility() {
        common_search_bar_btn.visibility = View.VISIBLE
    }


    private fun setEditTextVisibility(boolean: Boolean) {
        if (boolean) {
            common_search_bar_text.visibility = View.GONE
            common_search_bar_edit_text.visibility = View.VISIBLE
            common_search_bar_btn.visibility = View.VISIBLE
            common_search_bar_edit_text.setOnEditorActionListener { v, actionId, event ->
                searchCallBack?.clickSearchBtn(common_search_bar_edit_text.text.toString())
                toggleKeyBoard(false)
                true
            }
            common_search_bar_btn.setOnClickListener {
                toggleKeyBoard(false)
                searchCallBack?.cloase()
            }

            iv_delete_icon.setOnClickListener {
                common_search_bar_edit_text.setText("")
            }
            common_search_bar_edit_text.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (!TextUtils.isEmpty(s)) {
                        iv_delete_icon.visibility = View.VISIBLE
                    } else {
                        iv_delete_icon.visibility = View.GONE
                    }
                }

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

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

    fun setText(content: String) {
        common_search_bar_edit_text.setText(content, TextView.BufferType.EDITABLE)
        if (!TextUtils.isEmpty(content)) {
            iv_delete_icon.visibility = View.VISIBLE
        }
    }

    fun toggleKeyBoard(type: Boolean) {
        if (common_search_bar_edit_text.requestFocus()) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (type) {
                imm.showSoftInput(common_search_bar_edit_text, InputMethodManager.SHOW_IMPLICIT)
            } else imm.hideSoftInputFromWindow(common_search_bar_edit_text.windowToken, 0)
        }
    }

    fun setSearchCallBack(mSearchCallback: SearchCallBack?) {
        searchCallBack = mSearchCallback
    }

    interface SearchCallBack {
        fun clickSearchBtn(str: String) //设置监听（跳转逻辑已在组件内部实现，该方法主要用于回调点击键盘搜索按钮事件）

        fun cloase()
    }
}