package com.example.myapplication.ui.home

import android.content.Intent
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.widget.HorizontalScrollView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.myapplication.ImeGuideActivity
import com.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.listByTagWithNotLogin
import com.example.myapplication.network.PersonaClick
import com.example.myapplication.utils.EncryptedSharedPreferencesUtil
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.card.MaterialCardView
import kotlinx.coroutines.launch
import kotlin.math.abs
import com.example.myapplication.network.AddPersonaClick

class HomeFragment : Fragment() {

    private lateinit var bottomSheet: MaterialCardView
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<MaterialCardView>
    private lateinit var scrim: View
    private lateinit var viewPager: ViewPager2
    private lateinit var tagContainer: LinearLayout
    private lateinit var tagScroll: HorizontalScrollView
    private lateinit var header: View
    private lateinit var tabList1: TextView
    private lateinit var tabList2: TextView
    private lateinit var backgroundImage: ImageView
    private var preloadJob: kotlinx.coroutines.Job? = null
    private var allPersonaCache: List<listByTagWithNotLogin> = emptyList()
    private val sharedPool = RecyclerView.RecycledViewPool()

    private var parentWidth = 0
    private var parentHeight = 0

    // 你点了哪个 tag（列表二）
    private var clickedTagId: Int? = null

    // ✅ 列表二：每个 tagId 对应一份 persona 数据，避免串页
    private val personaCache = mutableMapOf<Int, List<listByTagWithNotLogin>>()

    data class Tag(val id: Int, val tagName: String)

    private val tags = mutableListOf<Tag>()

    private val dragToCloseThreshold by lazy {
        val dp = 40f
        (dp * resources.displayMetrics.density)
    }

    private val list1Adapter: List1Adapter by lazy {
        List1Adapter { item: String ->
            Log.d("HomeFragment", "list1 click: $item")
        }
    }

