package com.casic.br.view

import android.util.Log
import android.view.KeyEvent
import android.view.MenuItem
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.amap.api.location.AMapLocation
import com.casic.br.R
import com.casic.br.adapter.ViewPagerAdapter
import com.casic.br.fragment.*
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocaleConstant
import com.casic.br.utils.LocationHelper
import com.casic.br.vm.UserViewModel
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.extensions.toJson
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.bean.HomeBean
import com.tuya.smart.home.sdk.callback.ITuyaGetHomeListCallback
import com.tuya.smart.home.sdk.callback.ITuyaHomeResultCallback
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : KotlinBaseActivity() {

    private val kTag = "MainActivity"
    private var menuItem: MenuItem? = null
    private var fragmentPages: ArrayList<Fragment> = ArrayList()
    private var clickTime: Long = 0

    init {
        fragmentPages.add(HomePageFragment())
        fragmentPages.add(DevicePageFragment())
        fragmentPages.add(ShopPageFragment())
        fragmentPages.add(MessagePageFragment())
        fragmentPages.add(MinePageFragment())
    }

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

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

    override fun initData() {
        val userViewModel = ViewModelProvider(this)[UserViewModel::class.java]
        //每次都更新PUSH_ID，防止收不到消息
        val clientId = SaveKeyValues.getValue(LocaleConstant.PUSH_CLIENT_ID, "") as String
        val currentUser = DeserializeModel.getUserModel() ?: return
        currentUser.attr1 = clientId
        userViewModel.updateUserInfo(currentUser)
    }

    override fun observeRequestState() {
//        createHome()
//        dismissHome()
    }

    override fun initEvent() {
        bottomNavigation.itemIconTintList = null
        bottomNavigation.setOnItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_home -> {
                    mainViewPager.currentItem = 0
                }
                R.id.nav_device -> {
                    if (DeserializeModel.isLogin()) {
                        mainViewPager.currentItem = 1
                    } else {
                        navigatePageTo<LoginActivity>()
                    }
                }
                R.id.nav_shop -> {
                    mainViewPager.currentItem = 2
                }
                R.id.nav_message -> {
                    if (DeserializeModel.isLogin()) {
                        mainViewPager.currentItem = 3
                    } else {
                        navigatePageTo<LoginActivity>()
                    }
                }
                R.id.nav_mine -> {
                    mainViewPager.currentItem = 4
                }
            }
            false
        }
        mainViewPager.adapter = ViewPagerAdapter(fragmentPages, supportFragmentManager)
        mainViewPager.offscreenPageLimit = fragmentPages.size //缓存页数
        mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                if (menuItem != null) {
                    menuItem!!.isChecked = false
                } else {
                    bottomNavigation.menu.getItem(0).isChecked = false
                }
                menuItem = bottomNavigation.menu.getItem(position)
                menuItem!!.isChecked = true
            }
        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - clickTime > 2000) {
                "再按一次退出程序".show(this)
                clickTime = System.currentTimeMillis()
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        } else super.onKeyDown(keyCode, event)
    }

    private fun dismissHome() {
        TuyaHomeSdk.getHomeManagerInstance().queryHomeList(object : ITuyaGetHomeListCallback {
            override fun onSuccess(homeBeans: List<HomeBean>) {
                Log.d(kTag, homeBeans.toJson())
//                homeBeans.forEach {
//                    Log.d(kTag, it.toJson())
//                    TuyaHomeSdk.newHomeInstance(it.homeId)
//                        .dismissHome(object : com.tuya.smart.sdk.api.IResultCallback {
//                            override fun onError(code: String?, error: String?) {
//
//                            }
//
//                            override fun onSuccess() {
//                                Log.d(kTag, it.homeId.toString())
//                            }
//                        })
//                }
            }

            override fun onError(errorCode: String, error: String) {

            }
        })
    }

    private fun createHome() {
        LocationHelper.obtainCurrentLocation(this, object : LocationHelper.ILocationListener {
            override fun onAMapLocationGet(aMapLocation: AMapLocation?) {
                /**
                 * 家庭是智能生活 App SDK 开发下实际场景的最大单位。
                 * IoT 设备的添加、编辑、移除、状态变化的监听基于家庭下。
                 * 用户账号下创建任意多个家庭。
                 * */
                if (aMapLocation == null) {
                    "信号弱，创建家庭失败".show(this@MainActivity)
                    LoadingDialogHub.dismiss()
                    return
                }
                val userModel = DeserializeModel.getUserModel()!!
                TuyaHomeSdk.getHomeManagerInstance().createHome(
                    "${userModel.phone}的家", aMapLocation.longitude, aMapLocation.latitude,
                    aMapLocation.address, arrayListOf("1"), object : ITuyaHomeResultCallback {
                        override fun onSuccess(bean: HomeBean?) {
                            Log.d(kTag, "homeId: ${bean!!.homeId}")
                        }

                        override fun onError(errorCode: String?, errorMsg: String?) {
                            Log.e(kTag, "errorCode: $errorCode ---- $errorMsg")
                        }
                    })
            }
        })
    }
}