package com.develop.common.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.develop.base.ext.load
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.updateText
import com.develop.base.util.TopResumedAtyHolder
import com.develop.common.R
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.FoodContentModel
import com.develop.common.data_repo.db.entity.UserFavoriteRecipes
import com.develop.common.databinding.FoodContentViewBinding
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.common.event.RefreshDataEvent
import com.develop.common.router.Screens
import com.develop.common.tag.*
import com.drake.net.utils.scope
import com.drake.net.utils.withMain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus

class FoodContentView : RelativeLayout {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
    }

    private val cancelConfirmDialog by lazy {
        CancelConfirmDialog()
    }
    private var binding: FoodContentViewBinding


    private var mFoodContent: FoodContentModel? = null

    private var mIsFoodList = false
    var mIsHistoryList = false

    init {
        val root = View.inflate(context, R.layout.food_content_view, this)
        binding = FoodContentViewBinding.bind(root)
        binding.contentLayout.setOnClickListener {
            mFoodContent?.apply {
                TopResumedAtyHolder.getCurrentActivity()?.navigateTo(Screens.Cook.COOK_DETAIL) {
                    withString(
                        SOURCE_TAG, if (isNetRecipes) {
                            "remote"
                        } else {
                            "local"
                        }
                    )
                    withString(NUMBER_TAG, foodId)
                    withBoolean(IS_LIKE_TAG, isLike)
                    if (!mIsFoodList) {
                        withString(RECIPES_EDITION_TAG, recipesEdition)
                    }
                }
            }
        }

    }

    /**
     * 显示菜谱数据
     * @param isFoodList 是否为FoodListActivity
     */
    fun setFoodContent(content: FoodContentModel, isFoodList: Boolean = false) {
        mFoodContent = content
        mIsFoodList = isFoodList
        val isNetRecipes = content.isNetRecipes
        val hasDownload = content.hasDownloaded
        val isLike = content.isLike
        val cover = if (isFoodList) {
            if (isNetRecipes && !content.hasDownloaded) {
                content.cover
            } else {
                FoodDataProvider.getResourcePath(content.cover.toString())
            }
        } else {
            if (isNetRecipes) {
                content.cover
            } else {
                FoodDataProvider.getResourcePath(content.cover.toString())
            }
        }
        binding.apply {
            if("" != cover) ivCover.load(cover)
            tvFoodName.updateText(content.foodName)
            scope(Dispatchers.IO) {
                val result = FoodDataProvider.getUserDatabase().userInfoDao()
                    .queryUserTag(CURRENT_USER_ID, content.foodId)
                withMain {
                    result?.starCount?.apply {
                        starView.setStarCount(this)
                    }
                }
            }
            starView.apply {
                setCommentNumber(content.useNum.toString())
                setCommentTextColorGray()
            }
            tvTimeAndLevel.updateText("${content.time}・${content.level}")
            if (isNetRecipes) {
                ivNet.visibility = View.VISIBLE
            } else {
                ivNet.visibility = View.GONE
            }
            if (hasDownload) {
                ivLike.load(R.drawable.ic_delete)
            } else {
                if (isLike) {
                    ivLike.load(R.drawable.ic_like)
                } else {
                    ivLike.load(R.drawable.ic_unlike)
                }
            }
            //喜欢点击
            likeLayout.setOnClickListener {
                //收藏/取消收藏

                if (content.isNetRecipes && isFoodList) {
                    val titleStr = context.getString(R.string.are_you_sure_to_delete)
                    val confirmStr = context.getString(R.string.yes)
                    val cancelStr = context.getString(R.string.no)
                    TopResumedAtyHolder.getCurrentActivity()?.apply {
                        cancelConfirmDialog.apply {
                            this.title = titleStr
                            this.confirmStr = confirmStr
                            this.cancelStr = cancelStr
                            onDialogClickListener =
                                object : CancelConfirmDialog.OnDialogClickListener {
                                    override fun onConfirm() {
                                        FoodDataProvider.getUserDatabase().runInTransaction {
                                            FoodDataProvider.getUserDatabase().userInfoDao()
                                                .removeOnlineRecipe(
                                                    CURRENT_USER_ID, content.foodId
                                                )
                                        }
                                        FoodDataProvider.getDatabase().runInTransaction {
                                            val recipeDao =
                                                FoodDataProvider.getDatabase().recipeDao()
                                            val recipes = recipeDao.queryRecipe(content.foodId)
                                            recipes?.apply {
                                                recipeDao.deleteRecipe(this)
                                            }
                                            FoodDataProvider.deleteRecipeResource(content.foodId)
                                        }
                                        EventBus.getDefault().post(RefreshDataEvent())
                                    }

                                    override fun onCancel() {

                                    }
                                }
                            showDialog(supportFragmentManager, "cancelConfirmDialog")
                        }
                    }
                } else {
                    if (content.isLike) {
                        content.isLike = false
                        ivLike.load(R.drawable.ic_unlike)
                        FoodDataProvider.getUserDatabase().runInTransaction {
                            FoodDataProvider.getUserDatabase().userInfoDao().removeFavoriteRecipe(
                                CURRENT_USER_ID, content.foodId
                            )
                        }
                        if (!mIsHistoryList) {
                            EventBus.getDefault().post(RefreshDataEvent())
                        }

                    } else {
                        content.isLike = true
                        ivLike.load(R.drawable.ic_like)
                        FoodDataProvider.getUserDatabase().runInTransaction {
                            FoodDataProvider.getUserDatabase().userInfoDao().insertFavoriteRecipe(
                                UserFavoriteRecipes(CURRENT_USER_ID, content.foodId)
                            )
                        }
                        if (!mIsHistoryList) {
                            EventBus.getDefault().post(RefreshDataEvent())
                        }
                    }
                }
            }
        }
    }

    companion object {
        val dp10 = (com.develop.base.R.dimen.convert_10px).resId2Dimension()
    }

}