    override fun onDestroyView() {
        preloadJob?.cancel()
        pageChangeCallback?.let { viewPager.unregisterOnPageChangeCallback(it) }
        pageChangeCallback = null
        sheetAdapter = null
        super.onDestroyView()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 充值按钮点击
        view.findViewById<View>(R.id.rechargeButton).setOnClickListener {
            findNavController().navigate(R.id.action_global_rechargeFragment)
        }

        // 输入法激活跳转
        view.findViewById<ImageView>(R.id.floatingImage).setOnClickListener {
            if (isAdded) {
                startActivity(Intent(requireActivity(), ImeGuideActivity::class.java))
            }
        }

        scrim = view.findViewById(R.id.view_scrim)
        bottomSheet = view.findViewById(R.id.bottomSheet)
        tagContainer = view.findViewById(R.id.tagContainer)
        tagScroll = view.findViewById(R.id.tagScroll)
        header = view.findViewById(R.id.bottomSheetHeader)
        tabList1 = view.findViewById(R.id.tab_list1)
        tabList2 = view.findViewById(R.id.tab_list2)
        viewPager = view.findViewById(R.id.viewPager)
        viewPager.isSaveEnabled = false
        backgroundImage = bottomSheet.findViewById(R.id.backgroundImage)
        val root = view.findViewById<CoordinatorLayout>(R.id.rootCoordinator)
        val floatingImage = view.findViewById<ImageView>(R.id.floatingImage)

        root.post {
            parentWidth = root.width
            parentHeight = root.height
        }

        initDrag(floatingImage, root)
        setupBottomSheet(view)
        setupTopTabs()

        //  先把 ViewPager / Tags 初始化为空（避免你下面网络回来前被调用多次）
        setupViewPager()
        setupTags()

        //刚进来强制显示列表1
        viewPager.setCurrentItem(0, false)
        updateTabsAndTags(0)

        //  加载标签列表（列表一）
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val list = fetchAllPersonaList()
                allPersonaCache = list
                viewPager.adapter?.notifyItemChanged(0) // 只刷新第一页
            } catch (e: Exception) {
                Log.e("1314520-HomeFragment", "获取列表一失败", e)
            }
        }
        //  拉标签 + 默认加载第一个 tag 的 persona（列表二第一个页）
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val response = RetrofitClient.apiService.tagList()
                tags.clear()
                response.data?.let { networkTags ->
                    tags.addAll(networkTags.map { Tag(it.id, it.tagName) })
                }
                // 刷新：页数和标签栏
                setupViewPager()
                setupTags()
                startPreloadAllTags()
            } catch (e: Exception) {
                Log.e("1314520-HomeFragment", "获取标签失败", e)
            }
        }
    }

    // ---------------- 拖拽效果 ----------------
    private fun initDrag(target: View, parent: ViewGroup) {
        var dX = 0f
        var dY = 0f
        var lastRawX = 0f
        var lastRawY = 0f
        var isDragging = false

        val touchSlop = ViewConfiguration.get(requireContext()).scaledTouchSlop

        target.setOnTouchListener { v, event ->
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    parent.requestDisallowInterceptTouchEvent(true)
                    if (::bottomSheetBehavior.isInitialized) bottomSheetBehavior.isDraggable = false

                    dX = v.x - event.rawX
                    dY = v.y - event.rawY
                    lastRawX = event.rawX
                    lastRawY = event.rawY
                    isDragging = false
                    true
                }

                MotionEvent.ACTION_MOVE -> {
                    val dxMove = event.rawX - lastRawX
                    val dyMove = event.rawY - lastRawY
                    if (!isDragging && (abs(dxMove) > touchSlop || abs(dyMove) > touchSlop)) {
                        isDragging = true
                    }

                    if (isDragging) {
                        var newX = event.rawX + dX
                        var newY = event.rawY + dY

                        val maxX = parentWidth - v.width
                        val maxY = parentHeight - v.height

                        newX = newX.coerceIn(0f, maxX.toFloat())
                        newY = newY.coerceIn(0f, maxY.toFloat())

                        v.x = newX
                        v.y = newY
                    }

                    lastRawX = event.rawX
                    lastRawY = event.rawY
                    true
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    parent.requestDisallowInterceptTouchEvent(false)
                    if (::bottomSheetBehavior.isInitialized) bottomSheetBehavior.isDraggable = true

                    if (!isDragging) v.performClick()
                    snapToEdge(v)
                    true
                }

                else -> false
            }
        }
    }

    private fun snapToEdge(v: View) {
        if (parentWidth == 0 || parentHeight == 0) return

        val centerX = v.x + v.width / 2f
        val toLeft = centerX < parentWidth / 2f

        val targetX = if (toLeft) 0f else (parentWidth - v.width).toFloat()
        val minTop = 0f
        val maxBottom = (parentHeight - v.height).toFloat()
        val targetY = v.y.coerceIn(minTop, maxBottom)

        v.animate().x(targetX).y(targetY).setDuration(200).start()
    }

    // ---------------- BottomSheet 行为 ----------------
    private fun setupBottomSheet(root: View) {
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)

        bottomSheetBehavior.isDraggable = true
        bottomSheetBehavior.isHideable = false
        bottomSheetBehavior.isFitToContents = false
        bottomSheetBehavior.halfExpandedRatio = 0.7f

        root.post {
            val coordinatorHeight = root.height - 40
            val button = root.findViewById<View>(R.id.rechargeButton)
            val peek = (coordinatorHeight - button.bottom).coerceAtLeast(200)
            bottomSheetBehavior.peekHeight = peek
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }

        bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                scrim.isVisible = newState != BottomSheetBehavior.STATE_COLLAPSED
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                if (slideOffset >= 0f) scrim.alpha = slideOffset.coerceIn(0f, 1f)
            }
        })

        scrim.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }

        scrim.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_MOVE) {
                bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                true
            } else false
        }

        header.setOnClickListener {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED ->
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED

                BottomSheetBehavior.STATE_HALF_EXPANDED,
                BottomSheetBehavior.STATE_EXPANDED ->
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

                else -> {}
            }
        }
    }

    // ---------------- ViewPager2 + Tabs ----------------
    private var sheetAdapter: SheetPagerAdapter? = null
    private var pageChangeCallback: ViewPager2.OnPageChangeCallback? = null

    private fun setupViewPager() {
        if (sheetAdapter == null) {
            sheetAdapter = SheetPagerAdapter(1 + tags.size)
            viewPager.adapter = sheetAdapter
    
            pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    updateTabsAndTags(position)
                }
            }
            viewPager.registerOnPageChangeCallback(pageChangeCallback!!)
        } else {
            // tags 数量变了，只更新 pageCount 并刷新一次即可
            sheetAdapter!!.updatePageCount(1 + tags.size)
        }
    }
    

    private fun startPreloadAllTags() {
        preloadJob?.cancel()
    
        // 限制并发，避免一下子打爆网络/主线程调度抖动
        val semaphore = kotlinx.coroutines.sync.Semaphore(permits = 2)
    
        preloadJob = viewLifecycleOwner.lifecycleScope.launch {
            // tags 还没拿到就别跑
            if (tags.isEmpty()) return@launch
    
            // 逐个 tag 预拉取（并发=2）
            tags.forEachIndexed { index, tag ->
                // 已经有缓存就跳过
                if (personaCache.containsKey(tag.id)) return@forEachIndexed
                launch {
                    semaphore.acquire()
                    try {
                        val list = fetchPersonaByTag(tag.id)
                        personaCache[tag.id] = list
                
                        val pagePos = 1 + index
                        kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                            viewPager.adapter?.notifyItemChanged(pagePos)
                        }
                    } finally {
                        semaphore.release()
                    }
                }
            }
        }
    }
    

    private fun setupTopTabs() {
        tabList1.setOnClickListener { viewPager.currentItem = 0 }
        tabList2.setOnClickListener {
            // 没有标签就别切
            if (tags.isNotEmpty()) viewPager.currentItem = 1
        }
    }

    private fun setupTags() {
        tagContainer.removeAllViews()

        tags.forEachIndexed { index, tag ->
            val tv = layoutInflater.inflate(R.layout.item_tag, tagContainer, false) as TextView
            tv.text = tag.tagName

            tv.setOnClickListener {
                clickedTagId = tag.id
                val pagePos = 1 + index
            
                // ✅ 先切页：用户体感立刻响应
                viewPager.setCurrentItem(pagePos, true)
            
                // ✅ 有缓存就不阻塞（可选：同时后台刷新）
                val cached = personaCache[tag.id]
                if (cached != null) {
                    viewPager.adapter?.notifyItemChanged(pagePos)
                    return@setOnClickListener
                }
            
                // ✅ 没缓存：页内显示 loading（你 onBind 已经处理 cached==null 的 loading）
                viewPager.adapter?.notifyItemChanged(pagePos)
            
                // 后台拉取，回来只刷新这一页
                viewLifecycleOwner.lifecycleScope.launch {
                    val list = fetchPersonaByTag(tag.id)
                    personaCache[tag.id] = list
                    viewPager.adapter?.notifyItemChanged(pagePos) // ✅ 只刷新这一页
                }
            }
            

            tagContainer.addView(tv)
        }

        tagScroll.isVisible = false
    }

    private fun updateTabsAndTags(position: Int) {
        if (position == 0) {
            tabList1.setTextColor(requireContext().getColor(R.color.black))
            tabList2.setTextColor(requireContext().getColor(R.color.light_black))
            tagScroll.isVisible = false
            fadeImage(backgroundImage, R.drawable.option_background)
        } else {
            tabList1.setTextColor(requireContext().getColor(R.color.light_black))
            tabList2.setTextColor(requireContext().getColor(R.color.black))
            tagScroll.isVisible = true
            fadeImage(backgroundImage, R.drawable.option_background_two)

            val tagIndex = position - 1
            highlightTag(tagIndex)
        }
    }

    private fun fadeImage(imageView: ImageView, newImageRes: Int) {
        val oldDrawable = imageView.drawable
        val newDrawable = ContextCompat.getDrawable(requireContext(), newImageRes) ?: return

        if (oldDrawable == null) {
            imageView.setImageDrawable(newDrawable)
            return
        }

        val transitionDrawable = TransitionDrawable(arrayOf(oldDrawable, newDrawable)).apply {
            isCrossFadeEnabled = true
        }
        imageView.setImageDrawable(transitionDrawable)
        transitionDrawable.startTransition(300)
    }
    
    private fun highlightTag(index: Int) {
        for (i in 0 until tagContainer.childCount) {
            val child = tagContainer.getChildAt(i) as TextView
            if (i == index) {
                child.setBackgroundResource(R.drawable.tag_selected_bg)
                child.setTextColor(requireContext().getColor(android.R.color.white))
                tagScroll.post {
                    val scrollViewWidth = tagScroll.width
                    val childCenter = child.left + child.width / 2
                    val targetScrollX = childCenter - scrollViewWidth / 2
                    tagScroll.smoothScrollTo(targetScrollX.coerceAtLeast(0), 0)
                }
            } else {
                child.setBackgroundResource(R.drawable.tag_unselected_bg)
                child.setTextColor(requireContext().getColor(R.color.light_black))
            }
        }
    }

    // ---------------- ViewPager Adapter ----------------
    inner class SheetPagerAdapter(
        private var pageCount: Int
    ) : RecyclerView.Adapter<SheetPagerAdapter.PageViewHolder>() {
    
        inner class PageViewHolder(val root: View) : RecyclerView.ViewHolder(root)
    
        fun updatePageCount(newCount: Int) {
            pageCount = newCount
            notifyDataSetChanged()
        }
    
        override fun getItemViewType(position: Int): Int = if (position == 0) 0 else 1
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
            val layoutId = if (viewType == 0) {
                R.layout.bottom_page_list1
            } else {
                R.layout.bottom_page_list2
            }
            val root = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
            return PageViewHolder(root)
        }
    
        override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
            val root = holder.root
    
            if (position == 0) {
                renderList1(root, allPersonaCache)
            } else {
                val rv2 = root.findViewById<RecyclerView>(R.id.recyclerView)
                val loadingView = root.findViewById<View>(R.id.loadingView)
    
                rv2.setHasFixedSize(true)
                rv2.itemAnimator = null
                rv2.isNestedScrollingEnabled = false
    
                var adapter = rv2.adapter as? PersonaAdapter
                if (adapter == null) {
                    adapter = PersonaAdapter { click ->
                        when (click) {
                            is PersonaClick.Item -> {
                                val id = click.persona.id
                                PersonaDetailDialogFragment
                                    .newInstance(id)
                                    .show(childFragmentManager, "persona_detail")
                            }
                            is PersonaClick.Add -> {
                                lifecycleScope.launch {
                                    if (click.persona.added == true) {
                                        click.persona.id?.let { id ->
                                            RetrofitClient.apiService.delUserCharacter(id.toInt())
                                        }
                                    } else {
                                        val req = AddPersonaClick(
                                            characterId = click.persona.id?.toInt() ?: 0,
                                            emoji = click.persona.emoji ?: ""
                                        )
                                        RetrofitClient.apiService.addUserCharacter(req)
                                    }
                                }
                            }
                        }
                    }
                    rv2.layoutManager = GridLayoutManager(root.context, 2)
                    rv2.adapter = adapter
                }
    
                val tagIndex = position - 1
                if (tagIndex !in tags.indices) {
                    loadingView.isVisible = false
                    adapter.submitList(emptyList())
                    return
                }
    
                val tagId = tags[tagIndex].id
                val cached = personaCache[tagId]
    
                if (cached == null) {
                    loadingView.isVisible = true
                    adapter.submitList(emptyList())
                } else {
                    loadingView.isVisible = false
                    adapter.submitList(cached)
                }
            }
        }
    
        override fun getItemCount(): Int = pageCount
    }
    

    // 通过 tagIndex 取出该页要显示的数据
    private fun getPersonaListByTagIndex(tagIndex: Int): List<listByTagWithNotLogin> {
        if (tagIndex !in tags.indices) return emptyList()
        val tagId = tags[tagIndex].id
        return personaCache[tagId] ?: emptyList()
    }

    private fun renderList1(root: View, list: List<listByTagWithNotLogin>) {
        // 1) 排序：rank 小的排前面
        val sorted = list.sortedBy { it.rank ?: Int.MAX_VALUE }
    
        val top3 = sorted.take(3)
        val others = if (sorted.size > 3) sorted.drop(3) else emptyList()
    
        // 2) 绑定前三名（注意：你的 UI 排列是：第二/第一/第三）
        bindTopItem(root,
            avatarId = R.id.avatar_first,
            nameId = R.id.name_first,
            addBtnId = R.id.btn_add_first,
            container = R.id.container_first,
            item = top3.getOrNull(0) // rank 最小 = 第一名
        )
    
        bindTopItem(root,
            avatarId = R.id.avatar_second,
            nameId = R.id.name_second,
            addBtnId = R.id.btn_add_second,
            container = R.id.container_second,
            item = top3.getOrNull(1) // 第二名
        )
    
        bindTopItem(root,
            avatarId = R.id.avatar_third,
            nameId = R.id.name_third,
            addBtnId = R.id.btn_add_third,
            container = R.id.container_third,
            item = top3.getOrNull(2) // 第三名
        )
    
        // 3) 渲染后面的内容卡片
        val container = root.findViewById<LinearLayout>(R.id.container_others)
        container.removeAllViews()
    
        val inflater = LayoutInflater.from(root.context)
        others.forEach { p ->
            val itemView = inflater.inflate(R.layout.item_rank_other, container, false)


    
            itemView.findViewById<TextView>(R.id.tv_rank).text = (p.rank ?: "--").toString()
            itemView.findViewById<TextView>(R.id.tv_name).text = p.characterName ?: ""
            itemView.findViewById<TextView>(R.id.tv_desc).text = p.characterBackground ?: ""
    
            // 头像
            val iv = itemView.findViewById<de.hdodenhof.circleimageview.CircleImageView>(R.id.iv_avatar)
            // Glide 示例
            com.bumptech.glide.Glide.with(iv).load(p.avatarUrl).into(iv)
    
            itemView.setOnClickListener {
                val id = p.id
                Log.d("HomeFragment", "list1 others click id=$id")
                PersonaDetailDialogFragment
                    .newInstance(id)
                    .show(childFragmentManager, "persona_detail")
            }

            // 只点“添加”按钮
            itemView.findViewById<View>(R.id.btn_add).setOnClickListener {
                val id = p.id
                lifecycleScope.launch {
                    if(p.added == true){
                        //取消收藏
                        p.id?.let { id ->
                            try {
                                RetrofitClient.apiService.delUserCharacter(id.toInt())
                            } catch (e: Exception) {
                                // 处理错误
                            }
                        }
                    }else{
                        val addPersonaRequest = AddPersonaClick(
                            characterId = p.id?.toInt() ?: 0,
                            emoji = p.emoji ?: ""
                        )
                        try {
                            RetrofitClient.apiService.addUserCharacter(addPersonaRequest)
                        } catch (e: Exception) {
                            // 处理错误
                        }
                    }
                }
            }
    
            container.addView(itemView)
        }
    }
    
    private fun bindTopItem(
        root: View,
        avatarId: Int,
        nameId: Int,
        addBtnId: Int,
        container: Int,
        item: listByTagWithNotLogin?
    ) {
        val avatar = root.findViewById<de.hdodenhof.circleimageview.CircleImageView>(avatarId)
        val name = root.findViewById<TextView>(nameId)
        val addBtn = root.findViewById<View>(addBtnId)
        val container = root.findViewById<LinearLayout>(container)
    
        if (item == null) {
            // 没数据就隐藏（或者显示占位）
            // avatar.isVisible = false
            name.isVisible = false
            addBtn.isVisible = false
            return
        }
    
        avatar.isVisible = true
        name.isVisible = true
        addBtn.isVisible = true
    
        name.text = item.characterName ?: ""
    
        // 头像
        com.bumptech.glide.Glide.with(avatar).load(item.avatarUrl).into(avatar)
    
        addBtn.setOnClickListener {
            val id = item.id
            lifecycleScope.launch {
                if(item.added == true){
                    //取消收藏
                    item.id?.let { id ->
                        try {
                            RetrofitClient.apiService.delUserCharacter(id.toInt())
                        } catch (e: Exception) {
                            // 处理错误
                        }
                    }
                }else{
                    val addPersonaRequest = AddPersonaClick(
                        characterId = item.id?.toInt() ?: 0,
                        emoji = item.emoji ?: ""
                    )
                    try {
                        RetrofitClient.apiService.addUserCharacter(addPersonaRequest)
                    } catch (e: Exception) {
                        // 处理错误
                    }
                }
            }
        }

        container.setOnClickListener {
            val id = item.id
            Log.d("HomeFragment", "list1 top click id=$id rank=${item.rank}")
            PersonaDetailDialogFragment
                .newInstance(id)
                .show(childFragmentManager, "persona_detail")
        }
    }
    
    
    // ---------------- 网络请求 ----------------
    private suspend fun fetchPersonaByTag(tagId: Int): List<listByTagWithNotLogin> {
        return try {
            val resp = if (!isLoggedIn()) {
                RetrofitClient.apiService.personaListByTag(tagId)
            } else {
                RetrofitClient.apiService.loggedInPersonaListByTag(tagId)
            }
            resp.data ?: emptyList()
        } catch (e: Exception) {
            if(!isLoggedIn()){
                //未登录用户获取人设列表
                Log.e("1314520-HomeFragment", "未登录根据标签获取人设列表", e)
            }else{
                Log.e("1314520-HomeFragment", "登录根据标签获取人设列表", e)
            }
            emptyList()
        }
    }

    private suspend fun fetchAllPersonaList(): List<listByTagWithNotLogin> {
        return try {
            val personaData = if (!isLoggedIn()) {
                RetrofitClient.apiService.personaListWithNotLogin()
            } else {
                RetrofitClient.apiService.personaByTag()
            }
            personaData.data ?: emptyList()
        } catch (e: Exception) {
            if(!isLoggedIn()){
                //未登录用户获取人设列表
                Log.e("1314520-HomeFragment", "未登录用户人设列表", e)
            }else{
                Log.e("1314520-HomeFragment", "登录用户人设列表", e)
            }
            emptyList()
        }
    }

    suspend fun getpersonaLis(id: Int): ApiResponse<List<listByTagWithNotLogin>>? {
        return try {
            RetrofitClient.apiService.personaListByTag(id)
        } catch (e: Exception) {
            Log.e("1314520-HomeFragment", "未登录用户按标签查询人设列表", e)
            null
        }
    }

    suspend fun loggedInGetpersonaLis(id: Int): ApiResponse<List<listByTagWithNotLogin>>? {
        return try {
            RetrofitClient.apiService.loggedInPersonaListByTag(id)
        } catch (e: Exception) {
            Log.e("1314520-HomeFragment", "登录用户按标签查询人设列表", e)
            null
        }
    }

    private fun isLoggedIn(): Boolean {
        return EncryptedSharedPreferencesUtil.contains(requireContext(), "user")
    }
}
