package com.develop.main.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.scopeNetLife
import com.develop.base.ext.getSN
import com.develop.base.mvvm.BaseViewModel
import com.develop.base.util.MMkvUtils
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.*
import com.develop.common.data_repo.db.entity.DevRecipe
import com.develop.common.data_repo.db.entity.DevRecipeCategory
import com.develop.common.data_repo.db.entity.UserFavoriteRecipes
import com.develop.common.data_repo.net.Api
import com.develop.common.data_repo.net.model.response.*
import com.develop.common.tag.CURRENT_LANGUAGE
import com.develop.common.tag.CURRENT_USER_ID
import com.develop.common.widget.HomeOrBack
import com.drake.net.Get
import com.drake.net.utils.scope
import kotlinx.coroutines.Dispatchers

class HomeViewModel : BaseViewModel() {

    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>>()
    val onLineHotTagsLiveData = MutableLiveData<MutableList<String>>()
    var noticesLiveData = MutableLiveData<MutableList<Inform>>()
    var tempOnLineRecipes = mutableListOf<DevRecipe>()

    var currCategoryName = ""
    var recipesType = RecipesType.LOCAL
    var isFromDownloadNewRecipesEntrance = false
    var currentPage = 1
    var currentPageSize = 12
    var totalPageSize = 1
    var sortedType = SortedType.Popular
    var homeOrBackLiveData = MutableLiveData<HomeOrBack>()
    var isSearch = false
    private val userId = CURRENT_USER_ID

    private var totalLocalRecipes = mutableListOf<DevRecipe>()
    private var totalLocalSize = 0
    private var startSize = 0
    private var endSize = 12
    private var lastLocalRecipesShowList = mutableListOf<Any>()
    private var hasMoreLocal = false
    private var lastLocalRecipeList = mutableListOf<DevRecipe>()
    private var localFavoriteRecipesList = mutableListOf<UserFavoriteRecipes>()

    /**查询本地菜谱分类*/
    fun queryRecipesCategory() {
        FoodDataProvider.getDatabase().runInTransaction {
            localCategoryLiveData.postValue(
                FoodDataProvider.getDatabase().recipeDao().queryCategory().toMutableList()
            )
        }
    }

    /**查询本地对应菜谱分类下的菜谱列表信息*/
    fun queryLocalRecipes(categoryNum: String) {
        scope(Dispatchers.IO) {
            startSize = 0
            endSize = 12
            localFavoriteRecipesList =
                FoodDataProvider.getUserDatabase().userInfoDao().queryFavoriteRecipes(userId)
                    .toMutableList()
            //获取所有的分类
            totalLocalRecipes =
                if (categoryNum.isEmpty()) FoodDataProvider.getDatabase().recipeDao()
                    .queryAllRecipe().toMutableList() else {
                    //获取当前分类
                    FoodDataProvider.getDatabase().recipeDao().queryRecipesByCategory(categoryNum)
                        .toMutableList()
                }
            totalLocalSize = totalLocalRecipes.size
            val localRecipeList = if (totalLocalSize < 12) {
                hasMoreLocal = false
                totalLocalRecipes
            } else {
                hasMoreLocal = true
                totalLocalRecipes.subList(0, 12)
            }
            lastLocalRecipeList.clear()
            lastLocalRecipeList.addAll(localRecipeList)
            lastLocalRecipesShowList = DataFactory.genLocalRecipes(
                currCategoryName, localRecipeList, localFavoriteRecipesList, sortedType
            )
            localRecipesLiveData.postValue(
                lastLocalRecipesShowList
            )
        }
    }

    /**
     * 获取更多本地数据，没有返回false
     */
    fun loadMoreLocalRecipes(): Boolean {
        if (hasMoreLocal) {
            startSize = endSize
            endSize = startSize + 12
            if (endSize > totalLocalSize) {
                endSize = totalLocalSize
                hasMoreLocal = false
            }
            val moreData = totalLocalRecipes.subList(startSize, endSize)
            lastLocalRecipeList.addAll(moreData)
            lastLocalRecipesShowList = DataFactory.genLocalRecipes(
                currCategoryName, lastLocalRecipeList, localFavoriteRecipesList, sortedType
            )
            localRecipesLiveData.postValue(lastLocalRecipesShowList)
        } else {
            return false
        }
        return true
    }


