package com.zxhl.main.page.adapter

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.base.BaseRecyclerAdapter
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.HomeListEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.RecycleImageView
import com.zxhl.main.R

class UserAdapter : BaseRecyclerAdapter<HomeListEntity, RecyclerView.ViewHolder> {
    private var mContext: Context? = null
    private val listener: OnRecycleItemClickListener<HomeListEntity>
    private var ifplay: Boolean = false
    private var lastpostion: Int = -1

    //private val HEAD = 1009
    private val CONTENT = 1000
    public val LOADMORE = 1001
    private val checkStatus: MutableMap<Int, Boolean> = HashMap()
    private var userId: String = ""
    private var likeposition: Int = -1
    private var ifPlayAnimal: Boolean = false
    private var distancePositon: Int = -1//获取某个位置的距离
    private var distance: String = ""//获取距离传过来

    constructor(
        content: Context?,
        listener: OnRecycleItemClickListener<HomeListEntity>
    ) : super() {
        this.listener = listener
        mContext = content
    }


    private var isLoadMore = false
    fun setLoadMore(isBoolean: Boolean) {
        isLoadMore = isBoolean
    }

    fun getLoadMore(): Boolean = isLoadMore
    override fun getItemViewType(position: Int): Int {
        if (isLoadMore) {
            if (position == mList.size) {
                return LOADMORE
            } else {
                return CONTENT
            }
        } else {
            return CONTENT
        }
    }

