package com.casic.br.view.device

import android.graphics.Color
import android.graphics.Typeface
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.casic.br.R
import com.casic.br.adapter.TabPagerAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.toChineseTypeName
import com.casic.br.fragment.cooker.ControlPageFragment
import com.casic.br.fragment.cooker.ServicePageFragment
import com.casic.br.fragment.cooker.StatusPageFragment
import com.casic.br.utils.LocaleConstant
import com.casic.br.utils.TuyaDeviceListener
import com.casic.br.utils.WebImageViewHelper
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import com.tuya.smart.android.device.bean.UpgradeInfoBean
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.IGetOtaInfoCallback
import com.tuya.smart.sdk.api.IResultCallback
import com.tuya.smart.sdk.api.ITuyaDevice
import com.tuya.smart.sdk.api.ITuyaOta
import kotlinx.android.synthetic.main.activity_cooker.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 燃气灶
 * */
class CookerActivity : KotlinBaseActivity() {

    private val kTag = "CookerActivity"
    private val context = this@CookerActivity
    private val inflater by lazy { LayoutInflater.from(this) }
    private var fragmentPages: ArrayList<Fragment> = ArrayList()
    private lateinit var deviceInstance: ITuyaDevice
    private lateinit var tuyaOTA: ITuyaOta

    override fun initLayoutView(): Int = R.layout.activity_cooker

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        initLayoutImmersionBar(rootView)
        ImmersionBar.with(this).statusBarDarkFont(true).init()

        leftBackView.setOnClickListener { finish() }
    }

    override fun initData() {
        val deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        tuyaOTA = TuyaHomeSdk.newOTAInstance(deviceId)
        //控制设备前必须初始家庭化数据，每次 App 活跃期间，初始化一次即可。
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)

        val deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(deviceId)
        if (deviceBean == null) {
            "查询设备信息失败，请检查设备是否已离线".show(this)
            return
        }
        titleView.text = deviceBean.toChineseTypeName()
        WebImageViewHelper.setImage(deviceLogoView, deviceBean.iconUrl)

        fragmentPages.add(ControlPageFragment(deviceInstance))
        fragmentPages.add(StatusPageFragment(deviceInstance))
        fragmentPages.add(ServicePageFragment())

        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d(kTag, "onDpUpdate: $dpStr")

                val controlMsg = ControlPageFragment.weakReference.obtainMessage()
                controlMsg.what = 2022092901
                controlMsg.obj = dpStr
                ControlPageFragment.weakReference.sendMessage(controlMsg)

                val statusMsg = StatusPageFragment.weakReference.obtainMessage()
                statusMsg.what = 2022092902
                statusMsg.obj = dpStr
                StatusPageFragment.weakReference.sendMessage(statusMsg)

                val deviceBeanMsg = StatusPageFragment.weakReference.obtainMessage()
                deviceBeanMsg.what = 2022092903
                deviceBeanMsg.obj = deviceBean
                StatusPageFragment.weakReference.sendMessage(deviceBeanMsg)
            }
        })
    }

    override fun initEvent() {
        rightOperateView.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(arrayListOf("固件升级", "移除设备"))
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        when (position) {
                            0 -> {
                                tuyaOTA.getOtaInfo(object : IGetOtaInfoCallback {
                                    override fun onSuccess(upgradeInfoBeans: MutableList<UpgradeInfoBean>?) {
                                        if (upgradeInfoBeans.isNullOrEmpty()) {
                                            "无新版本可用".show(context)
                                        }
                                        val mainModel = upgradeInfoBeans!![0]
                                        when (mainModel.upgradeStatus) {
                                            1 -> updateVersion()
                                            2 -> {

                                            }
                                            else -> "主联网模组无新版本可用".show(context)
                                        }

                                        val mcuModel = upgradeInfoBeans[1]
                                        when (mcuModel.upgradeStatus) {
                                            1 -> updateVersion()
                                            2 -> {

                                            }
                                            else -> "MCU模块无新版本可用".show(context)
                                        }
                                    }

                                    override fun onFailure(code: String?, error: String?) {

                                    }
                                })
                            }
                            1 -> deviceInstance.removeDevice(object : IResultCallback {
                                override fun onError(code: String?, error: String?) {
                                    Log.d(kTag, "onError: $error")
                                }

                                override fun onSuccess() {
                                    finish()
                                }
                            })
                        }
                    }
                })
                .build().show()
        }

        deviceViewPager.adapter =
            TabPagerAdapter(fragmentPages, LocaleConstant.DEVICE_PAGE_TITLE, supportFragmentManager)
        deviceTabLayout.setupWithViewPager(deviceViewPager)
        deviceTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val textView = inflater.inflate(R.layout.item_top_tab, null) as TextView
                textView.textSize = 28f
                textView.typeface = Typeface.DEFAULT_BOLD
                textView.text = tab!!.text
                tab.customView = textView
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView = null
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
    }

    private fun updateVersion() {
        AlertControlDialog.Builder()
            .setContext(this)
            .setTitle("版本升级")
            .setMessage("有新版本可以升级，是否升级？")
            .setNegativeButton("取消")
            .setPositiveButton("确定")
            .setOnDialogButtonClickListener(object :
                AlertControlDialog.OnDialogButtonClickListener {
                override fun onCancelClick() {
                    tuyaOTA.startOta()
                }

                override fun onConfirmClick() {

                }
            })
            .build().show()
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceInstance.unRegisterDevListener()
        deviceInstance.onDestroy()
    }
}