package com.zjgsu.jianshu

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
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.BookShelf
import kotlinx.android.synthetic.main.activity_bookshelf.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_perception.*
import kotlinx.android.synthetic.main.bookshelf_item.*
import kotlinx.android.synthetic.main.expandable.*
import kotlin.concurrent.thread
import com.google.android.material.snackbar.Snackbar

import android.view.LayoutInflater
import android.view.View.OnLongClickListener

import android.view.ViewGroup

import android.widget.TextView

import androidx.recyclerview.widget.RecyclerView
import android.view.MotionEvent
import android.view.View.OnTouchListener
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import cn.bmob.v3.listener.UpdateListener
import kotlinx.android.synthetic.main.layout_bottom_navigation.*

class BookShelfActivity : AppCompatActivity() {
    val booklist = ArrayList<Book_Shelf>()
    lateinit var adapter:BookshelfAdapter
    lateinit var userId:String
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bookshelf)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")//连接bmob
        userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").toString()
        loadBookshelf()
        val layoutManager=GridLayoutManager(this,3)
        bookshelf_recyclerView.layoutManager=layoutManager
        adapter=BookshelfAdapter(this,booklist)
        bookshelf_recyclerView.adapter=adapter
        bookshelf_swipeRefresh.setOnRefreshListener {
            loadBookshelf()
        }
        setupBottomNavigation()
        select()
    }
    private fun loadBookshelf(){
        booklist.clear()
        val bmobQuery = BmobQuery<BookShelf>()
        bmobQuery.addWhereEqualTo("userid", userId)
        bmobQuery.findObjects(object : FindListener<BookShelf>() {
            override fun done(books: List<BookShelf>?, e: BmobException?) {
                bookshelf_swipeRefresh.isRefreshing = false
                if (e == null) {
                    booklist.clear()
                    books?.let {
                        booklist.addAll(it.map { b ->
                            val url = b.picurl?: "default_url_or_handling_case"
                            Book_Shelf(b.b_name,url)
                        })
                    }
                    booklist.add(Book_Shelf("添加", ""))
                    adapter.notifyDataSetChanged()
                }else {
                    Log.d("error", "error")
                }
            }
        })
    }
    private fun setupBottomNavigation() {
        bookshelf.setImageResource(R.drawable.bookshelf2)
        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)
        }
    }

    private fun select(){
        bookshelf_select.setOnClickListener{
            default_title.visibility=View.GONE
            selected_title.visibility = View.VISIBLE
            bookshelf_layout_bottom_navigation.visibility=View.GONE
            selected_bottom_navigation.visibility=View.VISIBLE
            adapter.toggleSelectMode()
        }
        bookshelf_cancel.setOnClickListener {
            default_title.visibility=View.VISIBLE
            selected_title.visibility = View.GONE
            bookshelf_layout_bottom_navigation.visibility=View.VISIBLE
            selected_bottom_navigation.visibility=View.GONE
            adapter.toggleSelectMode()
        }
        adapter.onSelectionChanged = { selectedCount ->
            select_books.text = if (selectedCount > 0) "已选择 $selectedCount 本书籍" else "选择书籍"
        }
    }
    fun onRemoveFromBookshelfClicked(view: View) {
        //TODO：目前是用消息弹窗的方式，其他方法：若没有选中书籍时，可以设置移除按钮不可选中
        if (adapter.selectedItems.isEmpty()) {
            // 如果没有选中图书,弹出提示并返回
            Toast.makeText(this, "请先选择要移除的图书", Toast.LENGTH_SHORT).show()
            return
        }
        adapter.selectedItems.toList().also { positionList ->
            // 创建并显示删除确认对话框
            val builder = AlertDialog.Builder(this)
            val dialogView = layoutInflater.inflate(R.layout.delete_dialog, null)
            builder.setView(dialogView)

            val dialog = builder.create()
            dialogView.findViewById<TextView>(R.id.dialog_message)?.text = "是否将《${booklist[positionList.first()].bkname}》移出书架?"
            dialogView.findViewById<Button>(R.id.dialog_cancel)?.setOnClickListener {
                dialog.dismiss()
            }
            dialogView.findViewById<Button>(R.id.dialog_remove)?.setOnClickListener {
                // 从 BookShelf 表中删除图书的逻辑
                positionList.sorted().reversed().forEach { position ->
                    val bmobQuery = BmobQuery<BookShelf>()
                    bmobQuery.addWhereEqualTo("userid", userId)
                    bmobQuery.addWhereEqualTo("b_name", booklist[position].bkname)
                    bmobQuery.findObjects(object : FindListener<BookShelf>() {
                        override fun done(books: List<BookShelf>?, e: BmobException?) {
                            if (e == null) {
                                books?.firstOrNull()?.also { book ->
                                    book.delete(object : UpdateListener() {
                                        override fun done(e: BmobException?) {
                                            if (e == null) {
                                                // 删除成功
                                                booklist.removeAt(position)
                                                adapter.selectedItems.remove(position)
                                                adapter.selectedItems.forEach { selectedPosition ->
                                                    if (selectedPosition > position) {
                                                        adapter.selectedItems.remove(selectedPosition)
                                                        adapter.selectedItems.add(selectedPosition - 1)
                                                    }
                                                }
                                                Toast.makeText(
                                                    this@BookShelfActivity,
                                                    "移除成功",
                                                    Toast.LENGTH_SHORT
                                                ).show()
                                                adapter.notifyDataSetChanged()
                                                adapter.onSelectionChanged?.invoke(adapter.selectedItems.size)
                                            } else {
                                                // 删除失败
                                            }
                                            dialog.dismiss()
                                        }
                                    })
                                }
                            } else {
                                // 查询失败
                                dialog.dismiss()
                            }
                        }
                    })
                }
            }

            dialog.show()
        }
    }
}