    override fun getItemCount(): Int {
        val size = mList.size
        if (size > 0) {
            return if (isLoadMore) {
                mList.size + 1
            } else {
                mList.size
            }
        } else {
            return size
        }
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun onCreateViewHolder(holder: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (isLoadMore) {
            if (viewType == LOADMORE) {
                return LoadMoreHolder(
                    LayoutInflater.from(mContext).inflate(R.layout.item_load_more, holder, false)
                )
            } else {

                return ViewHolder(
                    LayoutInflater.from(holder.context)
                        .inflate(R.layout.item_layout_home, holder, false)
                )


            }
        } else {

            return ViewHolder(
                LayoutInflater.from(holder.context)
                    .inflate(R.layout.item_layout_home, holder, false)
            )


        }


    }

    //更新当前播放状态
    fun updateCurrentPlayStatus(ifplay: Boolean, p: Int) {
        this.ifplay = ifplay
        notifyItemChanged(p)
        if (ifplay) {
            lastpostion = p
        } else {
            lastpostion = -1
        }

    }

    //更新其他按钮的播放状态
    fun updateOtherPlayStatus(ifplay: Boolean) {
        this.ifplay = ifplay
        notifyDataSetChanged()
        lastpostion = -1
    }

    //更新从详情页回来的超级喜欢状态
    fun updateUserLikeStatus(userId: String) {
        this.userId = userId
        SettingPreference.setLikeUserId("")
        notifyDataSetChanged()
    }

    //当前页点赞成功 更新状态
    fun likeSuccess(likeposition: Int, boolean: Boolean) {
        this.ifPlayAnimal = boolean
        this.likeposition = likeposition
        Log.e("MXL", "刷新当前喜欢的状态" + likeposition + boolean)
        notifyItemChanged(likeposition)
    }

    //更新获取的距离
    fun getDistanceSuc(disPostion: Int, distance: String) {
        this.distancePositon = disPostion
        this.distance = distance
        notifyItemChanged(disPostion)
    }

//    private var lastPos: Int = -1
//
//    //设置某个item状态
//    fun updatePlayStatus(ifplay: Boolean, p: Int) {
//        if (lastPos != -1) {
//            checkStatus.put(lastPos, false)
//        }
//        checkStatus.put(p, ifplay)
//        lastPos = p
//        notifyDataSetChanged()
//    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ViewHolder) {
            val data = mList[position]
            holder.id_tv_age.text = "${data.age}"
            holder.id_tv_countryEn.text = "${data.countryEn}"
            holder.id_tv_chat_price.text="${data.videoPrice}/min"
            holder.id_img_guoqi.setLoadImageUrl("${data.nationalFlag}", false)
            if (TextUtils.equals(data.sex, "2")) {
                //girl
                holder.id_ll_sex_bg.setBackgroundResource(R.drawable.shape_girl_bg)
            } else {
                //boy
                holder.id_ll_sex_bg.setBackgroundResource(R.drawable.shape_boy_bg)
            }
            if (TextUtils.isEmpty(data.voice)) {
                holder.id_rl_play_audio.visibility = View.GONE
            } else {
                holder.id_rl_play_audio.visibility = View.GONE
            }
            if (TextUtils.equals(data.onlineStatus, "1")) {
                holder.id_img_online.visibility = View.GONE
            } else {
                holder.id_img_online.visibility = View.GONE
            }
            if (TextUtils.isEmpty(data.distance)) {
                holder.id_tv_chakan_juli.visibility = View.GONE
                holder.id_tv_juli.visibility = View.GONE
            } else {
                holder.id_tv_chakan_juli.visibility = View.GONE
                holder.id_tv_juli.visibility = View.GONE
                // var str: String = String.format("%.2f", distance.toDouble())
                holder.id_tv_juli.text = "${data.distance}km"
            }
            if (TextUtils.equals(data.hasLikes, "0")) {
                holder.id_img_home_like.setImageResource(R.drawable.icon_home_like_default)
            } else {
                holder.id_img_home_like.setImageResource(R.drawable.icon_home_like_click)
            }
            if (!TextUtils.isEmpty(userId)) {
                if (userId.equals(data.uid)) {
                    holder.id_img_home_like.setImageResource(R.drawable.icon_home_like_click)
                }
            }
            if (position == lastpostion) {
                holder.id_img_voice.setImageResource(R.drawable.icon_bofang)
                holder.id_tv_play_status.text = "播放中…"
            } else {
                holder.id_tv_play_status.text = "点击播放"
                holder.id_img_voice.setImageResource(R.drawable.icon_yuyin)
            }
            if (data.chatStatus == 0) {
                //搭讪
                holder.id_tv_chat_status?.text = "搭讪"
            } else if (data.chatStatus == 1) {
                //继续聊天
                holder.id_tv_chat_status?.text = "继续聊天"
            }
            holder.id_tv_satus?.text = data.pageTag
            holder.id_tv_user_nick_name?.text = data.nickname
            val width = (PhoneUtils.getScreenWidth(AppContext.get()) - Utils.dip2px(14)) / 2
            val height: Float = width * 1.33f
            holder.rl_item.setLayoutParams(RelativeLayout.LayoutParams(width, height.toInt()))
            if (!data.picturesList.isNullOrEmpty()) {
                Glide.with(mContext!!).load(data.picturesList?.get(0))
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(10)))
                    .into(holder.img)
               // holder.img.setLoadImageUrl(data.picturesList?.get(0), false)
            } else {
                //holder.img.setLoadImageUrl(data.headImage, false)
            }
            if (!TextUtils.isEmpty(data.voiceTime)) {
                if (data.voiceTime?.contains("s") == true) {
                    holder.id_tv_voicetime.text = data.voiceTime
                } else {
                    holder.id_tv_voicetime.text = data.voiceTime + "s"
                }

            }

            if (this.likeposition == position && ifPlayAnimal) {
                data.hasLikes = "1"
                playAnimation(holder.id_img_home_like, holder.id_img_heart_gif)
            }
            if (this.distancePositon == position) {
                holder.id_tv_chakan_juli.visibility = View.GONE
                holder.id_tv_juli.visibility = View.VISIBLE
                // var str: String = String.format("%.2f", distance.toDouble())
                holder.id_tv_juli.text = "${distance}KM"
                data.distance = distance
                this.distancePositon = -1
            }

            onReport(data, position)

        } else if (holder is LoadMoreHolder) {
            Glide.with(AppContext.get()).asGif().load(R.drawable.load_more).into(holder.mImg)
        }
    }

    private fun onReport(data: HomeListEntity, position: Int) {
        if (!data.isUpload) {
            //   Log.d("glc", "postion:"+position+"我被上报了:" + data.nickname)
            EventUtils.onEvent("HomeUserShow", "" + data.uid)
            mList[position].isUpload = true
        }
    }

    inner class ViewHolder : RecyclerView.ViewHolder {

        var img: ImageView
        var rl_item: RelativeLayout
        var id_tv_satus: TextView
        var id_tv_chakan_juli: TextView
        var id_tv_juli: TextView
        var id_rl_play_audio: RelativeLayout
        var id_img_voice: ImageView
        var id_tv_play_status: TextView
        var id_img_home_like: ImageView
        var id_img_heart_gif: ImageView
        var id_tv_voicetime: TextView
        var id_img_online: ImageView
        var id_tv_chat_status: TextView
        var id_tv_user_nick_name: TextView
        var id_tv_age: TextView//年龄
        var id_ll_sex_bg: LinearLayout
        var id_img_guoqi: RecycleImageView
        var id_tv_countryEn: TextView
        var id_tv_chat_price: TextView

        constructor(itemView: View) : super(itemView) {
            img = itemView.findViewById(R.id.id_img_photo)
            rl_item = itemView.findViewById(R.id.id_rl_item)
            id_tv_satus = itemView.findViewById(R.id.id_tv_satus)
            id_tv_chakan_juli = itemView.findViewById(R.id.id_tv_chakan_juli)
            id_tv_juli = itemView.findViewById(R.id.id_tv_juli)
            id_rl_play_audio = itemView.findViewById(R.id.id_rl_play_audio)
            id_img_voice = itemView.findViewById(R.id.id_img_voice)
            id_tv_play_status = itemView.findViewById(R.id.id_tv_play_status)
            id_tv_voicetime = itemView.findViewById(R.id.id_tv_voicetime)
            id_img_home_like = itemView.findViewById(R.id.id_img_home_like)
            id_img_heart_gif = itemView.findViewById(R.id.id_img_heart_gif)
            id_img_online = itemView.findViewById(R.id.id_img_online)
            id_tv_chat_status = itemView.findViewById(R.id.id_tv_chat_status)
            id_tv_user_nick_name = itemView.findViewById(R.id.id_tv_user_nick_name)
            id_tv_age = itemView.findViewById(R.id.id_tv_age)
            id_ll_sex_bg = itemView.findViewById(R.id.id_ll_sex_bg)
            id_img_guoqi = itemView.findViewById(R.id.id_img_guoqi)
            id_tv_countryEn = itemView.findViewById(R.id.id_tv_countryEn)
            id_tv_chat_price = itemView.findViewById(R.id.id_tv_chat_price)
            id_img_home_like.setOnClickListener(object : NoDoubleClickListener() {
                override fun onNoDoubleClick(v: View?) {
                    val pos = adapterPosition
                    if (pos >= 0 && pos < mList.size) {
                        if (mList[pos].hasLikes.equals("0")) {
                            listener.onItemClick(v, pos, mList[pos])
                        } else {
                            playAnimation(id_img_home_like, id_img_heart_gif)
                        }
                    }
                }

            })

            id_tv_chat_status.setOnClickListener(object : NoDoubleClickListener() {
                override fun onNoDoubleClick(v: View?) {
                    val pos = adapterPosition
                    Log.e("MXL", "pos" + pos)
                    if (pos >= 0 && pos < mList.size) {
                        listener.onItemClick(v, pos, mList[pos])
                    }
                }

            })
            id_rl_play_audio.setOnClickListener {
                val pos = adapterPosition
                if (pos >= 0 && pos < mList.size) {
                    listener.onItemClick(it, pos, mList[pos])
                }
            }
            id_tv_chakan_juli.setOnClickListener(object : NoDoubleClickListener() {
                override fun onNoDoubleClick(v: View?) {
                    val pos = adapterPosition
                    if (pos >= 0 && pos < mList.size) {
                        listener.onItemClick(v, pos, mList[pos])
                    }
                }

            })
            rl_item.setOnClickListener(object : NoDoubleClickListener() {
                override fun onNoDoubleClick(v: View?) {
                    val pos = adapterPosition
                    if (pos >= 0 && pos < mList.size) {
                        listener.onItemClick(v, pos, mList[pos])
                    }
                }
            })
        }
    }


    inner class LoadMoreHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mImg: ImageView

        init {
            mImg = itemView.findViewById(R.id.id_item_more_img)
        }
    }

    fun playAnimation(id_img_home_like: ImageView, id_img_heart_gif: ImageView) {
        var animatorSet = AnimatorSet()
        var durin: Long = 300
        id_img_heart_gif.visibility = View.VISIBLE
        Glide.with(AppContext.get()).asGif().load(R.drawable.heart)
            .into(id_img_heart_gif)
        animatorSet.play(
            alphaAni(id_img_home_like, 0F, 1F, durin, 0)
        )
            .with(scaleAni(id_img_home_like, "scaleX", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleY", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleX", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleY", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleX", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleY", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleX", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_home_like, "scaleY", 1.14f, 1F, durin, 0))
        animatorSet.start()
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                MainLooper.get()
                    ?.postDelayed(Runnable {
                        id_img_heart_gif.visibility = View.GONE
                    }, 1000)

            }
        })

        id_img_home_like.setImageResource(R.drawable.icon_home_like_click)
        likeposition = -1
        ifPlayAnimal = false
    }

    fun scaleAni(
        view: View,
        propertyName: String,
        from: Float,
        to: Float,
        time: Long,
        delayTime: Long
    ): ObjectAnimator {
        val ani = ObjectAnimator.ofFloat(view, propertyName, from, to)
        ani.interpolator = LinearInterpolator()
        ani.startDelay = delayTime
        ani.duration = time
        return ani
    }

    fun alphaAni(view: View, from: Float, to: Float, time: Long, delayTime: Long): ObjectAnimator {
        val ani = ObjectAnimator.ofFloat(view, "alpha", from, to)
        ani.interpolator = LinearInterpolator()
        ani.duration = time
        ani.startDelay = delayTime
        return ani
    }


}