package com.yidianling.uikit.business.session.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.TranslateAnimation
import android.widget.LinearLayout
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.yidianling.im.R
import com.yidianling.im.api.bean.ImCommendDetailBean
import kotlinx.android.synthetic.main.im_real_view_in.view.*
import kotlinx.android.synthetic.main.im_real_view_left.view.*
import kotlinx.android.synthetic.main.im_real_view_out.view.*

class ImCommentBannerView : LinearLayout {

    constructor(context: Context) : super(context) {
        mContext = context
        initViews()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        mContext = context
        initViews()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        mContext = context
        initViews()
    }

    private var mContext: Context? = null

    private val STATUS_IN = 0
    private val STATUS_OUT = 1
    private var curTipIndex = 0
    private var lastTimeMillis: Long = 0
    private val ANIM_DELAYED_MILLIONS = 2 * 1000
    /**
     * 动画持续时长
     */
    private val ANIM_DURATION = 500
    /**
     * 进、出 两个view (主要用于做动画，其实是两个相同的布局文件)
     */
    private var view_out: View? = null
    private var view_in: View? = null
    /**
     * 进、出 两个View 的动画
     */
    private var anim_out: Animation? = null
    private var anim_in: Animation? = null
    /**
     * 数据缓存
     */
    private var mDataList: ArrayList<ImCommendDetailBean>? = null


    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            updateTipAndPlayAnimation()
            sendMessageDelayed(Message(), ANIM_DELAYED_MILLIONS.toLong())
        }
    }

    private fun initViews() {
        initView()
        initAnimation()
    }

    /**
     * 界面初始化
     */
    private fun initView() {
        orientation = HORIZONTAL
        var params = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        View.inflate(mContext, R.layout.im_real_view_left, this)
        view_out = View.inflate(mContext, R.layout.im_real_view_out, null)
        view_in = View.inflate(mContext, R.layout.im_real_view_in, null)
        imRealViewLeftFrameLayout.addView(view_out)
        imRealViewLeftFrameLayout.addView(view_in)
        layoutParams = params
    }

    private fun initAnimation() {
        anim_out = newAnimation(0f, -1f)
        anim_in = newAnimation(1f, 0f)
        anim_in?.setAnimationListener(object : Animation.AnimationListener {

            override fun onAnimationStart(animation: Animation) {

            }

            override fun onAnimationRepeat(animation: Animation) {

            }

            override fun onAnimationEnd(animation: Animation) {
                updateViewVisibility()
            }
        })
    }

    /**
     * 设置数据
     */
    fun initData(list: ArrayList<ImCommendDetailBean>?) {
        mHandler.removeCallbacksAndMessages(null)
        if (null == list || list.isEmpty() || list.size == 0) {
            visibility = View.INVISIBLE
            return
        }
        visibility = View.VISIBLE
        if (null == mDataList) {
            mDataList = ArrayList()
        } else {
            (mDataList as ArrayList).clear()
        }
        (mDataList as ArrayList).addAll(list)
        curTipIndex = 0
        updateTip(STATUS_OUT)
        updateTipAndPlayAnimation()
        mHandler.sendMessageDelayed(Message(), ANIM_DELAYED_MILLIONS.toLong())
    }

    private fun updateViewVisibility() {
        if (curTipIndex % 2 == 0) {
            view_out?.visibility = View.INVISIBLE
        } else {
            view_in?.visibility = View.INVISIBLE
        }
    }

    private fun newAnimation(fromYValue: Float, toYValue: Float): Animation {
        val anim = TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
            Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue
        )
        anim.duration = ANIM_DURATION.toLong()
        anim.interpolator = DecelerateInterpolator()
        return anim
    }

    private fun updateTipAndPlayAnimation() {
        view_in?.visibility = View.VISIBLE
        view_out?.visibility = View.VISIBLE
        if (curTipIndex % 2 == 0) {
            updateTip(STATUS_OUT)
            view_in?.startAnimation(anim_out)
            view_out?.startAnimation(anim_in)
            this.bringChildToFront(view_in)
        } else {
            updateTip(STATUS_IN)
            view_out?.startAnimation(anim_out)
            view_in?.startAnimation(anim_in)
            this.bringChildToFront(view_out)
        }
    }

    private fun updateTip(status: Int) {
        val bodyBean = getNextTip() ?: return

        mContext?.let {
            when (status) {
                STATUS_IN -> {
                    tv_in_comment_desc.text = bodyBean.commentContent
                    tv_in_content_before.text = getName(bodyBean.nickName)
                    view_in?.setOnClickListener {
                        val params: H5Params = H5Params(bodyBean.commentUrl, "")
                        mContext?.let {
                            NewH5Activity.start(mContext, params)
                        }
                    }
                }
                STATUS_OUT -> {
                    tv_out_comment_desc.text = bodyBean.commentContent
                    tv_out_content_before.text = getName(bodyBean.nickName)
                    view_out?.setOnClickListener {
                        val params: H5Params = H5Params(bodyBean.commentUrl, "")
                        mContext?.let {
                            NewH5Activity.start(mContext, params)
                        }
                    }
                }
                else -> {}
            }
        }
    }


    //获取经过加密的名字 ： 徐**
    private fun getName(name: String?): String {
        var nameBuffer = StringBuffer()
        name?.let {

            nameBuffer.append(name[0])
            nameBuffer.append("**：")
        }
        return nameBuffer.toString()
    }

    private fun getNextTip(): ImCommendDetailBean? {
        if (null == mDataList || mDataList?.isEmpty()!!) {
            return null
        }
        return mDataList!![curTipIndex++ % mDataList!!.size!!]
    }

    fun onDestory() {
        mHandler.removeCallbacksAndMessages(null)
    }
}