package com.develop.main.init.ui.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.develop.food.base.api.FoodRepository
import com.develop.food.base.data.CategoryType
import com.develop.food.base.data.DataFactory
import com.develop.food.base.data.SortedType
import com.develop.food.base.data.model.CategoryModel
import com.develop.food.base.data.model.FilterSortModel
import com.develop.food.base.data.model.FoodContentModel
import com.develop.food.base.data.model.NewsModel
import com.develop.food.base.http.observeStatus
import com.develop.food.base.repo.CURRENT_USER_ID
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.DevRecipe
import com.develop.food.base.repo.entity.DevRecipeCategory
import com.develop.food.base.utils.ThreadUtils

class HomeViewModel : ViewModel() {
    val netFoodLiveData = MutableLiveData<Boolean>()
    val refreshRecipesLiveData = MutableLiveData<Boolean>()
    val localCategoryLiveData = MutableLiveData<MutableList<DevRecipeCategory>>()
    val localRecipesLiveData = MutableLiveData<MutableList<Any>>()
    val onlineCategoryLiveData = MutableLiveData<MutableList<DevRecipeCategory>>()
    val onLineRecipesLiveData = MutableLiveData<MutableList<Any>>()
    val hotWordSearchRecipesLiveData = MutableLiveData<MutableList<Any>>()
    var currCategoryName = ""
    private val userId = CURRENT_USER_ID

    val onLineHotTagsLiveData = MutableLiveData<MutableList<String>>()

    var noticesLiveData = MutableLiveData<MutableList<NewsModel>>()

    var recipesType = RecipesType.LOCAL

    var currentPage = 1
    var currentPageSize = 10
    var totalPageSize = 1

    var sortedType = SortedType.Popular

    var tempOnLineRecipes = mutableListOf<DevRecipe>()
    fun queryRecipesCategory() {
        FoodDataProvider.getDatabase().runInTransaction {
            localCategoryLiveData.postValue(
                FoodDataProvider.getDatabase().recipeDao().queryCategory().toMutableList()
            )
        }
    }

    fun queryLocalRecipes(categoryNum: String) {
        ThreadUtils.runOnWorkThread({
            if (categoryNum.isEmpty()) {
                //获取所有的分类
                val favoriteRecipesList =
                    FoodDataProvider.getUserDatabase().userInfoDao().queryFavoriteRecipes(userId)
                        .toMutableList()
                val localRecipeList =
                    FoodDataProvider.getDatabase().recipeDao().queryAllRecipe().toMutableList()
                val starList = mutableListOf<Int>()
                localRecipeList.forEach {
                    val userTag = FoodDataProvider.getUserDatabase().userInfoDao().queryUserTag(
                        CURRENT_USER_ID, it.number ?: ""
                    )
                    starList.add(it.score?.toInt() ?: 0)
                }
                localRecipesLiveData.postValue(
                    DataFactory.genLocalRecipes(
                        currCategoryName,
                        localRecipeList,
                        favoriteRecipesList,
                        starList,
                        sortedType
                    )
                )
            } else {
                //获取当前分类
                val favoriteRecipesList =
                    FoodDataProvider.getUserDatabase().userInfoDao().queryFavoriteRecipes(userId)
                        .toMutableList()
                val localRecipeList =
                    FoodDataProvider.getDatabase().recipeDao().queryRecipesByCategory(categoryNum)
                        .toMutableList()
                val starList = mutableListOf<Int>()
                localRecipeList.forEach {
                    val userTag = FoodDataProvider.getUserDatabase().userInfoDao().queryUserTag(
                        CURRENT_USER_ID, it.number ?: ""
                    )
                    starList.add(it.score?.toInt() ?: 0)
                }
                localRecipesLiveData.postValue(
                    DataFactory.genLocalRecipes(
                        currCategoryName,
                        localRecipeList,
                        favoriteRecipesList,
                        starList,
                        sortedType
                    )
                )
            }
        })
    }

