package com.develop.step

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
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.KeyboardUtils
import com.develop.food.base.event.RefreshStarDataEvent
import com.develop.food.base.repo.CURRENT_USER_ID
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.UserTag
import com.develop.food.base.router.Screens
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.GlobalToast
import com.develop.food.base.utils.ThreadUtils
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.step.databinding.ActivityCookEvaluateBinding
import org.greenrobot.eventbus.EventBus

@Route(path = Screens.Cook.COOK_EVALUATE)
class CookEvaluateActivity : BaseActivity<ActivityCookEvaluateBinding>() {

    private val starViews = mutableListOf<View>()

    @JvmField
    @Autowired(name = "recipeNumber")
    var recipeNumber = ""

    @JvmField
    @Autowired(name = "recipesEdition")
    var recipesEdition = ""

    private var starCount = 0
    private var evaluateContent = ""
    private var useNum = 0L
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)

        binding.let {
            starViews.add(it.ivStar1)
            starViews.add(it.ivStar2)
            starViews.add(it.ivStar3)
            starViews.add(it.ivStar4)
            starViews.add(it.ivStar5)
        }

        binding.root.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
        }

        binding.ivStar1.setOnClickListener {
            selectStar(1)
            starCount = 1
            binding.tvGood.text = getString(R.string.bad)
        }
        binding.ivStar2.setOnClickListener {
            selectStar(2)
            starCount = 2
            binding.tvGood.text = getString(R.string.imperfect)
        }
        binding.ivStar3.setOnClickListener {
            selectStar(3)
            starCount = 3
            binding.tvGood.text = getString(R.string.ordinary)
        }
        binding.ivStar4.setOnClickListener {
            selectStar(4)
            starCount = 4
            binding.tvGood.text = getString(R.string.good)
        }
        binding.ivStar5.setOnClickListener {
            selectStar(5)
            starCount = 5
            binding.tvGood.text = getString(R.string.perfect)
        }
        binding.viewClose.setOnClickListener {
            finish()
        }


//        safeGlobalScope.launch(Dispatchers.IO) {
//            val userTag = FoodDataProvider.getUserDatabase().userInfoDao().queryUserTag(
//                CURRENT_USER_ID, recipeNumber ?: ""
//            )
//            val recipes = FoodDataProvider.getDatabase().recipeDao().queryRecipe(recipeNumber)
//            val count1 = userTag?.starCount ?: 0
//            val count2 = recipes?.score?.toInt() ?: 0
//            starCount = if (count1 != 0) {
//                count1
//            } else if (count2 != 0) {
//                count2
//            } else {
//                0
//            }
//            runOnMainThread {
//                selectStar(starCount)
//                when (starCount) {
//                    1 -> {
//                        binding.tvGood.text = getString(R.string.bad)
//                    }
//
//                    2 -> {
//                        binding.tvGood.text = getString(R.string.imperfect)
//                    }
//
//                    3 -> {
//                        binding.tvGood.text = getString(R.string.ordinary)
//                    }
//
//                    4 -> {
//                        binding.tvGood.text = getString(R.string.good)
//                    }
//
//                    5 -> {
//                        binding.tvGood.text = getString(R.string.perfect)
//                    }
//                }
//                binding.etContent.setText(userTag?.daily)
//            }
//        }

        binding.tvOk.setOnClickListener {
            if (binding.etContent.text.toString().length>100){
                showMsgDialog()
                return@setOnClickListener
            }
            KeyboardUtils.hideSoftInput(this)
            evaluateContent = binding.etContent.text.toString()
            FoodDataProvider.getUserDatabase().runInTransaction {
                val userTag = UserTag(CURRENT_USER_ID, recipeNumber, starCount, evaluateContent)
                FoodDataProvider.getUserDatabase().userInfoDao().updateUserTag(userTag)
                val result = FoodDataProvider.getDatabase().recipeDao().queryRecipe(recipeNumber)
                result?.score = starCount.toDouble()
                result?.useNum = result?.useNum?.plus(1)
                useNum = result?.useNum ?: 0L
                result?.apply {
                    FoodDataProvider.getDatabase().recipeDao().updateRecipe(this)
                }
            }

//            FoodRepository.score(recipeNumber,recipesEdition,starCount.toString(),evaluateContent).observeStatus(
//                onSuccess = {
//                    GlobalToast.showToast(getString(R.string.evaluate_successfully))
//                    finish();
//                    return@observeStatus
//
//                },
//                onFailed = {
//                    it?.desc?.let { msg ->
//                        ToastUtils.showShort(msg)
//                    }
//                }
//            )
            EventBus.getDefault().post(RefreshStarDataEvent(starCount, recipeNumber, useNum))

            GlobalToast.showToast(getString(R.string.evaluate_successfully))
            finish()
        }
        ThreadUtils.runOnWorkThread(Runnable {
            val userTag = FoodDataProvider
                .getUserDatabase()
                .userInfoDao()
                .queryUserTag(CURRENT_USER_ID, recipeNumber)
                ?: return@Runnable
            ThreadUtils.runOnMainThread {
                val clickStart = starViews.getOrNull(userTag.starCount - 1)
                clickStart?.performClick()
                binding.etContent.setText(userTag.daily)
            }
        })
    }

    private fun selectStar(count: Int) {
        for (index in starViews.indices) {
            starViews[index].isSelected = index + 1 <= count
        }
    }

    override fun createViewBinding(inflater: LayoutInflater): ActivityCookEvaluateBinding {
        return ActivityCookEvaluateBinding.inflate(inflater)
    }
    private fun  showMsgDialog(){
        var deviceStateDialog = CancelConfirmDialog()
        deviceStateDialog.showCancel = false
        deviceStateDialog.showConfirm = true
        deviceStateDialog.confirmStr = getString(R.string.pmpt_confirm)
        deviceStateDialog.title = getString(R.string.note_comment_content_exceed)
        deviceStateDialog.showDialog(supportFragmentManager, "confirmCancelDialog")
        deviceStateDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    deviceStateDialog.removeSelf();
                }

                override fun onCancel() {
                    deviceStateDialog.removeSelf();
                }

            }


    }
}
