package com.zjgsu.jianshu.Adapter

import android.content.Context
import android.content.Intent
import android.media.Image
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.SaveListener
import com.bumptech.glide.Glide
import com.zjgsu.jianshu.*
import com.zjgsu.jianshu.Bmob.BookShelf
import kotlinx.android.synthetic.main.bookinfo_title.*

class BookRankAdapter(private val context: Context,var bookList: List<Book_rank>, val isHotList: Boolean, val userId: String) :
    RecyclerView.Adapter<BookRankAdapter.ViewHolder>() {
    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val bookrank_pic: ImageView = view.findViewById(R.id.bookrank_pic)
        val bookrank_intro: TextView = view.findViewById(R.id.bookrank_intro)
        val bookrank_name: TextView = view.findViewById(R.id.bookrank_name)
        val bookrank_desc: TextView = view.findViewById(R.id.bookrank_desc)
        val innerLinearLayout: LinearLayout = view.findViewById(R.id.bookrank_innerLinearLayout)
        val outerLinearLayout: LinearLayout = view.findViewById(R.id.bookrank_outerLinearLayout)
        val bookrank_author: TextView = view.findViewById(R.id.bookrank_author)
        val bookrank_icon: ImageView = view.findViewById(R.id.bookrank_icon)
        val bookrank_addbook: ImageView = view.findViewById(R.id.bookrank_addbook)
        val bookrank_add:TextView=view.findViewById(R.id.bookrank_add)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val book = bookList[position]
        holder.bookrank_name.text = book.name
        holder.bookrank_intro.text = book.intro
        val backgrounds = arrayOf(
            R.drawable.color_lightpurple, R.drawable.color_lightblue,
            R.drawable.color_lightgreen, R.drawable.color_flesh
        )
        holder.innerLinearLayout.setBackgroundResource(backgrounds[position % backgrounds.size])
        if (isHotList)
            holder.bookrank_desc.text = "在读人数：" + book.courtOfReaders
        else
            holder.bookrank_desc.text = "简书推荐值: " + book.score
        holder.bookrank_author.text = book.author
        when (position) {
            0 -> {
                holder.bookrank_icon.setImageResource(R.drawable.gold)
                holder.bookrank_icon.visibility = View.VISIBLE
            }
            1 -> {
                holder.bookrank_icon.setImageResource(R.drawable.silver)
                holder.bookrank_icon.visibility = View.VISIBLE
            }
            2 -> {
                holder.bookrank_icon.setImageResource(R.drawable.copper)
                holder.bookrank_icon.visibility = View.VISIBLE
            }
            else -> {
                holder.bookrank_icon.visibility = View.GONE
            }
        }

        Glide.with(holder.itemView.context)
            .load(book.picUrl) // 确保你的Book对象有正确的图片URL
            .placeholder(R.drawable.pre_load) // 可以设置一个占位图
            .error(R.drawable.fail_load) // 设置加载失败的图
            .into(holder.bookrank_pic)
        holder.outerLinearLayout.setOnClickListener {
            val intent = Intent(holder.itemView.context, BookInformationActivity::class.java)
            intent.putExtra("Book_name", book.name)
            if(isHotList)
                intent.putExtra("Source_Activity", HotBookActivity::class.java)
            else
                intent.putExtra("Source_Activity", GoodBookActivity::class.java)
            ContextCompat.startActivity(holder.itemView.context, intent, null)
        }
        holder.bookrank_addbook.setOnClickListener {
            val queryBookshelf = BmobQuery<BookShelf>()
            queryBookshelf.addWhereEqualTo("userid", userId)
            queryBookshelf.addWhereEqualTo("b_name", book.name)
            queryBookshelf.findObjects(object : FindListener<BookShelf>() {
                override fun done(bookshelfItems: MutableList<BookShelf>?, e: BmobException?) {
                    if (e == null && (bookshelfItems == null || bookshelfItems.isEmpty())) {
                        val bookshelfRecord = BookShelf()
                        bookshelfRecord.setb_name(book.name)
                        bookshelfRecord.setuserid(userId)
                        bookshelfRecord.setpicurl(book.picUrl)
                        bookshelfRecord.save(object : SaveListener<String>() {
                            override fun done(objectId: String?, saveException: BmobException?) {
                                if (saveException == null) {
                                    holder.bookrank_addbook.setImageResource(R.drawable.bookshelf2)
                                    Toast.makeText(
                                        context,
                                        "添加成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                } else {
                                    Log.e(
                                        "BookInfo",
                                        "Error adding book to bookshelf: ${saveException.message}"
                                    )
                                }
                            }
                        })
                    } else {
                        Toast.makeText(context, "该书已在您的书架中！", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
            })
        }
        fun judgeInBookshelf() {
            val queryBookshelf = BmobQuery<BookShelf>()
            queryBookshelf.addWhereEqualTo("userid", userId)
            queryBookshelf.addWhereEqualTo("b_name", book.name)
            queryBookshelf.findObjects(object : FindListener<BookShelf>() {
                override fun done(bookshelfItems: MutableList<BookShelf>?, e: BmobException?) {
                    if (e == null && bookshelfItems != null && bookshelfItems.isNotEmpty()) {
                        holder.bookrank_addbook.setImageResource(R.drawable.alreadyin)
                        holder.bookrank_add.text="已加入"
                    }
                }
            })
        }
        judgeInBookshelf()
    }

    override fun getItemCount() = bookList.size
}