package com.yidianling.home.ui.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
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.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.home.constants.HomeBIConstants
import com.yidianling.home.R
import com.yidianling.home.event.IHomeBaseEvent
import com.yidianling.home.model.bean.HomeHeaderBean
import kotlinx.android.synthetic.ydl.home_real_view_in.view.*
import kotlinx.android.synthetic.ydl.home_real_view_left.view.*
import kotlinx.android.synthetic.ydl.home_real_view_out.view.*

/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 首页顶部模块-动态标签模块
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/16
 */
class HomePagerBannerRealView(mContext : Context,homeEvent : IHomeBaseEvent) : LinearLayout(mContext){

    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 : List<HomeHeaderBean.HomeSaleDataBean>? = null

    private var homeEvent : IHomeBaseEvent? = null

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

    init {
        this.homeEvent = homeEvent
        initView()
        initAnimation()
    }

    /**
     * 界面初始化
     */
    private fun initView() {
        orientation = HORIZONTAL
        var params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        View.inflate(context, R.layout.home_real_view_left, this)
        view_out = View.inflate(context, R.layout.home_real_view_out,null)
        view_in = View.inflate(context, R.layout.home_real_view_in,null)
        homeModuleRealViewLeftFrameLayout.addView(view_out)
        homeModuleRealViewLeftFrameLayout.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: List<HomeHeaderBean.HomeSaleDataBean>?){
        mHandler.removeCallbacksAndMessages(null)
        if (null == list || list.isEmpty()){
            visibility = View.GONE
            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

        when(status){
            STATUS_IN -> {
                tv_in_doctor_name.text = bodyBean.doctorName
                tv_in_content_before.text = getName(bodyBean)
                tv_in_content_after.text = String.format("老师%s",bodyBean.contentAfter)
                view_in!!.setOnClickListener{
                    ActionCountUtils.count(HomeBIConstants.YDL_USER_NOTICE_CLICK)
                    homeEvent!!.linkTo(bodyBean.url!!)
                }
            }
            STATUS_OUT -> {
                tv_out_doctor_name.text = bodyBean.doctorName
                tv_out_content_before.text = getName(bodyBean)
                tv_out_content_after.text = String.format("老师%s",bodyBean.contentAfter)
                view_out!!.setOnClickListener{
                    ActionCountUtils.count(HomeBIConstants.YDL_USER_NOTICE_CLICK)
                    homeEvent!!.linkTo(bodyBean.url!!)
                }
            }
        }
    }

    private fun getName(bean : HomeHeaderBean.HomeSaleDataBean?) : String{
        var nameBuffer = StringBuffer()
        nameBuffer.append(bean?.contentBefore)
        nameBuffer.append(" ")
        nameBuffer.append(bean?.nickName)
        nameBuffer.append(resources.getString(R.string.home_real_appoint))
        return nameBuffer.toString()
    }

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

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