package com.zjgsu.jianshu.Activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
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 cn.bmob.v3.listener.QueryListener
import cn.bmob.v3.listener.SaveListener
import com.bumptech.glide.Glide
import com.zjgsu.jianshu.*
import com.zjgsu.jianshu.Bmob.Book_info_bmob
import com.zjgsu.jianshu.Bmob.Perception_bmob
import com.zjgsu.jianshu.Bmob.User_bmob
import kotlinx.android.synthetic.main.activity_book_info.*
import kotlinx.android.synthetic.main.activity_sendperception.*
import kotlinx.android.synthetic.main.activity_sendspecific.*
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class sendPerceptionActivity:AppCompatActivity() {
    private var bookList = ArrayList<Book_Shelf>()
    lateinit var userId:String
    private lateinit var adapter: send_perceptionAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sendperception)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")//连接bmob
        userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").toString()
        mycontent.requestFocus()
        // 弹出软键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mycontent, InputMethodManager.SHOW_IMPLICIT)
        // 防止自动弹出软键盘时页面被顶起
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        adapter = send_perceptionAdapter(bookList)
        val layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)//第一个参数是列数
        send_recyclerview.layoutManager = layoutManager
        send_recyclerview.adapter = adapter
        inits()
        send_return.setOnClickListener {
            val intent= Intent(this,PerceptionActivity::class.java)
            startActivity(intent)
            finish()
        }
        submit.setOnClickListener {
            if(selectedBook.equals("")){
                Toast.makeText(this,"请选择一本书！",Toast.LENGTH_SHORT).show()
            }
            else {
                val perception = Perception_bmob()
                perception.perception = mycontent.text.toString()
                perception.userid = userId
                perception.b_name = selectedBook
                perception.save(object : SaveListener<String>() {
                    override fun done(objectId: String?, e: BmobException?) {
                        if (e == null) {
                            Toast.makeText(
                                this@sendPerceptionActivity, "发布成功！",
                                Toast.LENGTH_SHORT
                            ).show()
                            val intent =
                                Intent(this@sendPerceptionActivity, PerceptionActivity::class.java)
                            startActivity(intent)
                            finish()
                        } else {
                            Toast.makeText(
                                this@sendPerceptionActivity,
                                "发布失败" + e.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                })
            }
        }
    }
    private fun inits(){
        val bmobQuery = BmobQuery<Book_info_bmob>()
        bmobQuery.findObjects(object : FindListener<Book_info_bmob>() {
            override fun done(lists: List<Book_info_bmob>, e: BmobException?) {
                if (e == null) {
                    bookList.clear()
                    lists?.let {
                        bookList.addAll(it.map { b ->
                            // 使用安全调用和Elvis操作符提供默认值或进行错误处理
                            val url = b.picture?.url ?: "default_url_or_handling_case"
                            Book_Shelf(b.name,url)
                        })
                    }
                    adapter.notifyDataSetChanged()
                } else {
                    Log.d("error", "error")
                }
            }
        })
        val queryUser = BmobQuery<User_bmob>()
        queryUser.getObject(userId, object : QueryListener<User_bmob>() {
            override fun done(user: User_bmob?, e: BmobException?) {
                if (e == null) {
                    user?.let {
                        Glide.with(this@sendPerceptionActivity) // 传入 Context
                            .load(it.face.url) // 加载图片的 URL
                            .placeholder(R.drawable.pre_load) // 设置占位图
                            .error(R.drawable.fail_load) // 设置加载失败时显示的图片
                            .into(send_avatar) // 将图片加载到指定的 ImageView 中
                    }
                } else {
                    Log.e("QueryUser", e.toString())
                }
            }
        })
    }
}