    fun queryRecipesByHotWord(hotWord: String, categoryType: CategoryType) {
        val result = mutableListOf<Any>()
        result.add(FilterSortModel(""))
        FoodDataProvider.getDatabase().runInTransaction {
            val recipeDao = FoodDataProvider.getDatabase().recipeDao()
            val recipesList = recipeDao.queryRecipeByName(hotWord)
            val foodList = mutableListOf<DevRecipe>()
            val allList = mutableListOf<DevRecipe>()
            recipeDao.queryFoodByFoodName(hotWord).forEach {
                it.recipeNumber?.apply {
                    recipeDao.queryRecipe(this)?.let { devRecipe ->
                        foodList.add(devRecipe)
                    }
                }
            }
            val recipeCount = recipesList.size
            val foodCount = foodList.size
            allList.addAll(recipesList)
            allList.addAll(foodList)
            result.add(CategoryModel(recipeCount + foodCount, recipeCount, foodCount))
            when (categoryType) {
                CategoryType.All -> {
                    allList.forEach {
                        result.add(
                            FoodContentModel(
                                it.photoPath ?: "", it.name ?: "",
                                3, DataFactory.getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "", foodId = it.number ?: ""
                            )
                        )
                    }
                }
                CategoryType.Recipes -> {
                    recipesList.forEach {
                        result.add(
                            FoodContentModel(
                                it.photoPath ?: "", it.name ?: "",
                                3, DataFactory.getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "", foodId = it.number ?: ""
                            )
                        )
                    }
                }
                CategoryType.Ingredients -> {
                    foodList.forEach {
                        result.add(
                            FoodContentModel(
                                it.photoPath ?: "", it.name ?: "",
                                3, DataFactory.getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "", foodId = it.number ?: ""
                            )
                        )
                    }
                }
            }
            hotWordSearchRecipesLiveData.postValue(result)
        }
    }

    fun getOnLineCategoryList() {
        FoodRepository.getRecipesCategory().observeStatus(onSuccess = {
            it?.categorys?.toMutableList()?.apply {
                onlineCategoryLiveData.postValue(this)
            }

        }, onFailed = {

        })
    }

    fun getOnLineRecipeList(
        category: String,
        name: String,
        pageIndex: Int = 1,
        pageSize: Int = 10,
        isLoadMore: Boolean = false
    ) {
        if (!isLoadMore) resetOnlineConfig()
        FoodRepository.recipesList(category, name, pageIndex, pageSize).observeStatus(
            onFailed = {

            },
            onSuccess = {
                val recipesList = it?.recipes?.toMutableList() ?: mutableListOf()
                val pager = it?.pager
                totalPageSize = pager?.pageCount ?: 1
                currentPage = pager?.pageIndex ?: 1
                FoodDataProvider.getUserDatabase().runInTransaction {

                    val favoriteRecipesList =
                        FoodDataProvider.getUserDatabase().userInfoDao()
                            .queryFavoriteRecipes(userId)
                            .toMutableList()
                    val starList = mutableListOf<Int>()
                    tempOnLineRecipes.addAll(recipesList)
                    tempOnLineRecipes.forEach { devRecipe ->
                        val userTag = FoodDataProvider.getUserDatabase().userInfoDao().queryUserTag(
                            CURRENT_USER_ID, devRecipe.number ?: ""
                        )
                        starList.add(devRecipe.score?.toInt()?: 0)
                    }
                    onLineRecipesLiveData.postValue(
                        DataFactory.genNetRecipesData(
                            currCategoryName,
                            tempOnLineRecipes,
                            favoriteRecipesList,
                            starList, sortedType
                        )
                    )
                }
            })
    }


    fun getOnLineHotTags() {
        FoodRepository.getHotTags().observeStatus(onSuccess = {
            it?.hotTags?.toMutableList()?.apply {
                onLineHotTagsLiveData.postValue(this)
            }

        }, onFailed = {

        })
    }

    fun getNotices() {
        FoodRepository.getNotices().observeStatus(
            onSuccess = {

            },
            onFailed = {

            })
    }


    private fun resetOnlineConfig() {
        currentPage = 1
        currentPageSize = 10
        totalPageSize = 1
        tempOnLineRecipes.clear()
    }

    enum class RecipesType {
        ONLINE,
        LOCAL
    }
}