//package com.zjgsu.jianshu
//import android.content.ClipData
//import android.content.Intent
//import androidx.appcompat.app.AppCompatActivity
//import android.os.Bundle
//import android.text.TextUtils
//import android.util.Log
//import android.view.Menu
//import android.view.MenuItem
//import android.widget.Adapter
//import android.widget.SearchView
//import android.widget.Toast
//import androidx.core.view.GravityCompat
//import androidx.recyclerview.widget.StaggeredGridLayoutManager
//import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
//import cn.bmob.v3.Bmob
//import cn.bmob.v3.BmobQuery
//import cn.bmob.v3.exception.BmobException
//import cn.bmob.v3.listener.FindListener
//import kotlinx.android.synthetic.main.activity_main.*
//import kotlinx.android.synthetic.main.activity_xinli.*
//import java.io.BufferedReader
//import java.io.IOException
//import java.io.InputStream
//import java.io.InputStreamReader
//import java.lang.StringBuilder
//import kotlin.concurrent.thread
//
//var UserId: String = ""
//
//class MainActivity : AppCompatActivity() {
//    private var user_id: String = ""
//    private var bookList = ArrayList<Book>()
//    private var bookList1 = ArrayList<Book>()
//    private var bookList2 = ArrayList<Book>()
//    private var bookList3 = ArrayList<Book>()
//    public fun Search(query: String): ArrayList<Book> {
//        val bookList1 = ArrayList<Book>()
//        for (source in bookList) {
//            if (source.name.contains(query))
//                bookList1.add(
//                    Book(
//                        source.name,
//                        source.introduce,
//                        source.tuijian,
//                        source.yiban,
//                        source.buxing
//                    )
//                )
//        }
//        return bookList1
//    }
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main)
//        supportActionBar?.let {
//            it.setDisplayHomeAsUpEnabled(true)
//            it.setHomeAsUpIndicator(R.drawable.menu)
//        }
//        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")//连接bmob
//        UserId = intent.getStringExtra("userid").toString()
//        inits()
//        val layoutManager =
//            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)//第一个参数是列数
//        recyclerView.layoutManager = layoutManager
//        var adapter = BookAdapter(bookList)
//        recyclerView.adapter = adapter
//        swipeRefresh.setOnRefreshListener {
//            refreshBooks(adapter)
//        }
//        navView.setCheckedItem(R.id.goodbook)
//        navView.setNavigationItemSelectedListener {
//            val intentwenxue = Intent(this, WenXueActivity::class.java)
//            val intentguanli = Intent(this, guanliActivity::class.java)
//            val intentxinli = Intent(this, xinliActivity::class.java)
//            val intentkexue = Intent(this, kexueActivity::class.java)
//            val intentzhexue = Intent(this, zhexueActivity::class.java)
//            when (it.itemId) {
//                R.id.wenxue -> startActivity(intentwenxue)
//                R.id.guanli -> startActivity(intentguanli)
//                R.id.xinli -> startActivity(intentxinli)
//                R.id.zhexue -> startActivity(intentzhexue)
//                R.id.kexue -> startActivity(intentkexue)
//            }
//            drawerLayout.closeDrawers()
//            true
//        }
//        main_searchview.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
//            // 设置搜索文本监听{
//            override fun onQueryTextSubmit(query: String): Boolean { //搜索时触发事件
//                return false
//            }
//
//            override fun onQueryTextChange(newText: String): Boolean {
//                if (TextUtils.isEmpty(newText)) {
//                    bookList.clear()
//                    bookList.addAll(bookList2)
//                } else {
//                    bookList1.clear()
//                    bookList.clear()
//                    bookList1.addAll(bookList2)
//                    for (source in bookList1) {
//                        if (source.name.contains(newText)) {
//                            bookList.add(
//                                Book(
//                                    source.name,
//                                    source.introduce,
//                                    source.tuijian,
//                                    source.yiban,
//                                    source.buxing
//                                )
//                            )
//                        }
//                    }
//                    for (i in bookList)
//                        Log.d("zy123", i.name)
//                    bookList3.addAll(bookList)
//                    thread {
//                        Thread.sleep(2000)
//                        runOnUiThread {
//                            initBooks()
//                            adapter.notifyDataSetChanged()
//                        }
//                    }
//                }
//                return false
//            }
//        })
//        book_recommend.setOnClickListener {
//            val intent = Intent(this, MainActivity::class.java)
//            startActivity(intent)
//            finish()
//        }
//        book_bookshelf.setOnClickListener {
//            val intent = Intent(this, BookShelfActivity::class.java)
//            startActivity(intent)
//            finish()
//        }
//        reading_comprehension.setOnClickListener {
//            val intent = Intent(this, PerceptionActivity::class.java)
//            startActivity(intent)
//            finish()
//        }
//        self.setOnClickListener {
//            val intent = Intent(this, MyActivity::class.java)
//            startActivity(intent)
//            finish()
//        }
//    }
//
//    private fun refreshBooks(adapter: BookAdapter) {
//        thread {
//            Thread.sleep(2000)
//            runOnUiThread {
//                initBooks()
//                adapter.notifyDataSetChanged()
//                swipeRefresh.isRefreshing = false
//                Toast.makeText(this, "刷新成功！", Toast.LENGTH_SHORT).show()
//            }
//        }
//    }
//
//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        when (item.itemId) {
//            android.R.id.home -> drawerLayout.openDrawer(GravityCompat.START)
//        }
//        return true
//    }
//
//    private fun initBooks() {
//        if (bookList3.isNotEmpty()) {
//            bookList.clear()
//            bookList.addAll(bookList3)
//            val adapter = BookAdapter(bookList)
//            recyclerView.adapter = adapter
//            bookList3.clear()
//        } else {
//            bookList.clear()
//            val bmobQuery = BmobQuery<Book_bmob>()
//            bmobQuery.findObjects(object : FindListener<Book_bmob>() {
//                override fun done(list: List<Book_bmob>, e: BmobException?) {
//                    var cnt: Int = 0
//                    if (e == null) {
//                        for (i in list) {
//                            if (cnt < 15) {
//                                bookList.add(
//                                    Book(
//                                        i.name,
//                                        i.introduce,
//                                        i.tuijian,
//                                        i.yiban,
//                                        i.buxing
//                                    )
//                                )
//                                val adapter = BookAdapter(bookList)
//                                recyclerView.adapter = adapter
//                                cnt++
//                            }
//                        }
////                        bookList.sortBy { it.tuijian * 100 / (it.buxing + it.tuijian + it.buxing) }
//                    } else {
//                        Log.d("error", "error")
//                    }
//                }
//            })
//        }
//    }
//
//
//    private fun inits() {
////        initsIntroduction()
////        val books= mutableListOf(Book("围城","1111111111111",R.drawable.weicheng),Book("当尼采哭泣","2222222222",R.drawable.nicai),Book("台北人","333333333",R.drawable.taibei))
////        for(index in 0..2) {
////            bookList.add(books[index])
////            bookList2.add(books[index])
////            val adapter = BookAdapter(this@MainActivity, bookList)
////            recyclerView.adapter = adapter
////        }
//        val bmobQuery = BmobQuery<Book_bmob>()
//        bmobQuery.findObjects(object : FindListener<Book_bmob>() {
//            override fun done(list: List<Book_bmob>, e: BmobException?) {
//                var cnt: Int = 0
//                if (e == null) {
//                    for (i in list) {
//                        if (cnt < 15) {
//                            bookList.add(Book(i.name, i.introduce, i.tuijian, i.yiban, i.buxing))
//                            bookList2.add(Book(i.name, i.introduce, i.tuijian, i.yiban, i.buxing))
//                            val adapter = BookAdapter(bookList)
//                            recyclerView.adapter = adapter
//                            cnt++
//                        }
//                    }
////                    bookList.add(Book("www","www",11,12,13))
//                } else {
//                    Log.d("error", "error")
//                }
//            }
//        })
//    }
//}


package com.zjgsu.jianshu

import android.app.Person
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout
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.Bmob.Book_bmob
import com.zjgsu.jianshu.Bmob.Book_inf_bmob
import com.zjgsu.jianshu.Bmob.User_bmob
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_bottom_navigation.*

var UserId: String = ""
class MainActivity : AppCompatActivity() {
    private lateinit var adapter: BookAdapter
    private var bookList = ArrayList<Book>()
    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)
        recyclerView.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        recyclerView.adapter = adapter

        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.goodbook)
        navView.setNavigationItemSelectedListener { menuItem ->
            startActivity(Intent(this, when(menuItem.itemId) {
                R.id.wenxue -> WenXueActivity::class.java
                R.id.guanli -> guanliActivity::class.java
                R.id.xinli -> xinliActivity::class.java
                R.id.zhexue -> zhexueActivity::class.java
                R.id.kexue -> kexueActivity::class.java
                else -> MainActivity::class.java
            }))
            drawerLayout.closeDrawers()
            true
        }

        loadBooks()
        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 setupBottomNavigation() {
        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)
    }
}

