package com.develop.step.ui.recipes_detail

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import com.develop.base.ext.load
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.develop.base.ext.*
import com.develop.base.util.ThreadUtils
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.entity.UserFavoriteRecipes
import com.develop.common.dialog.AmountSelectDialog
import com.develop.common.dialog.RecipeDeleteConfirmDialog
import com.develop.common.router.Screens
import com.develop.common.tag.CURRENT_USER_ID
import com.develop.common.ui.CommonBVMActivity
import com.develop.common.utils.Resource
import com.develop.common.dialog.DownloadFailedDialog
import com.develop.common.dialog.ShareQRCodeDialog
import com.develop.common.event.RefreshDataEvent
import com.develop.step.databinding.ActivityCookDetailBinding
import com.develop.step.viewmodel.CookDetailViewModel
import java.util.*
import com.develop.step.R
import com.develop.step.ui.recipes_detail.model.CookDetailInfo
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevModes
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.EventBus

@Route(path = Screens.Cook.COOK_DETAIL)
class CookDetailActivity : CommonBVMActivity<ActivityCookDetailBinding, CookDetailViewModel>() {
    /**
     * source=local为本地菜谱
     * source=remote为网络菜谱
     */
    @JvmField
    @Autowired(name = "source")
    var cookSource: String? = "remote"

    @JvmField
    @Autowired(name = "number")
    var recipeNumber: String? = null

    @JvmField
    @Autowired(name = "isLike")
    var isLike: Boolean = false

    @JvmField
    @Autowired(name = "recipesEdition")
    var recipesEdition: String? = "1.0"

    private var hideDetail = false
    private val hideViews = mutableListOf<View>()
    private val allTabViews = mutableListOf<View>()

    private val shareQRCodeDialog by lazy {
        ShareQRCodeDialog()
    }

    private val downloadFileDialog by lazy {
        DownloadFailedDialog()
    }

    override fun createViewModel(): CookDetailViewModel {
        return getViewModel(CookDetailViewModel::class.java)
    }

