package com.develop.setting.init.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.azhon.appupdate.listener.OnDownloadListener
import com.blankj.utilcode.util.AppUtils
import com.develop.food.base.api.FoodRepository
import com.develop.food.base.http.observeStatus
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.*
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.food.base.widgets.CommonDialog
import com.develop.food.base.widgets.RecipeUpdateDialog
import com.develop.setting.R
import com.develop.setting.databinding.ActivityAboutBinding
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.DevStatusEvent
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.Subscribe
import java.io.File

@Route(path = Screens.Setting.ABOUT)
class AboutActivity : BaseActivity<ActivityAboutBinding>() {
    override fun createViewBinding(inflater: LayoutInflater): ActivityAboutBinding {
        return ActivityAboutBinding.inflate(layoutInflater)
    }

    private var updateApkUrl = ""

    private var weightAlignCount = 0;

    private val cancelConfirmDialog by lazy {
        CancelConfirmDialog()
    }

    private val commonDialog by lazy {
        CommonDialog()
    }


    private val recipeUpdateDialog:RecipeUpdateDialog =   RecipeUpdateDialog();

    private  val weightAlignDialog:CancelConfirmDialog = CancelConfirmDialog()

    private var weight = false;

    //退出称重校准
    fun exitWeightAlign(){
        CofarSDK.stoptWeightAlign()
//        CofarSDK.unregister(this)
        weight = false;
    }

    @Subscribe
    fun onDevStateEvent(event: DevStatusEvent) {

        if(!weight){
            return;
        }
        ThreadUtils.runOnMainThread {
            Log.d("ddddddddd", event.devInfo.toJson())



            if(event.devInfo.weightAlignStatus == (0).toByte()){ //正在标定不是
                 weightAlignDialog.dialog?.hide()
                 weightAlignDialog.showCancel = false;
                 weightAlignDialog.confirmStr = getString(R.string.exit_weight_align)

                 if (!weightAlignDialog.isAdded){
                         weightAlignDialog.title = getString(R.string.weight_aligning)
                         weightAlignDialog.showDialog(supportFragmentManager,"weight_align_dialog")
                 } else  {
                     if(event.devInfo.weightPol == (1).toByte()){
                         weightAlignDialog.binding.tvTitle.text = getString(R.string.weight_one_kg_tips)
                     }

                     if(event.devInfo.weightPol == (2).toByte()){
                         weightAlignDialog.binding.tvTitle.text = getString(R.string.weight_two_kg_tips)
                     }

                     weightAlignDialog.dialog?.show()
                 }

                 weightAlignDialog.onDialogClickListener = object :CancelConfirmDialog.OnDialogClickListener{

                     override fun onConfirm() {
                         exitWeightAlign()
                         weight = false;
                     }

                     override fun onCancel() {
                         exitWeightAlign()
                         weight = false
                     }

                 }
            }

            if(event.devInfo.weightAlignStatus == (2).toByte()){ //正在标定不是
//                CofarSDK.unregister(this)
                weightAlignDialog.dialog?.hide()
                weightAlignDialog.showCancel = false;
                weightAlignDialog.confirmStr = getString(R.string.exit_weight_align)

                if (!weightAlignDialog.isAdded){
                    weightAlignDialog.title = getString(R.string.weight_align_success)
                    weightAlignDialog.showDialog(supportFragmentManager,"weight_align_dialog")
                } else  {
                    weightAlignDialog.binding.tvTitle.text =  getString(R.string.weight_align_success)
                    weightAlignDialog.dialog?.show()
                }

                weightAlignDialog.onDialogClickListener = object :CancelConfirmDialog.OnDialogClickListener{

                    override fun onConfirm() {
                        exitWeightAlign()
                    }

                    override fun onCancel() {
                        exitWeightAlign()
                    }

                }

                exitWeightAlign()
            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.topBar.setTopBarTitle(getString(R.string.About))
        binding.topBar.listenBackClick {
            finish()
        }

        binding.devSn.text = getSN()



        recipeUpdateDialog.onDialogClickListener = object :RecipeUpdateDialog.OnDialogClickListener{
            override fun onConfirm() {
                print("onConfirm")
            }

            override fun onCancel() {
                print("onCancel")
            }

        }

        //点击食谱更新
        binding.updateRecipes.setOnClickListener{
            AppVerUtils.checkRecipeUpdate(true)
        }

        binding.ivLogo.setOnClickListener{

            weightAlignCount++
            if(weightAlignCount >= 7){
                weight = true;
                weightAlignCount =0

                var dailog =  CancelConfirmDialog()
                dailog.title = getString(R.string.change_lang_tips)
                dailog.showCancel = false;

                dailog.onDialogClickListener = object: CancelConfirmDialog.OnDialogClickListener {
                    override fun onConfirm() {

                    }

                    override fun onCancel() {
                    }

                }
                if(CofarSDK.devInfo().runningStatus == DevStatus.RUNNING){
                    dailog.showDialog(supportFragmentManager,"confirm")
                    return@setOnClickListener
                }else{
//                    CofarSDK.register(this)

                    //进入称重标定模式
                    CofarSDK.startWeightAlign()
                }



            }else{
//                CofarSDK.unregister(this)
            }

        }

        commonDialog.msg = getString(R.string.update_msg)
        commonDialog.hasOKBtn = false
        cancelConfirmDialog.title = getString(R.string.update_title)
        cancelConfirmDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    commonDialog.showDialog(supportFragmentManager, "commonDialog")
                    UpdateUtil.updateApp(
                        this@AboutActivity,
                        updateApkUrl,
                        object : OnDownloadListener {
                            override fun cancel() {
                                runOnUiThread {
                                    commonDialog.removeSelf()
                                }
                            }

                            override fun done(apk: File) {
                                GlobalToast.showToast(getString(R.string.finish_download))
                                runOnUiThread {
                                    commonDialog.removeSelf()
                                }
                            }

                            override fun downloading(max: Int, progress: Int) {
                                runOnUiThread {
                                    commonDialog.updateProgress(
                                        "${
                                            String.format(
                                                "%.0f",
                                                ((progress.toFloat() / max.toFloat()) * 100f)
                                            )
                                        }%"
                                    )
                                }
                            }

                            override fun error(e: Throwable) {
                                GlobalToast.showToast(getString(R.string.download_fail))
                                runOnUiThread {
                                    commonDialog.removeSelf()
                                }
                            }

                            override fun start() {
                                GlobalToast.showToast(getString(R.string.start_download))
                            }

                        })
                }

                override fun onCancel() {

                }
            }

        binding.tvUpdate.setOnClickListener {
            cancelConfirmDialog.showDialog(supportFragmentManager, "cancelConfirmDialog")
        }

        binding.tvAppName.text = AppUtils.getAppName()
        binding.tvAppVersion.text = "v${AppUtils.getAppVersionName()}"

    }

    override fun onResume() {
        super.onResume()
        FoodRepository.devInfo().observeStatus(onSuccess = {
            updateApkUrl = it?.apkUrl ?: ""
            if (it?.apkUpdate == true) {
                binding.tvUpdate.visibility = View.VISIBLE
            } else {
                binding.tvUpdate.visibility = View.INVISIBLE
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (commonDialog.dialog?.isShowing == true) {
            commonDialog.dismiss()
        }
        if (cancelConfirmDialog.dialog?.isShowing == true) {
            cancelConfirmDialog.dismiss()
        }
    }
}