package com.qimai.android.widgetlib.topbar

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.contains
import com.qimai.android.tools.dpTopx
import com.qimai.android.tools.pxTosp
import com.qimai.android.widgetlib.R

/**
 *  默认配置
 *
+---------------------------------------------+
|                                             |
|  image            text                      |
|                                             |
+---------------------------------------------+
 *
 * 支持的
 *
 *  +------------------------------------------------------------------+
 *  | +-----+                  +------+                 +----+  +-----+|
 *  | |image|                  |title |                 |Text|  |image||
 *  | +-----+                  +------+                 +----+  +-----+|
 *   +-----------------------------------------------------------------+
 *
 *
 */

class QmTopBar : Toolbar {

    private var qmTopBarText: CharSequence? = ""


    var mRightImg: ImageView? = null
        private set

    var leftImageView: ImageView? = null
        private set
    // 中间的View
    lateinit var centerTextView: TextView
        private set
    lateinit var mRightTextView: TextView
        private set

    lateinit var lineView: View

    private var relativeLayout: RelativeLayout = RelativeLayout(context)

    var customRightView: View? = null


    var qmTopBarNeedSeparator: Boolean = false
        set(value) {
            field = value
            buildBottomDivideLine(relativeLayout)
        }
    private var qmTopBarBgColor: Int
        set(value) {
            field = value
            relativeLayout.setBackgroundColor(qmTopBarBgColor)
        }
    private var qmTopBarTextSize: Int
    private var qmTopBarTextColor: Int
    private var qmTopBarCenterBold = false


    var qmTopBarLeftDrawable: Int
        set(value) {
            field = value
            buildLeftImage(relativeLayout)
        }

    var qmTopBarRightDrawable: Int = -1
        set(value) {
            field = value
            if (value != -1) {
                buildRightImg(relativeLayout)
            }
        }

    private var qmTopBarRightTextColor: Int
    private var qmTopBarRightTextSize: Int
    private var rightTextBackground: Drawable? = null
    private var qmTopBarRightText: CharSequence? = null
    var rightTextProperty: TextProperty
        set(value) {
            field = value
            if (customRightView != null) {
                return
            }
            qmTopBarRightText = field.text
            qmTopBarRightTextSize = field.textSize
            qmTopBarRightTextColor = field.textColor
            rightTextBackground = field.textBackground
            buildRightText(relativeLayout)
        }

    var centerTextProperty: TextProperty
        set(value) {
            field = value
            qmTopBarText = field.text
            qmTopBarTextColor = field.textColor
            qmTopBarTextSize = field.textSize
            qmTopBarCenterBold = field.bold
            buildOrModifyCenter(relativeLayout)

        }


