package com.design.wallpapergallery.view

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.design.wallpapergallery.adapter.MoreAndSearchAdapter
import com.design.wallpapergallery.data.MainViewModel
import com.design.wallpapergallery.data.Photo
import com.design.wallpapergallery.databinding.ActivityTypeDescBinding
import com.design.wallpapergallery.listener.MainSecListener


class MorePhotoActivity : AppCompatActivity(),MainSecListener {
    private lateinit var binding:ActivityTypeDescBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter:MoreAndSearchAdapter
    private var currentTitleName: String = ""

    companion object{
        var titleName:String="name"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivityTypeDescBinding.inflate(layoutInflater)
        init()
        setContentView(binding.root)
    }

    private fun init(){
        showTPAD(this) { null }
        viewModel=ViewModelProvider(this)[MainViewModel::class.java]
        currentTitleName = intent?.getStringExtra(titleName) ?: "Default Title"
        // 保存标题到ViewModel
        viewModel.currentTitleName = currentTitleName

        // 设置标题 - 从ViewModel获取确保数据持久化
        binding.name.text = viewModel.currentTitleName ?: currentTitleName
        binding.searchPb.visibility= View.VISIBLE
        binding.imageBack.setOnClickListener { finish() }
        adapter=MoreAndSearchAdapter()
        adapter.setListener(this)
        binding.list.layoutManager=GridLayoutManager(this,2)
        binding.list.adapter=adapter
        viewModel.classificationList.observe(this) { list ->
            // 在这里处理返回的数据
            if(list.isNotEmpty()){
                updateUI(list)
            }
        }
        if(viewModel.classificationList.value.isNullOrEmpty()){
            Log.d("Therererer","startGet")
            viewModel.getClassificationList(currentTitleName)
        }
    }
    private fun updateUI(list: List<Photo>){
        Log.d("MorePhotoActivity","list size is"+list.size.toString())
        adapter.setList(list)
        binding.searchPb.visibility= View.GONE
        adapter.notifyDataSetChanged()
    }

    override fun inItemClick(paper: Photo) {
        showTPAD(this) {
            val intent= Intent(this,StartDownApplyActivity::class.java)
            intent.putExtra(StartDownApplyActivity.paperKey,paper)
            startActivity(intent)
        }
    }
}