package com.dlc.eboard.ui.widget

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import com.bumptech.glide.Glide
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.WidgetTitleBarBinding
import com.dlc.eboard.mqtt.MqttManager
import com.dlc.eboard.sp.DeviceSp
import com.dlc.eboard.ui.common.SimpleFlipperAdapter
import com.rc.httpcore.vo.response.NoticeSummaryVo
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.*

/**
 * info
 *
 * @author ReiChin_
 */
class TitleBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ConstraintLayout(context, attrs, defStyleAttr), ITitleBar {
    private val weakHandler by lazy { WeakReferenceHandler(this) }

    private val viewBinding =
        WidgetTitleBarBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.TitleBar)
        val signed = typeArray.getBoolean(R.styleable.TitleBar_signed, false)
        val showNotice = typeArray.getBoolean(R.styleable.TitleBar_showNotice, true)
        typeArray.recycle()

        setSigned(signed)
        setShowNotice(showNotice)
        viewBinding.noticeLayout.setOnClickListener { mTitleListener?.onNoticeViewClicked() }
    }

    override fun setSigned(signed: Boolean) {
        if (signed) {
            viewBinding.userGroup.visibility = VISIBLE
            val layoutParams = viewBinding.nowDate.layoutParams as LayoutParams
            layoutParams.horizontalBias = 0.52f
            viewBinding.nowDate.layoutParams = layoutParams
        } else {
            viewBinding.userGroup.visibility = GONE
            val layoutParams = viewBinding.nowDate.layoutParams as LayoutParams
            layoutParams.horizontalBias = 0.58f
            viewBinding.nowDate.layoutParams = layoutParams
        }
    }

    override fun setShowNotice(showNotice: Boolean) {
        viewBinding.noticeLayout.visibility = if (showNotice) VISIBLE else GONE
    }

    override fun setTitleInfoFromSp() {
        DeviceSp.loadLaboratoryVo(context)?.let { conf ->
            Glide.with(this)
                .load(conf.rectangleLogo)
                .into(viewBinding.logo)

            viewBinding.subName.text = conf.subName
        }
        weakHandler.sendEmptyMessage(1)
//        object : Handler(Looper.getMainLooper()) {
//            override fun handleMessage(msg: Message) {
//                // 3月13日 星期一 14:36
//                val format = SimpleDateFormat("MM月dd日 EEEE HH:mm", Locale.getDefault())
//                viewBinding.nowDate.text =
//                    format.format(Calendar.getInstance(Locale.getDefault()).time)
//                // 下一分钟更新日期显示
//                val calendar = Calendar.getInstance()
//                val nowTime = calendar.timeInMillis
//                calendar.set(Calendar.SECOND, 0) // 秒
//                calendar.set(Calendar.MILLISECOND, 0) // 毫秒
//                calendar.add(Calendar.MINUTE, 1) // 分+1
//                val nextTime = calendar.timeInMillis
//                sendEmptyMessageDelayed(1, nextTime - nowTime)
//            }
//        }.sendEmptyMessage(1)

        LabApp.sUserVo?.let {
            viewBinding.person.text = it.userName
        }
    }

    override fun updateNotice(data: List<NoticeSummaryVo>?) {
        if (VISIBLE == viewBinding.noticeFlipper.visibility) {
            val simpleData = data?.map { it.messContent }?.toMutableList()
            viewBinding.noticeFlipper.adapter = SimpleFlipperAdapter(data = simpleData)
            viewBinding.noticeFlipper.flipInterval = 3000
            viewBinding.noticeFlipper.setInAnimation(context, R.animator.anim_in)
            viewBinding.noticeFlipper.setOutAnimation(context, R.animator.anim_out)
            viewBinding.noticeFlipper.startFlipping()
        }
    }

    override fun refreshCountDownView(countDown: Int) {
        if (VISIBLE == viewBinding.countDown.visibility) {
            viewBinding.countDown.text = "${countDown}S"
        }
    }

    private var mTitleListener: ITitleBar.TitleListener? = null

    override fun setTitleListener(listener: ITitleBar.TitleListener) {
        this.mTitleListener = listener
    }

    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: TitleBar) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<TitleBar> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                // 3月13日 星期一 14:36
                val format = SimpleDateFormat("MM月dd日 EEEE HH:mm", Locale.getDefault())
                viewBinding.nowDate.text =
                    format.format(Calendar.getInstance(Locale.getDefault()).time)
                // 下一分钟更新日期显示
                val calendar = Calendar.getInstance()
                val nowTime = calendar.timeInMillis
                calendar.set(Calendar.SECOND, 0) // 秒
                calendar.set(Calendar.MILLISECOND, 0) // 毫秒
                calendar.add(Calendar.MINUTE, 1) // 分+1
                val nextTime = calendar.timeInMillis
                sendEmptyMessageDelayed(1, nextTime - nowTime)
            }
        }
    }
}