package com.zjgsu.jianshu

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import android.widget.SearchView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
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.BillboardAdapter
import com.zjgsu.jianshu.Bmob.Book_bmob
import com.zjgsu.jianshu.Bmob.Book_info_bmob
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_bottom_navigation.*

class MainActivity : AppCompatActivity() {
    private lateinit var adapter: BookAdapter
    private lateinit var billboardAdapter: BillboardAdapter
    private var bookList = ArrayList<Book>()
    private var listOfBookRankList: MutableList<ArrayList<Book_rank>> = mutableListOf()
    private var hotbookList=ArrayList<Book_rank>()
    private var goodbookList=ArrayList<Book_rank>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.menu)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")
        adapter = BookAdapter(bookList)
//        val userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "") //全局范围内userid，登录的时候存进来
//        Log.d("LoginActivity", "User ID: $userId")
        recyclerView.layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        recyclerView.adapter = adapter

        billboardAdapter= BillboardAdapter(listOfBookRankList)
        horizontal_recycler_view.layoutManager=
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
        horizontal_recycler_view.adapter=billboardAdapter
        swipeRefresh.setOnRefreshListener {
            loadBooks()    //下拉刷新
        }
        main_searchview.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean = false

            override fun onQueryTextChange(newText: String): Boolean {
                val filteredList = if (TextUtils.isEmpty(newText)) {
                    bookList
                } else {
                    bookList.filter { it.name.contains(newText) }
                }
                adapter.updateBooks(filteredList)     //搜索框刷新
                return true
            }
        })

        navView.setCheckedItem(R.id.recommend)
        navView.setNavigationItemSelectedListener { menuItem ->
            startActivity(
                Intent(
                    this, when (menuItem.itemId) {
                        R.id.literature -> LiteratureActivity::class.java
                        R.id.management -> ManagementActivity::class.java
                        R.id.psychology -> PsychologyActivity::class.java
                        R.id.philosophy -> PhilosophyActivity::class.java
                        R.id.science -> ScienceActivity::class.java
                        else -> MainActivity::class.java
                    }
                )
            )
            drawerLayout.closeDrawers()
            true
        }
        loadBooks()
        loadBookRanks()
        setupBottomNavigation()
    }

    private fun loadBooks() {
        val query = BmobQuery<Book_bmob>()
        query.findObjects(object : FindListener<Book_bmob>() {
            override fun done(books: List<Book_bmob>?, e: BmobException?) {
                swipeRefresh.isRefreshing = false
                if (e == null) {
                    bookList.clear()
                    books?.let {
                        bookList.addAll(it.map { b ->
                            // 使用安全调用和Elvis操作符提供默认值或进行错误处理
                            val url = b.picture?.url ?: "default_url_or_handling_case"
                            Book(b.name, b.introduce, url)
                        })
                    }
                    adapter.notifyDataSetChanged()
                } else {
                    Toast.makeText(
                        this@MainActivity,
                        "Failed to retrieve books: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })
    }
    private fun loadBookRanks(){
        val queryHotBooks = BmobQuery<Book_info_bmob>()
        queryHotBooks.order("-countOfReaders") // 根据 countOfReaders 降序排序
        queryHotBooks.setLimit(3) // 限制查询结果的数量为3
        queryHotBooks.findObjects(object : FindListener<Book_info_bmob>() {
            override fun done(books: List<Book_info_bmob>?, e: BmobException?) {
                if (e == null) {
                    // 检查 books 是否非空
                    if (books != null && books.isNotEmpty()) {
                        hotbookList.clear() // 清空当前列表
                        // 遍历 books 并转换为 Book_rank 类型后添加到列表
                        books.forEach { b ->
                            val bookRank = Book_rank(
                                name = b.name,
                                picUrl = b.picture.url,
                                score="0.0",
                                courtOfReaders = b.countOfReaders,
                                author=b.author_name,
                                intro=""
                            )
                            hotbookList.add(bookRank)
                        }
                        listOfBookRankList.add(hotbookList)
                        billboardAdapter.notifyDataSetChanged()  // 确保在这里更新适配器
                    }
                } else {
                    // 处理错误情况
                    Toast.makeText(
                        this@MainActivity,
                        "Failed to retrieve books: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })
        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) {
                    // 清空之前的书籍列表
                    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(3)
                        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=""
                            )
                            goodbookList.add(bookRank)
                        }
                        listOfBookRankList.add(goodbookList)
                        billboardAdapter.notifyDataSetChanged()  // 确保在这里更新适配器
                    }
                } else {
                    // 处理错误情况
                    Toast.makeText(
                        this@MainActivity,
                        "Failed to retrieve books: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })

    }
    private fun setupBottomNavigation() {
        bookcity.setImageResource(R.drawable.bookcity2)
        bookcity.setOnClickListener {
            NavigationHelper.navigateTo(this, MainActivity::class.java)
        }
        bookshelf.setOnClickListener {
            NavigationHelper.navigateTo(this, BookShelfActivity::class.java)
        }
        reading_comprehension.setOnClickListener {
            NavigationHelper.navigateTo(this, PerceptionActivity::class.java)
        }
        homepage.setOnClickListener {
            NavigationHelper.navigateTo(this, MyActivity::class.java)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            drawerLayout.openDrawer(GravityCompat.START)
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}