    private lateinit var mListenerViewClick: ListenerViewClick

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attributes: AttributeSet?) : this(context, attributes, 0)

    constructor(context: Context, attributes: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attributes,
        defStyleAttr
    ) {

        val a: TypedArray = context.theme.obtainStyledAttributes(
            /** layout 布局配置**/
            attributes,
            R.styleable.QmTopBar,
            /** 通过attr 设置**/
            defStyleAttr,
            /** 默认样式 **/
            0
        )

        qmTopBarNeedSeparator = a.getBoolean(R.styleable.QmTopBar_need_separator, false)
        qmTopBarBgColor = a.getColor(
            R.styleable.QmTopBar_bg_color,
            ContextCompat.getColor(context, R.color.QmTopBar_color_FFFFFFF)
        )

        qmTopBarTextSize = a.getDimensionPixelOffset(
            R.styleable.QmTopBar_title_text_size,
            context.resources.getDimensionPixelOffset(R.dimen.QmTopBar_dp_18)
        )

        qmTopBarTextColor = a.getColor(
            R.styleable.QmTopBar_title_color,
            ContextCompat.getColor(context, R.color.QmTopBar_color_000000)
        )
        qmTopBarText = a.getString(R.styleable.QmTopBar_title_text)

        qmTopBarLeftDrawable =
            a.getResourceId(R.styleable.QmTopBar_left_back_drawable_id, R.drawable.titlebar_back)


        qmTopBarRightDrawable = a.getResourceId(R.styleable.QmTopBar_right_drawable_id, -1)

        //----------
        qmTopBarRightTextColor = a.getColor(
            R.styleable.QmTopBar_right_text_color,
            ContextCompat.getColor(context, R.color.QmTopBar_color_3333333)
        )
        qmTopBarRightTextSize = a.getDimensionPixelOffset(
            R.styleable.QmTopBar_right_text_size,
            context.resources.getDimensionPixelOffset(R.dimen.QmTopBar_sp_12)
        )
        rightTextBackground = a.getDrawable(R.styleable.QmTopBar_right_text_background)
        qmTopBarRightText = a.getString(R.styleable.QmTopBar_right_text)
        rightTextProperty =
            TextProperty(
                qmTopBarRightText,
                qmTopBarRightTextColor,
                qmTopBarRightTextSize,
                rightTextBackground
            )

        centerTextProperty = TextProperty(qmTopBarText, qmTopBarTextColor, qmTopBarTextSize, null)
        a.recycle()
    }

    /**
     * 自定义 左边的返回按钮view
     * 移除自带的,直接加入用户的
     *  @param params = null 默认配置: （垂直居中 居左  离左边 16dp 宽/高 wrap_content）
     */
    fun customLeftView(view: View, params: RelativeLayout.LayoutParams?) {
        if (params == null) {
            val leftImageViewParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )
            leftImageViewParams.addRule(RelativeLayout.ALIGN_LEFT)
            leftImageViewParams.addRule(RelativeLayout.CENTER_VERTICAL)
            leftImageViewParams.leftMargin = context.dpTopx(16f)
            relativeLayout.addView(view, leftImageViewParams)
            relativeLayout.removeView(leftImageView)
            return
        }
        relativeLayout.removeView(leftImageView)
        leftImageView = null
        relativeLayout.addView(view, params)
    }

    /**
     * 自定义右边的view
     * default 居右 离右边 16dp 垂直居中
     */
    fun customRightView(view: View, params: RelativeLayout.LayoutParams?) {

        val rightParams: RelativeLayout.LayoutParams?
        if (params == null) {
            rightParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT
            )
            rightParams.addRule(RelativeLayout.CENTER_VERTICAL)
            rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            rightParams.rightMargin = context.dpTopx(16f)
        } else {

            rightParams = params
        }
        if (this.mRightImg != null && relativeLayout.contains(mRightImg!!)) {
            relativeLayout.removeView(mRightImg)
        }
        if (::mRightTextView.isInitialized && relativeLayout.contains(mRightTextView)) {
            relativeLayout.removeView(mRightTextView)
        }
        if (customRightView != null && relativeLayout.contains(customRightView!!)) {
            relativeLayout.removeView(customRightView)
        }
        customRightView = view
        relativeLayout.addView(view, rightParams)
    }


    private fun buildRightImg(relativeLayout: RelativeLayout) {
        if (qmTopBarRightDrawable != -1) {
            mRightImg = ImageView(context)
            mRightImg?.id = View.generateViewId()
            val rightImgParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )
            mRightImg?.setImageResource(qmTopBarRightDrawable)
            rightImgParams.addRule(RelativeLayout.CENTER_VERTICAL)
            rightImgParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            rightImgParams.rightMargin = context.dpTopx(16f)
            relativeLayout.addView(mRightImg, rightImgParams)
            registerRightImgListener()
        }
    }

    private fun buildRightText(relativeLayout: RelativeLayout) {

        if (!::mRightTextView.isInitialized) {
            mRightTextView = TextView(context)

            mRightTextView.text = qmTopBarRightText
            mRightTextView.setTextColor(qmTopBarRightTextColor)
            if (rightTextBackground != null) {
                mRightTextView.background = rightTextBackground
            }
            // textsize 的单位是sp
            mRightTextView.textSize = context.pxTosp(qmTopBarRightTextSize.toFloat()).toFloat()
            val rightTextParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )

            if (qmTopBarRightDrawable != -1) {
                rightTextParams.addRule(RelativeLayout.LEFT_OF, mRightImg!!.id)
                rightTextParams.addRule(RelativeLayout.CENTER_VERTICAL)
            } else {
                rightTextParams.addRule(RelativeLayout.CENTER_VERTICAL)
                rightTextParams.marginEnd = context.dpTopx(16f)
                rightTextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            }
            mRightTextView.setPadding(15, 5, 15, 5)

            relativeLayout.addView(mRightTextView, rightTextParams)
        } else {
            mRightTextView.text = qmTopBarRightText
            mRightTextView.setTextColor(qmTopBarRightTextColor)
            if (rightTextBackground != null) {
                mRightTextView.background = rightTextBackground
            }
        }
        registerRightTextListener()
    }

    fun registerViewClickListener(listenerViewClick: ListenerViewClick.() -> Unit) {

        mListenerViewClick = ListenerViewClick().also(listenerViewClick)
        initListener()
    }

    private fun initListener() {
        registerLeftImageListener()
        registerRightImgListener()
        registerRightTextListener()
    }

    private fun registerLeftImageListener() {
        if (!::mListenerViewClick.isInitialized) return
        leftImageView?.setOnClickListener {
            mListenerViewClick.backClick?.invoke(it)
        }

    }

    private fun registerRightImgListener() {
        if (mRightImg != null && ::mListenerViewClick.isInitialized) {
            mRightImg?.setOnClickListener {
                mListenerViewClick.rightImgClick?.invoke(it)
            }
        }
    }

    private fun registerRightTextListener() {
        if (!::mListenerViewClick.isInitialized) return
        mRightTextView.setOnClickListener {
            mListenerViewClick.rightTextClick?.invoke(it)
        }

    }


    init {
        addView(relativeLayout, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    }


    private fun buildBottomDivideLine(relativeLayout: RelativeLayout) {
        // 下划线
        if (qmTopBarNeedSeparator && !::lineView.isInitialized) {
            lineView = View(context)
            val lineParams =
                RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    context.dpTopx(0.5f)
                )
            lineView.setBackgroundColor(
                ContextCompat.getColor(
                    context,
                    R.color.QmTopBar_color_999999
                )
            )
            lineParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            relativeLayout.addView(lineView, lineParams)
        } else if (!qmTopBarNeedSeparator && ::lineView.isInitialized) {
            lineView.visibility = View.GONE
        } else if (qmTopBarNeedSeparator && ::lineView.isInitialized) {

            lineView.visibility = View.VISIBLE
        }
    }


    private fun buildLeftImage(relativeLayout: RelativeLayout) {
        leftImageView = ImageView(context)
        leftImageView!!.setImageDrawable(ContextCompat.getDrawable(context, qmTopBarLeftDrawable))
        leftImageView!!.id = View.generateViewId()
        val leftImageViewParams = RelativeLayout.LayoutParams(
            context.dpTopx(16f),
            context.dpTopx(19f)
        )
        leftImageViewParams.addRule(RelativeLayout.ALIGN_LEFT)
        leftImageViewParams.addRule(RelativeLayout.CENTER_VERTICAL)
        leftImageViewParams.leftMargin = context.dpTopx(16f)
        relativeLayout.addView(leftImageView, leftImageViewParams)
    }

    private fun buildOrModifyCenter(relativeLayout: RelativeLayout) {

        if (!::centerTextView.isInitialized) {
            centerTextView = TextView(context)
            val centerViewParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )
            centerViewParams.addRule(RelativeLayout.CENTER_IN_PARENT)


            centerTextView.text = qmTopBarText
            centerTextView.setTextColor(qmTopBarTextColor)
            centerTextView.id = View.generateViewId()
            relativeLayout.addView(centerTextView, centerViewParams)
        } else {
            centerTextView.text = qmTopBarText
            centerTextView.setTextColor(qmTopBarTextColor)
        }
        centerTextView.textSize = context.pxTosp(qmTopBarTextSize.toFloat()).toFloat()
        if (qmTopBarCenterBold) {
            centerTextView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        } else {
            centerTextView.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        }
    }

    inner class ListenerViewClick {
        var backClick: ((view: View) -> Unit)? = null
        var rightImgClick: ((view: View) -> Unit)? = null
        var rightTextClick: ((view: View) -> Unit)? = null


        fun backImgClick(action: (view: View) -> Unit) {
            backClick = action
        }

        fun rightImgClick(action: (view: View) -> Unit) {
            rightImgClick = action
        }

        fun rightTextClick(action: (view: View) -> Unit) {
            rightTextClick = action
        }
    }


}