package com.zjgsu.jianshu

import android.content.Context
import android.content.Intent
import android.util.Log
import cn.bmob.v3.Bmob
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.UpdateListener
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.bmob.v3.listener.SaveListener
import com.bumptech.glide.Glide
import com.zjgsu.jianshu.Adapter.GoodperceptionAdapter
import com.zjgsu.jianshu.Bmob.BookShelf
import com.zjgsu.jianshu.Bmob.Book_info_bmob
import com.zjgsu.jianshu.Bmob.Perception_bmob
import kotlinx.android.synthetic.main.activity_book_info.*
import kotlinx.android.synthetic.main.activity_sendspecific.*
import kotlinx.android.synthetic.main.bookinfo_title.*


class BookInformationActivity : AppCompatActivity() {
    private lateinit var adapter: GoodperceptionAdapter
    private val perceptionList = ArrayList<Perception>()
    private var isCommented = false
    private lateinit var bookName: String
    private lateinit var authorName: String
    private lateinit var userId:String
    private lateinit var picurl:String
    private var sourceActivityClass: Class<*>? = null
    private lateinit var bookInfoTextView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_book_info)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")
        bookinfo_swipeRefresh.setOnRefreshListener {
            loadBookInfo()   //下拉刷新
        }
        bookName = intent.getStringExtra("Book_name") ?: ""
        bookInfoTextView = findViewById(R.id.bookinfo_introduce)
        userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").toString()
        sourceActivityClass = intent.getSerializableExtra("Source_Activity") as? Class<*>
        loadPerceptions()
        setupRecyclerView()
        loadBookInfo()
        judgeInBookshelf()
        setClickListeners()
        judgeComment()
    }

    private fun loadPerceptions() {
        val queryPerception = BmobQuery<Perception_bmob>()
        queryPerception.addWhereEqualTo("b_name", bookName)  //查询指定书名的精彩点评
        queryPerception.findObjects(object : FindListener<Perception_bmob>() {
            override fun done(list: List<Perception_bmob>, e: BmobException?) {
                if (e == null) {
                    bookinfo_swipeRefresh.isRefreshing = false
                    list.forEach { perceptionList.add(Perception(it.objectId)) }
                    adapter.notifyDataSetChanged()
                } else {
                    Log.e("BookInfo", "Error loading perceptions: ${e.message}")
                }
            }
        })
    }

    private fun setupRecyclerView() {
            val layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        bookinfo_recyclerView.layoutManager = layoutManager
        adapter=GoodperceptionAdapter(perceptionList)
        bookinfo_recyclerView.adapter = adapter
    }

    private fun loadBookInfo() {
        val queryBook = BmobQuery<Book_info_bmob>()
        queryBook.addWhereEqualTo("name", bookName)
        queryBook.findObjects(object : FindListener<Book_info_bmob>() {
            override fun done(books: MutableList<Book_info_bmob>?, e: BmobException?) {
                if (e == null && books != null && books.isNotEmpty()) {
                    bookinfo_swipeRefresh.isRefreshing = false
                    val book = books[0]
                    loadBookCover(book.picture.url)
                    picurl=book.picture.url
                    if (book.buxing + book.tuijian + book.buxing != 0) {
                        var tuijian_res: Double = 0.0
                        tuijian_res = (book.tuijian) * 100.0 / (book.buxing + book.tuijian + book.yiban)
                        progressBar_henhao.progress =
                            book.tuijian * 100 / (book.buxing + book.tuijian + book.yiban)
                        progressBar_yiban.progress =
                            book.yiban * 100 / (book.buxing + book.tuijian + book.yiban)
                        progressBar_buxing.progress =
                            book.buxing * 100 / (book.buxing + book.tuijian + book.yiban)
                        val str: String = String.format("%.2f", tuijian_res)
                        textView10.text = "简书推荐值 " + str + "%"
                    }
                    updateBookRankings(book)
                    bookinfo_bookname.text = book.name
                    bookinfo_authorname.text = book.author_name
                    bookinfo_introduce.text=book.introduce
                    authorName = book.author_name
                    bookInfoTextView.text=book.introduce
                } else {
                    Log.e("BookInfo", "Error loading book info: ${e?.message}")
                }
            }
        })
    }

    private fun judgeInBookshelf() {
        val queryBookshelf = BmobQuery<BookShelf>()
        queryBookshelf.addWhereEqualTo("userid", userId)
        queryBookshelf.addWhereEqualTo("b_name", bookName)
        queryBookshelf.findObjects(object : FindListener<BookShelf>() {
            override fun done(bookshelfItems: MutableList<BookShelf>?, e: BmobException?) {
                if (e == null && bookshelfItems != null && bookshelfItems.isNotEmpty()) {
                    bookinfo_addBook.setImageResource(R.drawable.alreadyin)
                    bookinfo_mess.text="已加入"
                }
            }
        })
    }
    private fun showBookIntroDialog(bookIntroContent: String) {
        val builder = AlertDialog.Builder(this)
        val dialogView = layoutInflater.inflate(R.layout.bookintro_dialog, null)
        builder.setView(dialogView)
        val dialog = builder.create()
        dialogView.findViewById<TextView>(R.id.book_intro_content)?.text = bookIntroContent
        dialogView.findViewById<Button>(R.id.book_intro_close)?.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }

    private fun setClickListeners() {
        bookinfo_authorname.setOnClickListener {
            val intent = Intent(this, Author_introductionActivity::class.java)
            intent.putExtra("author_name", authorName)
            intent.putExtra("book_name",bookName)
            startActivity(intent)
        }
        //TODO:不一定回到MainActivity::class，后面还要在跳转前保存上一个页面
        bookinfo_return.setOnClickListener {
            if (sourceActivityClass != null) {
                // 返回到上一个页面
                val intent = Intent(this, sourceActivityClass!!)
                startActivity(intent)
            } else {
                // 如果没有来源页面信息,则返回到 MainActivity
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
            finish()
        }
        addBook2.setOnClickListener {
            addBookToBookshelf()
        }
        bookinfo_addBook.setOnClickListener {
            addBookToBookshelf()
        }
//TODO:BookIntroActivity要删
        bookinfo_img.setOnClickListener {
            val intent = Intent(this, BookIntroActivity::class.java)
            intent.putExtra("Book_name", bookName)
            startActivity(intent)
        }
        toBookshelf.setOnClickListener {
            val intent = Intent(this, BookShelfActivity::class.java)
            startActivity(intent)
        }
        setCommentClickListeners()
        bookinfo_introduce.setOnClickListener{
            showBookIntroDialog(bookInfoTextView.text.toString())
        }
        startToRead.setOnClickListener {
            val intent = Intent(this, BookIntroActivity::class.java)
            intent.putExtra("Book_name", bookName)
            startActivity(intent)
        }
    }
    //TODO:以后可以考虑再次点击这个“已加入的按钮”后，弹出一个对话框：是否将该书移除，然后将该书从书架中移除。而不是弹：该书已在您的书架中
    private fun addBookToBookshelf() {
        val queryBookshelf = BmobQuery<BookShelf>()
        queryBookshelf.addWhereEqualTo("userid", userId)
        queryBookshelf.addWhereEqualTo("b_name", bookName)
        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(bookName)
                    bookshelfRecord.setuserid(userId)
                    bookshelfRecord.setpicurl(picurl)
                    bookshelfRecord.save(object : SaveListener<String>() {
                        override fun done(objectId: String?, saveException: BmobException?) {
                            if (saveException == null) {
                                bookinfo_addBook.setImageResource(R.drawable.alreadyin)
                                bookinfo_mess.text="已加入"
                                Toast.makeText(
                                    this@BookInformationActivity,
                                    "添加成功",
                                    Toast.LENGTH_SHORT
                                ).show()
                            } else {
                                Log.e(
                                    "BookInfo",
                                    "Error adding book to bookshelf: ${saveException.message}"
                                )
                            }
                        }
                    })
                } else {
                    Toast.makeText(this@BookInformationActivity, "该书已在您的书架中！", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        })
    }

    private fun setCommentClickListeners() {
        if (!isCommented) {
            val commentClickListener = View.OnClickListener {
                val intent = Intent(this, SendSpecificActivity::class.java)
                intent.putExtra("bookname", bookName)
                when (it.id) {
                    R.id.b_henhao -> intent.putExtra("comment_rank", 1)
                    R.id.b_yiban -> intent.putExtra("comment_rank", 2)
                    R.id.b_buxing -> intent.putExtra("comment_rank", 3)
                }
                ContextCompat.startActivity(this, intent, null)
            }
            b_henhao.setOnClickListener(commentClickListener)
            b_yiban.setOnClickListener(commentClickListener)
            b_buxing.setOnClickListener(commentClickListener)
        } else {
            Toast.makeText(this, "你已点评过该书！", Toast.LENGTH_SHORT).show()
        }
    }

