package com.etong.smart.Main

import android.content.Intent
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.etong.smart.Data.Discuss
import com.etong.smart.Main.LeftDrawer.ReviewImageActivity
import com.etong.smart.Other.*
import com.etong.smart.R
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.end_view.view.*
import kotlinx.android.synthetic.main.item_activity_detail.view.*
import kotlinx.android.synthetic.main.item_activity_detail_comment.view.*
import kotlinx.android.synthetic.main.item_activity_detail_image.view.*
import kotlinx.android.synthetic.main.item_activity_detail_sub_comment.view.*
import java.util.*


class ActivityDetailAdapter(val activityActivity: ActivityDetailActivity, val dataList: ArrayList<AdapterData>, val mListener: ChangeListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    companion object {
        val Detail_type = 0
        val Comment_type = 1
        val Sub_comment_type = 2
        val More_sub_comment_type = 3
        val EndView_type = 4
        val NullView_tyep = 5
    }

    data class AdapterData(val type: Int, val Data: Any? = null)
    interface ChangeListener {
        fun reply(item: Discuss, position: Int)
        fun getMore(item: Discuss)
        fun getSubMore(item: Discuss, position: Int)
        fun removeDiscuss()
    }


    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            Detail_type ->
                return DetailViewHolder(InflateView(parent, R.layout.item_activity_detail))
            Comment_type ->
                return CommentViewHolder(InflateView(parent, R.layout.item_activity_detail_comment))
            Sub_comment_type ->
                return SubCommentViewHolder(InflateView(parent, R.layout.item_activity_detail_sub_comment))
            More_sub_comment_type ->
                return MoreViewHoler(InflateView(parent, R.layout.item_activity_detail_more_comment))
            else ->
                return EndViewHolder(InflateView(parent, R.layout.end_view))
        }
    }

    private fun InflateView(parent: ViewGroup?, layout: Int) = LayoutInflater.from(parent?.context).inflate(layout, parent, false)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        when (holder) {
            is DetailViewHolder -> {
                holder.bindView(dataList[position].Data as RxServie.ActivityDetailBean)
            }
            is CommentViewHolder -> {
                holder.bindView(dataList[position].Data as Discuss, position)
            }
            is SubCommentViewHolder -> {
                holder.bindView(dataList[position].Data as Discuss)
            }
            is EndViewHolder -> {
                holder.bindView(dataList[position].type)
            }
            is MoreViewHoler -> {
                holder.bindView(dataList[position - 1].Data as Discuss, position)
            }
        }
        if (itemCount != 1 && position == itemCount - 1 && dataList[position].type != EndView_type) {
            for (i in position.downTo(0)) {
                if (dataList[i].type == Comment_type) {
                    mListener.getMore(dataList[i].Data as Discuss)
                    return
                }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return dataList[position].type
    }

    override fun getItemCount() = dataList.count()


    inner class DetailViewHolder(val item: View) : RecyclerView.ViewHolder(item) {
        fun bindView(data: RxServie.ActivityDetailBean) {
            with(data) {
                itemView.tv_name.text = name
                itemView.tv_create_date.text = create_date?.split(" ")?.get(0)
                itemView.tv_content.text = content
                itemView.tv_activity_time.text = start_date?.split(" ")?.get(0) + " ~ " + end_date?.split(" ")?.get(0)
                Picasso.with(item.context).load(Service.QiniuUrl + header_img).placeholder(R.drawable.user_place).into(itemView.user_icon)
                itemView.recyclerView_images.layoutManager = GridLayoutManager(item.context, 3)
                itemView.recyclerView_images.adapter = DetailImageAdapter(activityActivity, img_url?.split(";"))
                itemView.tv_num.text = discuss_count
            }
        }

    }

    inner class CommentViewHolder(val item: View) : RecyclerView.ViewHolder(item) {
        fun bindView(discuss: Discuss, position: Int) {
            with(discuss) {
                itemView.user_name.text = name
                itemView.tv_time.text = create_date?.toDate()
                itemView.tv_comment_content.text = content
//                itemView.comment_spaceview.visibility = if (discuss_content_count == "0" && position != itemCount - 2) View.VISIBLE else View.GONE
                itemView.comment_spaceview.visibility = View.GONE
                Picasso.with(item.context).load(Service.QiniuUrl + header_img).placeholder(R.drawable.user_place).into(itemView.discuss_user_icon)
                itemView.btn_comment.setOnClickListener {
                    mListener.reply(discuss, position)
                }
                item.setOnLongClickListener {
                    val menu = PopupMenu(activityActivity, it, Gravity.TOP)
                    menu.inflate(R.menu.remove_disucss)
                    menu.setOnMenuItemClickListener {
                        RxServie.removeDiscuss(id, {
                            if (it) {
                                mListener.removeDiscuss()
                            } else {
                                "删除评论失败！".showToast()
                            }
                        })
                        true
                    }
                    if (discuss.name == Storage.readUserInfo().nickname)
                        menu.show()
                    true
                }
            }
        }
    }

    inner class SubCommentViewHolder(val item: View) : RecyclerView.ViewHolder(item) {
        fun bindView(discuss: Discuss) {
            val text = "<font color='#297EF5'>${discuss.name}:</font>${discuss.content}"
            itemView.tv_sub_discuss_content.text = Html.fromHtml(text)
            item.setOnLongClickListener {
                val menu = PopupMenu(activityActivity, it, Gravity.CENTER + Gravity.TOP)
                menu.inflate(R.menu.remove_disucss)
                menu.setOnMenuItemClickListener {
                    RxServie.removeDiscuss(discuss.id, {
                        if (it) {
                            mListener.removeDiscuss()
                        } else {
                            "删除评论失败！".showToast()
                        }
                    })
                    true
                }
                if (discuss.name == Storage.readUserInfo().nickname)
                    menu.show()
                true
            }
        }
    }

    inner class MoreViewHoler(val item: View) : RecyclerView.ViewHolder(item) {
        fun bindView(discuss: Discuss, position: Int) {
            itemView.setOnClickListener {
                mListener.getSubMore(discuss, position)
            }
        }
    }

    class EndViewHolder(val item: View) : RecyclerView.ViewHolder(item) {
        fun bindView(type: Int) {
            when (type) {
                EndView_type -> {
                    itemView.endView.visibility = View.VISIBLE
                    itemView.nullView.visibility = View.GONE
                }
                NullView_tyep -> {
                    itemView.endView.visibility = View.GONE
                    itemView.nullView.visibility = View.VISIBLE
                }
            }
        }
    }

    class DetailImageAdapter(val activityActivity: ActivityDetailActivity, val data: List<String>?) : RecyclerView.Adapter<DetailImageAdapter.ImageViewHolder>() {

        override fun getItemCount(): Int {
            return if (data != null) data.size - 1 else 0

        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageViewHolder {
            val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_activity_detail_image, parent, false)
            return ImageViewHolder(view)
        }

        override fun onBindViewHolder(holder: ImageViewHolder?, position: Int) {
            if (data != null)
                holder?.setView(data[position], position)
        }

        inner class ImageViewHolder(val item: View) : RecyclerView.ViewHolder(item) {
            fun setView(url: String, position: Int) {
                val space = (item.context.resources.displayMetrics.density * 10).toInt()
                val w = (activityActivity.resources.displayMetrics.widthPixels / 3.0).toInt()
                val layout = FrameLayout.LayoutParams(w, w)
                itemView.imageView.layoutParams = layout
                if (position < 3) {
                    if (position % 3 == 2) itemView.frameLayout.setPadding(space, 0, space, 0) else itemView.frameLayout.setPadding(space, 0, 0, 0)
                } else {
                    if (position % 3 == 2) itemView.frameLayout.setPadding(space, space, space, 0) else itemView.frameLayout.setPadding(space, space, 0, 0)
                }
                itemView.imageView.setOnClickListener {
                    val option = ActivityOptionsCompat.makeSceneTransitionAnimation(activityActivity, it, "ImageView")
                    val intent = Intent(activityActivity, ReviewImageActivity::class.java)
                    intent.putExtra("image_url", url)
                    activityActivity.startActivity(intent, option.toBundle())
                }
                Picasso.with(item.context).load(Service.QiniuUrl + url).into(itemView.imageView)
            }
        }
    }

}