    override fun createViewBinding(inflater: LayoutInflater): ActivityCookDetailBinding {
        return ActivityCookDetailBinding.inflate(inflater)
    }




    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        initView()
        initData()
        initListener()
    }

    private fun initData() {
        viewModel.queryRecipe(
            recipeNumber ?: "",
            cookSource == "remote",
            recipesEdition ?: "1.0"
        )
        viewModel.getRecipeLiveData().observe(this) {
            updateCookDetail(it)
        }
        viewModel.getErrorCodeLiveData().observe(this) {
            if (it == CookDetailViewModel.ERR_NO_RECIPE_MATCH) {
                ToastUtils.showShort("No match recipe found!")
                finish()
            }
        }
        viewModel.starCountLiveData.observe(this) {
            binding.startLayout.apply {
                setStarCount(it)
                setCommentNumber(it.toString())
            }
        }
        viewModel.getDownloadState().observe(this) {
            updateDownloadButton(it)
        }
        viewModel.portionSizeLiveData.observe(this) {
            val jarsCount =
                (it?.portionSize ?: 1).toString() + " " + getString(com.develop.common.R.string.jar)
            binding.tvJarCount.text = jarsCount
        }
    }

    private fun initView() {
        if (isLike) {
            binding.viewLike.setImageResource(com.develop.common.R.drawable.ic_like)
        } else {
            binding.viewLike.setImageResource(com.develop.common.R.drawable.ic_unlike)
        }
        if (cookSource == "local") {
            binding.tvDownload.setText(com.develop.common.R.string.start_cooking)
            binding.viewProgress.setButtonColor(Color.parseColor("#CCEE8F08"))
            binding.viewIcon.setGone()
        } else {
            binding.tvDownload.text =
                getString(com.develop.common.R.string.download).uppercase(Locale.ROOT)
            binding.viewProgress.setButtonColor(Color.parseColor("#CC1296DB"))
            binding.viewIcon.setImageResource(com.develop.common.R.drawable.ic_detail_cook_download)
        }
        hideViews.let {
            it.add(binding.viewIcon1)
            it.add(binding.viewIcon2)
            it.add(binding.tvFoodTime)
            it.add(binding.tvEasy)
            it.add(binding.startLayout)
        }
        allTabViews.add(binding.ivTab1)
        allTabViews.add(binding.ivTab2)
        allTabViews.add(binding.ivTab3)
        allTabViews.add(binding.ivTab4)
        selectTab(TAB_SOURCE)
    }

    private fun initListener() {
        binding.ivTab1.setOnClickListener {
            selectTab(TAB_SOURCE)
        }
        binding.ivTab2.setOnClickListener {
            selectTab(TAB_DESC)
        }
        binding.ivTab3.setOnClickListener {
            selectTab(TAB_TOOLS)
        }
        binding.ivTab4.setOnClickListener {
            selectTab(TAB_SERVE)
        }
        binding.clStartCooking.setOnClickListener {
            if (cookSource == "remote") {
                if (viewModel.isDownloadSuccess()) {
                    navigateTo(Screens.Cook.COOK_STEP2) {
                        withString("number", recipeNumber)
                        withBoolean("isLike", isLike)
                    }
                } else if (!viewModel.isDownloading()) {
                    binding.tvDownload.setText(com.develop.common.R.string.downloading)
                    viewModel.downloadRecipe()
                }
            } else {
                navigateTo(Screens.Cook.COOK_STEP2) {
                    withString("number", recipeNumber)
                    withBoolean("isLike", isLike)
                }
            }
        }

        binding.viewLike.setOnClickListener {
            //收藏/取消收藏
            if (isLike) {
                isLike = false
                FoodDataProvider.getUserDatabase().runInTransaction {
                    FoodDataProvider.getUserDatabase().userInfoDao().removeFavoriteRecipe(
                        CURRENT_USER_ID, recipeNumber ?: ""
                    )
                }
                binding.viewLike.setImageResource(com.develop.common.R.drawable.ic_unlike)
            } else {
                isLike = true
                binding.viewLike.setImageResource(com.develop.common.R.drawable.ic_like)
                FoodDataProvider.getUserDatabase().runInTransaction {
                    FoodDataProvider.getUserDatabase().userInfoDao().insertFavoriteRecipe(
                        UserFavoriteRecipes(CURRENT_USER_ID, recipeNumber ?: "")
                    )
                }
            }
        }

        binding.tvMoreScore.setOnClickListener {
            navigateTo(Screens.Cook.COOK_EVALUATE) {
                withString("recipeId", recipeNumber)
            }
            binding.clFuncMore.setGone()
        }
        binding.tvMoreDelete.setOnClickListener {
            binding.clFuncMore.setGone()
            showDeleteRecipeDialog()
        }
        binding.tvMoreShare.setOnClickListener {
            val number = viewModel.getRecipeLiveData().value?.recipe?.number
            if (number.isNullOrEmpty()) {
                return@setOnClickListener
            }
            binding.clFuncMore.setGone()
            shareQRCodeDialog.apply {
                recipeNum = number
                showDialog(supportFragmentManager, "ShareQRCodeDialog")
            }
        }
        binding.viewServing.setOnClickListener {
            showAmountSelectDialog()
        }
        binding.tvServingSize.setOnClickListener {
            showAmountSelectDialog()
        }
        binding.viewBack.setOnClickListener {
            finish()
        }

        binding.viewHide.setOnClickListener {
            hideDetail = !hideDetail
            for (view in hideViews) {
                if (hideDetail) {
                    view.visibility = View.INVISIBLE
                } else {
                    view.visibility = View.VISIBLE
                }
            }
            if (hideDetail) {
                binding.viewHide.setImageResource(com.develop.common.R.drawable.ic_detail_show)
            } else {
                binding.viewHide.setImageResource(com.develop.common.R.drawable.ic_visible)
            }
        }

        binding.viewMore.setOnClickListener {
            binding.clFuncMore.setVisible()
        }
        binding.viewMoreClose.setOnClickListener {
            binding.clFuncMore.setGone()
        }
        binding.clFuncMore.setOnClickListener {
            binding.clFuncMore.setGone()
        }
    }

    private fun selectTab(tab: Int) {
        for (tabView in allTabViews) {
            tabView.isSelected = false
        }
        when (tab) {
            TAB_SOURCE -> {
                binding.ivTab1.isSelected = true
                replaceFragmentInstance(R.id.fl_tab_content, CookDetailSourceFragment())
            }

            TAB_DESC -> {
                binding.ivTab2.isSelected = true
                replaceFragmentInstance(R.id.fl_tab_content, CookDetailDescFragment())
            }

            TAB_TOOLS -> {
                binding.ivTab3.isSelected = true
                replaceFragmentInstance(R.id.fl_tab_content, CookDetailToolsFragment())
            }

            TAB_SERVE -> {
                binding.ivTab4.isSelected = true
                replaceFragmentInstance(R.id.fl_tab_content, CookDetailServeFragment())
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateCookDetail(detail: CookDetailInfo) {
        val bannerImg = FoodDataProvider.getResourcePath(detail.recipe.photoPath)
        binding.ivTopBanner.load(bannerImg)
        binding.tvFoodName.text = detail.recipe.name
        val timeDescBuilder = StringBuilder()
        timeDescBuilder.append(getString(com.develop.common.R.string.preparation))
        timeDescBuilder.append(" ")
        if (detail.recipe.prepareHours.isPositive()) {
            timeDescBuilder.append(detail.recipe.prepareHours)
            timeDescBuilder.append(getString(com.develop.common.R.string.hours))
            timeDescBuilder.append(" ")
        }
        if (detail.recipe.prepareMinutes.isPositive()) {
            timeDescBuilder.append(detail.recipe.prepareMinutes)
            timeDescBuilder.append(getString(com.develop.common.R.string.min))
        }
        timeDescBuilder.append("\n")
        timeDescBuilder.append(getString(com.develop.common.R.string.ready_in))
        if (detail.recipe.makeHours.isPositive()) {
            timeDescBuilder.append(detail.recipe.makeHours)
            timeDescBuilder.append(getString(com.develop.common.R.string.hours))
            timeDescBuilder.append(" ")
        }
        if (detail.recipe.makeMinutes.isPositive()) {
            timeDescBuilder.append(detail.recipe.makeMinutes)
            timeDescBuilder.append(getString(com.develop.common.R.string.min))
        }

        binding.tvFoodTime.text = timeDescBuilder.toString()
        binding.tvEasy.text = detail.recipe.difficultyLevel
        binding.startLayout.setCommentNumber(detail.recipe.useNum.toString())
        FoodDataProvider.getUserDatabase().runInTransaction {
           val result =  FoodDataProvider.getUserDatabase().userInfoDao()
                .queryUserTag(CURRENT_USER_ID, detail.recipe.number ?: "")
           runOnUiThread {
               result?.starCount?.apply {
                   binding.startLayout.setStarCount(this)
               }
           }
        }
//        detail.recipe.score?.let { binding.startLayout.setStarCount(it.toInt()) }
    }

    @Suppress("UNCHECKED_CAST")
    private fun updateDownloadButton(resource: Resource<Int>) {
        binding.tvDownload.tag = resource
        when (resource.status) {
            Resource.Status.FAILURE -> {
                binding.tvDownload.setVisible()
                binding.viewIcon.setVisible()
                binding.tvProgress.setGone()
                binding.tvDownloadState.setGone()
                binding.tvDownload.text =
                    getString(com.develop.common.R.string.download).uppercase(Locale.ROOT)
                binding.viewProgress.setProgress(1f)
                binding.viewProgress.setButtonColor(Color.parseColor("#CC1EABDB"))
                binding.viewIcon.setImageResource(com.develop.common.R.drawable.ic_detail_cook_download)
                downloadFileDialog.showDialog(supportFragmentManager, "DownloadFailedDialog")
            }

            Resource.Status.LOADING -> {
                val updateProgress = "${resource.data}%"
                binding.tvDownload.setGone()
                binding.viewIcon.setGone()
                binding.tvProgress.setVisible()
                binding.tvDownloadState.setVisible()
                binding.tvProgress.updateText(updateProgress)
                binding.viewProgress.setProgress(resource.data!! / 100f)
                binding.viewProgress.setButtonColor(Color.parseColor("#CC79C414"))
                binding.viewIcon.setImageResource(com.develop.common.R.drawable.ic_detail_cook_download)
            }

            else -> {
                binding.tvDownload.setVisible()
                binding.viewIcon.setVisible()
                binding.tvProgress.setGone()
                binding.tvDownloadState.setGone()
                binding.tvDownload.setText(com.develop.common.R.string.start_cooking)
                binding.viewProgress.setProgress(1f)
                binding.viewProgress.setButtonColor(Color.parseColor("#CCEE8F08"))
                binding.viewIcon.setGone()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.getStarCount(recipeNumber ?: "")
    }

    private fun showAmountSelectDialog() {
//        viewModel.getRecipeLiveData().value?.let {
//            AmountSelectDialog(it.portionSize) { size ->
//                viewModel.portionSizeLiveData.value = size
//            }.showDialog(supportFragmentManager, "AmountSelectDialog")
//        }
    }

    private fun showDeleteRecipeDialog() {
        val dialog = RecipeDeleteConfirmDialog {
            ThreadUtils.runOnWorkThread({
                val recipe = viewModel.getRecipeLiveData().value?.recipe
                if (recipe != null) {
                    FoodDataProvider.getDatabase().recipeDao().deleteRecipe(recipe)
                    FoodDataProvider.deleteRecipeResource(recipe.number ?: "")
                    FoodDataProvider.getUserDatabase().userInfoDao()
                        .removeOnlineRecipe(
                            CURRENT_USER_ID, recipe.number ?: ""
                        )
                    EventBus.getDefault().post(RefreshDataEvent())
                    runOnUiThread {
                        finish()
                    }
                }
            })
        }
        dialog.showDialog(supportFragmentManager, "RecipeDeleteConfirmDialog")
    }

    companion object {
        private const val TAB_SOURCE = 1
        private const val TAB_DESC = 2
        private const val TAB_TOOLS = 3
        private const val TAB_SERVE = 4
    }
}