package com.develop.setting.init.ui

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
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.ui.BaseActivity
import com.develop.food.base.utils.AppVerUtils
import com.develop.food.base.utils.GlobalToast
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.utils.ThreadUtils
import com.develop.food.base.utils.UpdateUtil
import com.develop.food.base.utils.getSN
import com.develop.food.base.utils.isNightTheme
import com.develop.food.base.utils.toJson
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.food.base.widgets.CommonDialog
import com.develop.food.base.widgets.PwdDialog
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 var adbCount = 0

    private var testCount = 0

    private var tpCount = 0

    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)
        if (isNightTheme()) {
            binding.ivLogo.setBackgroundResource(R.drawable.ic_app_logo)
            val param = binding.ivDownload.layoutParams as LinearLayout.LayoutParams
            param.width = ResDimension(R.dimen.convert_98px).toInt()
            param.height = ResDimension(R.dimen.convert_98px).toInt()
            binding.ivDownload.layoutParams = param
            binding.tvApk .text = "APK"
            binding.tvMcu .text = "MCU"
            binding.tvModel .text = "MODEL"
            binding.tvTp .text = "TP"
            binding.tvSn .text = "SN"
        }
        binding.topBar.setTopBarTitle(getString(R.string.About))
        binding.topBar.listenBackClick {
            finish()
        }


        binding.devSn.text = getSN()

        CofarSDK.devInfo().let {
            binding.tvMcuVersion.text =
                (it.manufacturer.toString() + "P" + it.haradware.toString() + "S" + it.software.toString())
        }

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

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

            }

        binding.tvUpdateFirmware.setOnClickListener {
            val packageName = "com.abupdate.fota_demo_iot"
            val intent = packageManager.getLaunchIntentForPackage(packageName)

            if (intent != null) {
                // 存在可以处理的应用程序
                // 启动应用程序
                startActivity(intent)
            } else {
                // 未找到指定包名的应用程序
            }

        }
        binding.devSn.setOnClickListener {
            testCount++
            if (testCount >= 7) {
                testCount = 0

                //2023年06月29日14:16:18 处理密码弹出
                val pwdDialog = PwdDialog()
                pwdDialog.title = getString(com.develop.base.R.string.enter_password)
                pwdDialog.showDialog(supportFragmentManager, "pwdDialog")
                pwdDialog.onDialogClickListener = object : PwdDialog.OnDialogClickListener {

                    override fun onConfirm(pwd: String) {
                        if ("12345678".equals(pwd)) {
                            // 创建启动目标活动的Intent
                            val intent = Intent()
                            intent.component = ComponentName(
                                "com.zavier.androidrk3326functiontest",
                                "com.zavier.androidrk3326functiontest.MainFunctionActivity"
                            )

                            // 启动目标活动
                            startActivity(intent)
                        } else {
                            GlobalToast.showToast(getString(com.develop.base.R.string.account_password_error))
                        }
                    }

                    override fun onCancel() {

                    }
                }


            }
        }

        binding.tvTpVersion.setOnClickListener {
            tpCount++
            if (tpCount >= 7) {
                tpCount = 0


                val ctx = this
                //2023年06月29日14:16:18 处理密码弹出
                val pwdDialog = PwdDialog()
                pwdDialog.title = getString(com.develop.base.R.string.enter_password)
                pwdDialog.showDialog(supportFragmentManager, "pwdDialog")
                pwdDialog.onDialogClickListener = object : PwdDialog.OnDialogClickListener {

                    override fun onConfirm(pwd: String) {
                        if ("12345678".equals(pwd)) {
                            togglePointerLocation(ctx)
                        } else {
                            GlobalToast.showToast(getString(com.develop.base.R.string.account_password_error))
                        }
                    }

                    override fun onCancel() {

                    }
                }


            }
        }



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

        binding.ivLogo.setOnClickListener {

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

                val ctx = this
                //2023年06月29日14:16:18 处理密码弹出
                val pwdDialog = PwdDialog()
                pwdDialog.title = getString(com.develop.base.R.string.enter_password)
                pwdDialog.showDialog(supportFragmentManager, "pwdDialog")
                pwdDialog.onDialogClickListener = object : PwdDialog.OnDialogClickListener {

                    override fun onConfirm(pwd: String) {
                        if ("12345678".equals(pwd)) {
                            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")
                            } else {
//                    CofarSDK.register(this)
                                //进入称重标定模式
                                CofarSDK.startWeightAlign()
                            }

                        } else {
                            GlobalToast.showToast(getString(com.develop.base.R.string.account_password_error))
                        }
                    }

                    override fun onCancel() {

                    }
                }


            } 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.tvAppVersion.setOnClickListener {
            adbCount++
            if (adbCount >= 7) {
                adbCount = 0

                val ctx = this
                //2023年06月29日14:16:18 处理密码弹出
                val pwdDialog = PwdDialog()
                pwdDialog.title = getString(com.develop.base.R.string.enter_password)
                pwdDialog.showDialog(supportFragmentManager, "pwdDialog")
                pwdDialog.onDialogClickListener = object : PwdDialog.OnDialogClickListener {

                    override fun onConfirm(pwd: String) {
                        if ("12345678".equals(pwd)) {
                            if (isAdbDebuggingEnabled(ctx)) {
                                Toast.makeText(ctx, "adb disable", Toast.LENGTH_SHORT).show()
                                toggleAdbDebugging(ctx, false)
                            } else {
                                Toast.makeText(ctx, "adb enable", Toast.LENGTH_SHORT).show()
                                toggleAdbDebugging(ctx, true)
                            }
                        } else {
                            GlobalToast.showToast(getString(com.develop.base.R.string.account_password_error))
                        }
                    }

                    override fun onCancel() {

                    }
                }


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

        binding.tvTpVersion.text = Build.DISPLAY
    }

    fun isAdbDebuggingEnabled(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Settings.Secure.getInt(
                context.contentResolver,
                Settings.Global.ADB_ENABLED,
                0
            ) != 0
        } else {
            Settings.Secure.getInt(
                context.contentResolver,
                Settings.Secure.ADB_ENABLED,
                0
            ) != 0
        }
    }


    fun toggleAdbDebugging(context: Context, enable: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Settings.Secure.putInt(
                context.contentResolver,
                Settings.Global.ADB_ENABLED,
                if (enable) 1 else 0
            )
        } else {
            Settings.Secure.putInt(
                context.contentResolver,
                Settings.Secure.ADB_ENABLED,
                if (enable) 1 else 0
            )
        }
    }


    override fun onResume() {
        super.onResume()
        FoodRepository.devInfo().observeStatus(onSuccess = {
            updateApkUrl = it?.apkUrl ?: ""
            if (it?.apkUpdate == true) {

                binding.tvUpdate.performClick()
            }
            binding.tvUpdate.visibility = View.VISIBLE
            binding.tvUpdateFirmware.visibility = View.VISIBLE
        })
    }
    fun togglePointerLocation(context: Context) {
        val currentSetting = Settings.System.getInt(context.contentResolver, "pointer_location", 0)
        val newSetting = if (currentSetting == 0) 1 else 0
        Settings.System.putInt(context.contentResolver, "pointer_location", newSetting)
    }


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