package com.zjgsu.jianshu

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.bmob.v3.Bmob
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import com.zjgsu.jianshu.Adapter.BookRankAdapter
import com.zjgsu.jianshu.Bmob.Book_info_bmob
import com.zjgsu.jianshu.Book_rank
import com.zjgsu.jianshu.MainActivity
import com.zjgsu.jianshu.NavigationHelper
import com.zjgsu.jianshu.R
import kotlinx.android.synthetic.main.activity_bookrank.*

class GoodBookActivity : AppCompatActivity() {
    private var goodbookList=ArrayList<Book_rank>()
    lateinit var adapter: BookRankAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bookrank)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")//连接bmob
        val userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").toString() //全局范围内userid，登录的时候存进来
        adapter= BookRankAdapter(this,goodbookList,false,userId)
        bookrank_recyclerView.layoutManager=
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        bookrank_recyclerView.adapter=adapter
        bookrank_swipeRefresh.setOnRefreshListener {
            loadBookRanks()    //下拉刷新
        }
        loadBookRanks()
        bookrank_title.text="一周好评图书榜单"
        bookrank_subtitle.text="10本・ 9852人关注"
        returnTOCity()
    }
    private fun loadBookRanks(){
        val queryGoodBooks = BmobQuery<Book_info_bmob>()
        queryGoodBooks.findObjects(object : FindListener<Book_info_bmob>() {
            override fun done(books: List<Book_info_bmob>?, e: BmobException?) {
                if (e == null) {
                    bookrank_swipeRefresh.isRefreshing = false
                    // 清空之前的书籍列表
                    goodbookList.clear()
                    // 计算每本书的 good 比例，并构建 Book 对象加入列表
                    books?.let {
                        // 对书籍列表按照 good 比例进行排序
                        val sortedBooks = it.sortedByDescending { book ->
                            val total = book.tuijian + book.yiban + book.buxing
                            if (total > 0) {
                                book.tuijian.toDouble() / total.toDouble()  // 计算 good 的比例
                            } else {
                                0.0  // 如果总数为 0，比例设为 0
                            }
                        }
                        // 获取前三名书籍
                        val topThreeBooks = sortedBooks.take(10)
                        topThreeBooks.forEach { b ->
                            val tmp = b.tuijian + b.yiban + b.buxing
                            val scorePercentage = if (tmp > 0) {
                                (b.tuijian.toDouble() / tmp.toDouble()) * 100
                            } else {
                                0.0
                            }
                            val formattedScore = String.format("%.1f%%", scorePercentage)  // 将百分数格式化为带一位小数的字符串
                            val bookRank = Book_rank(
                                name = b.name,
                                picUrl = b.picture.url,
                                score = formattedScore,
                                courtOfReaders = b.countOfReaders,
                                author=b.author_name,
                                intro=b.introduce
                            )
                            goodbookList.add(bookRank)
                            adapter.notifyDataSetChanged()  // 确保在这里更新适配器
                        }
                    }
                } else {
                    // 处理错误情况
                    Toast.makeText(
                        this@GoodBookActivity,
                        "Failed to retrieve books: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })
    }
    private fun returnTOCity() {
        bookrank_return.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish() // 结束当前页面
        }
    }
}