//    private fun updateBookComment(isRecommended: Boolean) {
//        if (!isCommented) {
//            isCommented = true
//            val queryBook = BmobQuery<Book_info_bmob>()
//            queryBook.addWhereEqualTo("name", bookName)
//            queryBook.findObjects(object : FindListener<Book_info_bmob>() {
//                override fun done(books: List<Book_info_bmob>, e: BmobException?) {
//                    if (e == null) {
//                        for (book in books) {
//                            updateBookRankings(book, isRecommended)
//                            b_henhao.setImageResource(R.drawable.recommend2)
//                        }
//                        Toast.makeText(this@BookInformationActivity, "评价成功！", Toast.LENGTH_LONG)
//                            .show()
//                    } else {
//                        Log.e("BookInfo", "Error updating book comment: ${e.message}")
//                    }
//                }
//            })
//        } else {
//            Toast.makeText(this, "仅能评价一次！", Toast.LENGTH_SHORT).show()
//        }
//    }

    private fun updateBookRankings(book: Book_info_bmob, isRecommended: Boolean = false) {
        if (isRecommended) {
            book.settuijian(book.tuijian + 1)
        } else {
            book.setyiban(book.yiban + 1)
            book.setbuxing(book.buxing + 1)
        }
        book.update(book.objectId, object : UpdateListener() {
            override fun done(e: BmobException?) {
                if (e != null) {
                    Log.e("BookInfo", "Error updating book rankings: ${e.message}")
                }
            }
        })
    }
    private fun judgeComment(){
        val query=BmobQuery<Perception_bmob>()
        query.addWhereEqualTo("userid",userId)
        query.addWhereEqualTo("b_name",bookName)
        query.findObjects(object : FindListener<Perception_bmob>() {
            override fun done(lists: List<Perception_bmob>, e: BmobException?) {
                if (e == null) {
                    if(lists.isNotEmpty()) {
                        isCommented=true
                        val Myperception = lists[0]
                        if (Myperception.evaluation == 1)
                            b_henhao.setImageResource(R.drawable.recommend2)
                        else if (Myperception.evaluation == 2)
                            b_yiban.setImageResource(R.drawable.normal2)
                        else if (Myperception.evaluation == 3)
                            b_buxing.setImageResource(R.drawable.bad2)
                    }
                } else {
                    Log.d("error", "error")
                }
            }
        })
    }
    private fun loadBookCover(coverUrl: String) {
        Glide.with(this) // 传入 Context
            .load(coverUrl) // 加载图片的 URL
            .placeholder(R.drawable.pre_load) // 设置占位图
            .error(R.drawable.fail_load) // 设置加载失败时显示的图片
            .into(bookinfo_img) // 将图片加载到指定的 ImageView 中
    }
}