package com.ym.game.adapter

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Activity
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.ym.library.listener.OnRecycleItemClickListener
import com.ym.game.view.MainDialog
import com.ym.library.base.BaseRecyclerAdapter
import com.ym.library.net.BaseObserver
import com.ym.library.net.RxSchedulers
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusUtil
import com.ym.library.utils.LogUtils
import com.ym.library.utils.Utils
import com.ym.xynt.R
import com.ym.library.module.NewsEntity
import com.ym.library.module.TaskCompleteEntity
import com.ym.library.module.WateringTaskEntity
import com.ym.library.net.GameApiClient
import com.ym.library.utils.EventUtils

class SpeedWaterTaskAdapter :
    BaseRecyclerAdapter<NewsEntity, SpeedWaterTaskAdapter.WateringTaskHolder> {

    private var type: Int = -1
    private var mContext: Activity? = null
    private val listener: OnRecycleItemClickListener<NewsEntity>

    constructor(
        content: Activity?,
        type: Int,
        listener: OnRecycleItemClickListener<NewsEntity>
    ) : super() {
        this.listener = listener
        mContext = content
        this.type = type
    }


    override fun onBindViewHolder(holder: WateringTaskHolder, position: Int) {
        if (mList.size > 0) {
            val data = mList[position]
            holder.tvTitle.text = data.title
            if (data?.awardRangeStart != null && data?.awardRangeEnd != null) {
                holder.tvCount.text = "+${data?.awardRangeStart}~${data?.awardRangeEnd}"
            } else {
                holder.tvCount.text = "+${data.coins}     "
            }
            if (!TextUtils.isEmpty(data.description)) {
             //   holder.btnProgess.visibility = View.GONE
             //   holder.tvTitle.text = data.title
                holder.tvProgess.text = data.description
            } else {
//                holder.btnProgess.visibility = View.VISIBLE
//                holder.btnProgess.max = data.awardLimit!!
//                holder.btnProgess.setProgress(data.current_nums!!)
                holder.tvProgess.text = "${data.current_nums}/${data.awardLimit}"
            }
            if (data?.adRenderStyle != null && data?.adRenderStyle == 1) {
                holder?.rlbg.setBackgroundResource(R.drawable.withdraw_bg)
                holder?.imglucky.visibility=View.GONE
            } else if (data?.adRenderStyle != null && data?.adRenderStyle == 3) {
                holder?.rlbg.setBackgroundResource(R.drawable.icon_luck_task)
                holder?.imglucky.visibility=View.VISIBLE
            }

            if (data?.buttonSway != null && data?.buttonSway == 1&&data?.status!=1) {
                startAnimator(holder?.ivStatus)
            } else {
                holder?.ivStatus.clearAnimation()
            }
//            holder.tvCount.text = "+${data.awardNum}"
//            holder.imgspeed.setImageResource(R.mipmap.icon_speed_get)
//            if (data.subTitle != null) {
//                holder.tvProgess.text = data.subTitle
//            } else {
//                holder.tvProgess.text = "${data.completedNum}/${data.targetNum}"
//            }

            holder.ivStatus.addClickScale()
            holder.ivStatus.setOnClickListener {
                if (Utils.isFastClick()) {
                    when (data.status) {

                        0 ->{
                            EventUtils.onEvent("jiasu_renwu_undone_click_"+mList[position].sid, "加速剂任务去完成点击")
                            listener.onItemClick(it, position, mList[position])
                        }


                        1 -> {

                            Utils.showToast(mContext, "您已经领过了哦~")
                        }
                        //领取
                        2 ->{
                            if (mList[position].opentype == 1) {
                                EventUtils.onEvent("jiasu_done_click_total","加速剂任务视频领取点击")
                            }
                            EventUtils.onEvent("jiasu_done_click_"+mList[position].sid, "加速剂任务领取点击")

                            getDripTaskReceive( data.sid!!,data)
                        }
                    }
                }
            }

            // 0未完成 1已领取 2可领取
            when (data.status) {
                0 -> holder.ivStatus.setImageResource(R.mipmap.icon_mian_popup_complete)
                1 -> holder.ivStatus.setImageResource(R.mipmap.icon_main_popup_receiveed)
                2 -> holder.ivStatus.setImageResource(R.mipmap.icon_main_popup_receive)
            }

            val layoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )
            if (position == mList.size - 1) {
                layoutParams.setMargins(0, 0, 0, Utils.dip2px(20f))
            } else {
                layoutParams.setMargins(0, 0, 0, Utils.dip2px(8f))
            }
            holder.layoutRoot.layoutParams = layoutParams
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WateringTaskHolder {
        return WateringTaskHolder(
            LayoutInflater.from(mContext).inflate(R.layout.item_get_water_task, parent, false)
        )
    }

    inner class WateringTaskHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvTitle: TextView = itemView.findViewById(R.id.tv_watering_item_title)
        val tvProgess: TextView = itemView.findViewById(R.id.tv_watering_item_progess)
        val tvCount: TextView = itemView.findViewById(R.id.tv_watering_item_count)
        val ivStatus: ImageView = itemView.findViewById(R.id.tv_watering_item_status)
        val imgspeed: ImageView = itemView.findViewById(R.id.img_icon_item)
        val layoutRoot: LinearLayout = itemView.findViewById(R.id.layout_watering_root)
        val rlbg: RelativeLayout = itemView.findViewById(R.id.ll_one)
        val imglucky: ImageView = itemView.findViewById(R.id.id_img_lucy)
    }

    // 领取水滴  type:1每日领水  2高额领水
    private fun getDripTaskReceive(sid: Int, data: NewsEntity) {
        GameApiClient.gameApi.getAcceleTask(sid).compose(
            RxSchedulers.observableIO2Main()
        ).subscribe(object : BaseObserver<TaskCompleteEntity>() {
            override fun onSuccess(result: TaskCompleteEntity?) {
                RxBusUtil.getDefault()
                    .send(RxBusConstant.RX_SPEED_WATER_TASK_LIST)
                if (result != null) {
                    MainDialog.showgetWaterDrop(mContext, 5, "task_accelerator", result.awardNum!!, null)
                }
            }

            override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {}
        })
    }
    private var animatorList: MutableList<ObjectAnimator> = ArrayList()
    private var viewList: MutableList<View> = ArrayList()
    private fun startAnimator(view: View) {
        val oa: ObjectAnimator = ObjectAnimator.ofFloat(
            view,
            View.ROTATION,
            0F, 8F, -8F, 0F, 0F, 0F, 0F, 0F, 0F
        )
        oa.repeatCount = ValueAnimator.INFINITE
        oa.setDuration(1000).start()
        animatorList.add(oa)
        viewList.add(view)
    }

    fun clearAnimation() {
        if (animatorList.size > 0) {
            for (animator in animatorList) {
                animator?.cancel()
            }
            animatorList.clear()
        }
        if (viewList.size > 0) {
            for (view in viewList) {
                view?.clearAnimation()
            }
            viewList.clear()
        }
    }
    /**
     * 添加点击缩放效果
     */
    fun View.addClickScale(scale: Float = 0.9f, duration: Long = 150) {
        this.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    this.animate().scaleX(scale).scaleY(scale).setDuration(duration).start()
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    this.animate().scaleX(1f).scaleY(1f).setDuration(duration).start()
                }
            }
            // 点击事件处理，交给View自身
            this.onTouchEvent(event)
        }
    }

}