    /**根据热词查询菜谱列表信息*/
    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))
            val foodContentList = mutableListOf<FoodContentModel>()
            when (categoryType) {
                CategoryType.All -> {
                    allList.forEach {
                        foodContentList.add(
                            FoodContentModel(
                                it.photoPath ?: "",
                                it.name ?: "",
                                3,
                                getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "",
                                foodId = it.number ?: ""
                            )
                        )
                    }
                }
                CategoryType.Recipes -> {
                    recipesList.forEach {
                        foodContentList.add(
                            FoodContentModel(
                                it.photoPath ?: "",
                                it.name ?: "",
                                3,
                                getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "",
                                foodId = it.number ?: ""
                            )
                        )
                    }
                }
                CategoryType.Ingredients -> {
                    foodList.forEach {
                        foodContentList.add(
                            FoodContentModel(
                                it.photoPath ?: "",
                                it.name ?: "",
                                3,
                                getTime(it.makeHours ?: 0, it.makeMinutes ?: 0),
                                it.difficultyLevel ?: "",
                                foodId = it.number ?: ""
                            )
                        )
                    }
                }
            }
            result.add(FoodListModel(foodContentList,""))
            hotWordSearchRecipesLiveData.postValue(result)
        }
    }

    /**获取线上的菜谱分类*/
    fun getOnLineCategoryList() {
        scopeNetLife {
            onlineCategoryLiveData.value = Get<CategoryListResult>(Api.GET_CATEGORIES) {
                addQuery("sn", getSN())
                addQuery("lang", MMkvUtils.getString(CURRENT_LANGUAGE) ?: "EN")
            }.await().categorys.toMutableList()
        }
    }

    /**获取线上的热门标签*/
    fun getOnLineHotTags() {
        scopeNetLife {
            onLineHotTagsLiveData.value = Get<HotTagsResult>(Api.GET_HOT_TAGS) {
                addQuery("sn", getSN())
                addQuery("lang", MMkvUtils.getString(CURRENT_LANGUAGE) ?: "EN")
            }.await().hotTags.toMutableList()
        }
    }

    fun getOnLineRecipeList(
        category: String,
        name: String,
        pageIndex: Int = 1,
        pageSize: Int = 10,
        isLoadMore: Boolean = false
    ) {
        if (!isLoadMore) resetOnlineConfig()
        scopeNetLife {
            val result = Get<RecipesListResult>(Api.GET_RECIPES) {
                addQuery("category", category)
                addQuery("name", name)
                addQuery("sn", getSN())
                addQuery("lang", MMkvUtils.getString(CURRENT_LANGUAGE) ?: "EN")
                addQuery("pageIndex", pageIndex)
                addQuery("pageSize", pageSize)
            }.await()
            val recipesList = result.recipes
            val pager = result.pager
            totalPageSize = pager.pageCount
            currentPage = pager.pageIndex
            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(userTag?.starCount ?: 0)
                }
                onLineRecipesLiveData.postValue(
                    DataFactory.genNetRecipesData(
                        currCategoryName, tempOnLineRecipes, favoriteRecipesList, sortedType
                    )
                )
            }
        }
    }

    /**获取线上的消息*/
    fun getNotices() {
        scopeNetLife {
            noticesLiveData.value = Get<NoticeResult>(Api.GET_NOTICES) {
                addQuery("sn", getSN())
                addQuery("lang", MMkvUtils.getString(CURRENT_LANGUAGE) ?: "EN")
            }.await().informs.toMutableList()
        }
    }


    /**刷新空数据*/
    fun postEmptyOnlineRecipes() {
        onLineRecipesLiveData.postValue(
            DataFactory.genNetRecipesData(
                currCategoryName, tempOnLineRecipes, arrayListOf(), sortedType
            )
        )
    }


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


}