package com.base.appzxhy.ui.vm

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewModelScope
import com.base.appzxhy.R
import com.base.appzxhy.utils.LogEx
import com.bytedance.sdk.shortplay.api.PSSDK
import com.bytedance.sdk.shortplay.api.PSSDK.FeedListLoadResult
import com.bytedance.sdk.shortplay.api.PSSDK.FeedListResultListener
import com.bytedance.sdk.shortplay.api.ShortPlay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

class ShortPlayViewModel : ViewModel() {

    private val TAG = "ShortPlayViewModel"

    val bannerList = MutableStateFlow<List<ShortPlay>>(listOf())
    var newList = MutableStateFlow<List<ShortPlay>>(listOf())
    var categoryList = MutableStateFlow<List<ShortPlay>>(listOf())

    companion object {

        const val CATEGORY_MALE_ID = 1L//男频
        const val CATEGORY_FEMALE_ID = 2L//女频
        const val CATEGORY_CITY_ID = 3L//都市
        const val CATEGORY_SUSPENSE_ID = 4L//悬疑
        const val CATEGORY_MODERN_ID = 5L//现代
        const val CATEGORY_ANCIENT_ID = 6L//古代
        const val CATEGORY_MILITARY_ID = 7L//军事
        const val CATEGORY_FANTASY_ID = 8L//玄幻
        const val CATEGORY_BLOOD_ID = 9L//热血
        const val CATEGORY_HISTORY_ID = 10L//历史
        const val CATEGORY_COMEDY_ID = 11L//喜剧
        const val CATEGORY_ACTION_ID = 12L//动作
        const val CATEGORY_ACG_ID = 13L//二次元
        const val CATEGORY_OTHERS_ID = 14L//其他

        private val tempCategoryList = listOf(
            CATEGORY_CITY_ID,
            CATEGORY_MODERN_ID,
            CATEGORY_COMEDY_ID,
            CATEGORY_ANCIENT_ID,
            CATEGORY_ACTION_ID,
            CATEGORY_FANTASY_ID,
            CATEGORY_BLOOD_ID,
            CATEGORY_SUSPENSE_ID,
            CATEGORY_MILITARY_ID,
            CATEGORY_HISTORY_ID,
            CATEGORY_ACG_ID,
            CATEGORY_OTHERS_ID
        )
    }

    private val categoryLoading = AtomicBoolean(false)
    private val homeCategoryList = ArrayList<Long>().apply {
        addAll(tempCategoryList)
    }

    /**
     * 按分类顺序获取列表
     */
    fun getCategoryListFlow(
        reload: Boolean = false,
        count: Int = 12,
    ) {
        if (reload) {
            homeCategoryList.addAll(tempCategoryList)
        }
        if (homeCategoryList.isNotEmpty()) {
            val nextCategory = homeCategoryList[0]
            homeCategoryList.removeAt(0)

            PSSDK.requestFeedListByCategoryIds(listOf(nextCategory), null, 1, count, object : FeedListResultListener {
                override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
                    LogEx.logDebug(TAG, "requestFeedListByCategoryIds ${errorInfo?.msg} ${errorInfo?.code}")
                    getCategoryListFlow(false)
                }

                override fun onSuccess(result: FeedListLoadResult<ShortPlay>?) {

                    viewModelScope.launch(Dispatchers.IO) {
                        result?.dataList?.let { categoryList.emit(it) }
                    }

                }
            })
        }

    }

    /**
     * 获取热门短剧列表
     */
    fun getPopularDrama(
        count: Int = 10,
    ) {
        PSSDK.requestPopularDrama(1, count, object : FeedListResultListener {
            override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
                LogEx.logDebug(TAG, "requestPopularDrama ${errorInfo?.msg} ${errorInfo?.code}")
            }

            override fun onSuccess(result: FeedListLoadResult<ShortPlay>?) {
                result?.dataList?.let {
                    viewModelScope.launch { bannerList.emit(it) }
                }
            }
        })
    }

    /**
     * 获取近期新增短剧列表
     */
    fun getNewDrama(
        count: Int = 12,
    ) {
        PSSDK.requestNewDrama(1, count, object : FeedListResultListener {
            override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
                LogEx.logDebug(TAG, "requestNewDrama ${errorInfo?.msg} ${errorInfo?.code}")
            }

            override fun onSuccess(result: FeedListLoadResult<ShortPlay>?) {
                LogEx.logDebug(TAG, "dataList=${result?.dataList?.size}")
                result?.dataList?.let {
                    viewModelScope.launch { newList.emit(it) }
                }
            }
        })
    }

    /**
     * 获取指定分类或短剧的列表
     */
    fun getFeedListByCategoryIds(
        categoryIds: List<Long>? = null,
        shortPlayIds: List<Long>? = null,
        index: Int = 1,
        count: Int = 12,
        uiAction: (list: List<ShortPlay>) -> Unit
    ) {
        categoryLoading.set(true)
        PSSDK.requestFeedListByCategoryIds(categoryIds, shortPlayIds, index, count, object : FeedListResultListener {
            override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
                LogEx.logDebug(TAG, "requestFeedListByCategoryIds ${errorInfo?.msg} ${errorInfo?.code}")
                categoryLoading.set(false)
            }

            override fun onSuccess(result: FeedListLoadResult<ShortPlay>?) {
                result?.dataList?.let { uiAction.invoke(it) }
                categoryLoading.set(false)
            }
        })
    }

    fun categoryTitle(context: Context, ids: Long): String {
        return when (ids) {
            CATEGORY_MALE_ID -> context.getString(R.string.male)
            CATEGORY_FEMALE_ID -> context.getString(R.string.female)
            CATEGORY_CITY_ID -> context.getString(R.string.city)
            CATEGORY_SUSPENSE_ID -> context.getString(R.string.suspense)
            CATEGORY_MODERN_ID -> context.getString(R.string.modern)
            CATEGORY_ANCIENT_ID -> context.getString(R.string.ancient)
            CATEGORY_MILITARY_ID -> context.getString(R.string.military)
            CATEGORY_FANTASY_ID -> context.getString(R.string.fantasy)
            CATEGORY_BLOOD_ID -> context.getString(R.string.blood)
            CATEGORY_HISTORY_ID -> context.getString(R.string.history)
            CATEGORY_COMEDY_ID -> context.getString(R.string.comedy)
            CATEGORY_ACTION_ID -> context.getString(R.string.action)
            CATEGORY_ACG_ID -> context.getString(R.string.acg)
            CATEGORY_OTHERS_ID -> context.getString(R.string.others)
            else -> ""
        }
    }


    /**
     * 获取分类标签接口
     */
    fun getCategoryList(
        language: String,
        uiAction: (list: List<ShortPlay.ShortPlayCategory>) -> Unit
    ) {
        PSSDK.requestCategoryList(language, object : PSSDK.CategoryListResultListener {
            override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
                LogEx.logDebug(TAG, "requestNewDrama ${errorInfo?.msg} ${errorInfo?.code}")
            }

            override fun onSuccess(result: FeedListLoadResult<ShortPlay.ShortPlayCategory>?) {
                result?.dataList?.let { uiAction.invoke(it) }
            }
        })
    }
}