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.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.SaveListener
import com.zjgsu.jianshu.*
import com.zjgsu.jianshu.Adapter.CommentAdapter
import com.zjgsu.jianshu.Bmob.Book_info_bmob
import com.zjgsu.jianshu.Bmob.Comment_bmob
import com.zjgsu.jianshu.Bmob.Perception_bmob
import com.zjgsu.jianshu.Bmob.User_bmob
import kotlinx.android.synthetic.main.activity_perception_infomation.*
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class Perception_informationActivity:AppCompatActivity() {
    private lateinit var perceptionid:String
    private lateinit var bookName:String
    private val commentlist=ArrayList<Comment>()
    lateinit var userId:String
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_perception_infomation)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")//连接bmob
        userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").toString()
        perceptionid = intent.getStringExtra("PerceptionId").toString()
        Log.d("mytest",perceptionid)
        inits()
        val layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)//第一个参数是列数
        comment_recyclerview.layoutManager = layoutManager
        var adapter = CommentAdapter(commentlist)
        comment_recyclerview.adapter = adapter
        submitComment.setOnClickListener {
            val comment=Comment_bmob()
            comment.text=yourcomment.text.toString()
            comment.perceptionid=perceptionid
            comment.comment_personid= userId
            comment.save(object : SaveListener<String>() {
                override fun done(objectId: String?, e: BmobException?) {
                    if (e == null) {
                        Toast.makeText(
                            this@Perception_informationActivity,
                            "评论成功！",
                            Toast.LENGTH_SHORT
                        ).show()
                        yourcomment.text=null
                    } else {
                        Toast.makeText(
                            this@Perception_informationActivity,
                            "评论失败!",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })
        }
        inf_bookInf.setOnClickListener{
            val intent = Intent(this, BookInformationActivity::class.java)
            intent.putExtra("Book_name", bookName)
            startActivity(intent)
            finish()
        }
    }
    private fun inits(){
        val query = BmobQuery<Perception_bmob>()
        query.addWhereEqualTo("objectId",perceptionid)
        //加载用户头像
        query.findObjects(object : FindListener<Perception_bmob>() {
            override fun done(p0: MutableList<Perception_bmob>?, p1: BmobException?) {
                if (p1 == null) {
                    if (p0 != null && p0.size > 0) {
                        for (p in p0) {
                            //找发布用户
                            inf_textView_perception.text=p.perception
                            postTime.text="发表于 "+p.createdAt
                            val queryUser = BmobQuery<User_bmob>()
                            queryUser.findObjects(object : FindListener<User_bmob>() {
                                override fun done(list: List<User_bmob>, e: BmobException?) {
                                    if (e == null) {
                                        for (i in list) {
                                            if (p.userid.equals(i.objectId)) {
                                                inf_postPersonName.text=i.nickName
//                                                flag = true //找到
                                                Log.d("myLog", "find sucessflly")
                                                //加载图片
                                                object : Thread() {
                                                    override fun run() {
                                                        try {
                                                            val url = URL(i!!.face?.url)
                                                            val connection: HttpURLConnection =
                                                                url.openConnection() as HttpURLConnection
                                                            connection.setRequestMethod("GET")
                                                            connection.setConnectTimeout(3000)
                                                            val `in`: InputStream = connection.getInputStream()
                                                            val bitmap: Bitmap =
                                                                BitmapFactory.decodeStream(`in`)
                                                            inf_user_icon.setImageBitmap(bitmap)
                                                        } catch (e: Exception) {
                                                            e.printStackTrace()
                                                        }
                                                    }
                                                }.start()


                                            }
                                        }
                                    } else {
                                        Log.d("myLog", "error")
                                    }
                                }
                            })
                        }
                    }
                }
            }
        })
        //加载书籍封面
        query.findObjects(object : FindListener<Perception_bmob>() {
            override fun done(p0: MutableList<Perception_bmob>?, p1: BmobException?) {
                if (p1 == null) {
                    if (p0 != null && p0.size > 0) {
                        for (p in p0) {
                            Log.d("myLog", p.b_name)
                            bookName = p.b_name
                            inf_bookName.text = bookName
                            val queryBook = BmobQuery<Book_info_bmob>()
                            queryBook.findObjects(object : FindListener<Book_info_bmob>() {
                                override fun done(list: List<Book_info_bmob>, e: BmobException?) {
                                    if (e == null) {
                                        for (i in list) {
                                            if (p.b_name.equals(i.name)) {
                                                inf_bookAuthor.text =
                                                    i.author_name
                                                //加载图片
                                                object : Thread() {
                                                    override fun run() {
                                                        try {
                                                            val url = URL(i!!.picture?.url)
                                                            val connection: HttpURLConnection =
                                                                url.openConnection() as HttpURLConnection
                                                            connection.setRequestMethod("GET")
                                                            connection.setConnectTimeout(3000)
                                                            val `in`: InputStream =
                                                                connection.getInputStream()
                                                            val bitmap: Bitmap =
                                                                BitmapFactory.decodeStream(`in`)
                                                            inf_book_pic.setImageBitmap(
                                                                bitmap
                                                            )
                                                        } catch (e: Exception) {
                                                            e.printStackTrace()
                                                        }
                                                    }
                                                }.start()


                                            }
                                        }
                                    } else {
                                        Log.d("myLog", "error")
                                    }
                                }
                            })
                        }
                    }
                }
            }
        })
        val bmobquery=BmobQuery<Comment_bmob>()
        bmobquery.addWhereEqualTo("perceptionid",perceptionid)
        bmobquery.findObjects(object:FindListener<Comment_bmob>(){
          override fun done(list:List<Comment_bmob>,e:BmobException?){
              if(e==null){
                  var cnt=0
                  for(i in list){
                      cnt++
                      commentlist.add(Comment(i.objectId))
                      val adapter = CommentAdapter(commentlist)
                      comment_recyclerview.adapter = adapter
                  }
                  comment_cnt.text="评论  "+cnt.toString()
              }
          }
        })
    }
}