package com.develop.main.init.ui

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.food.base.common.CURRENT_USER_ID_TAG
import com.develop.food.base.common.FOOD_LIST_TYPE
import com.develop.food.base.common.FOOL_LIST_TITLE
import com.develop.food.base.common.Favourite
import com.develop.food.base.common.History
import com.develop.food.base.common.MODE_ENTRANCE
import com.develop.food.base.common.POLICY_FROM_MAIN_SETTING
import com.develop.food.base.common.Recipes
import com.develop.food.base.common.WIFI_FROM_MAIN_SETTING
import com.develop.food.base.data.FunType
import com.develop.food.base.data.model.NewsModel
import com.develop.food.base.event.FinishAtyEvent
import com.develop.food.base.event.TokenInvalidateEvent
import com.develop.food.base.ext.src
import com.develop.food.base.manager.wifi.WifiData
import com.develop.food.base.manager.wifi.WifiHelp
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.UserInfo
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.GlobalToast
import com.develop.food.base.utils.MmkvUtils
import com.develop.food.base.utils.NetWorkManager
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.widgets.CommonPopupWindow
import com.develop.food.base.widgets.HomeFunctionTopBar
import com.develop.food.base.widgets.NewsLayout
import com.develop.main.R
import com.develop.main.databinding.ActivityHomeBinding
import com.develop.main.init.ui.viewmodel.HomeViewModel
import com.google.gson.Gson
import org.greenrobot.eventbus.Subscribe

@Route(path = Screens.Main.HOME)
class HomeActivity : BaseActivity<ActivityHomeBinding>(), NetWorkManager.OnSysChangeListener {
    private val recipesFragment by lazy {
        RecipesFragment()
    }
    private val modesFragment by lazy {
        ModesFragment()
    }

    private val homeViewModel by lazy {
        getViewModel(HomeViewModel::class.java)
    }

    private lateinit var wifiHelp: WifiHelp

    private var newsLayout: NewsLayout? = null

    private var newsList = mutableListOf<NewsModel>()

    private val newsPopupWindow by lazy {
        CommonPopupWindow.ViewBuilder<NewsLayout>()
            .width(LinearLayout.LayoutParams.MATCH_PARENT)
            .height(
                ResDimension(R.dimen.convert_1080px).toInt()
                        + ResDimension(R.dimen.convert_160px).toInt()
            )
            .outsideTouchable(true)
            .focusable(true)
            .alpha(0.5f)
            .clippingEnabled(false)
            .view(NewsLayout(this))
            .onShowBefore { popupWindow, view ->
                view.apply {
                    newsLayout = this
                    updateNewsData(newsList)
                    onNewsBackClickListener = object : NewsLayout.OnNewsNewsBackClickListener {
                        override fun onNewsBackClick() {
                            popupWindow.dismiss()
                        }
                    }
                }
            }
            .build<ViewDataBinding>(this)
    }

    private var modeEntrance = Recipes

    private val userInfoLiveData by lazy {
        MutableLiveData<UserInfo>()
    }

    override fun createViewBinding(inflater: LayoutInflater): ActivityHomeBinding {
        return ActivityHomeBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initFragment(intent)
        initCallbackAndListener()
        NetWorkManager.get().addTimeChangeListener(this)
        wifiHelp = WifiHelp.Build(this).build()
        val wifiData = MmkvUtils.getString("connectedWifi")
        if (!wifiData.isNullOrEmpty() && wifiHelp.getConnectionWifi() == null) {
            wifiHelp.setWifiEnabled(true)
            wifiHelp.connect(Gson().fromJson(wifiData, WifiData::class.java))
        }
        userInfoLiveData.observe(this) {
            if (it?.userName != null) {
                binding.functionTopBar.setUserName(it.userName ?: "")
                binding.tvUserName.text = it.userName ?: ""
                val icon = when (it.userAvatar?.toInt() ?: 0) {
                    0 -> {
                        R.drawable.ic_icon1
                    }
                    1 -> {
                        R.drawable.ic_icon2
                    }
                    2 -> {
                        R.drawable.ic_icon3
                    }
                    3 -> {
                        R.drawable.ic_icon4
                    }
                    4 -> {
                        R.drawable.ic_icon5
                    }
                    else -> {
                        R.drawable.ic_icon6
                    }
                }
                binding.ivAvatar.src = icon
            } else {
                binding.ivAvatar.src = R.drawable.ic_icon1
                binding.functionTopBar.setUserName(getString(R.string.login))
                binding.tvUserName.text = getString(R.string.login)
            }

        }
        binding.ivAvatar.setOnClickListener {
            navigateTo(Screens.Auth.MEMBER) {
                withBoolean("enter_from_home", true)
            }
        }
       // homeViewModel.getNotices()

        homeViewModel.noticesLiveData.observe(this) {
            newsList.clear()
            newsList.addAll(it)
            newsLayout?.updateNewsData(newsList)
        }
    }

    private fun queryUserInfo() {
        FoodDataProvider.getUserDatabase().runInTransaction {
            val userId = MmkvUtils.getLong(CURRENT_USER_ID_TAG)
            val userInfo = FoodDataProvider.getUserDatabase().userInfoDao()
                .queryUserInfoByUserId(userId)
            userInfoLiveData.postValue(userInfo)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        initFragment(intent, true)
    }


    private fun initFragment(intent: Intent?, isFromNew: Boolean = false) {
        modeEntrance = intent?.extras?.getInt(MODE_ENTRANCE) ?: Recipes
        if (modeEntrance == Recipes) {
            binding.functionTopBar.setCurrentFunType(FunType.LocalRecipes)
            if (isFromNew) {
                replaceFragment(R.id.fragment_container, recipesFragment)
            } else {
                addFragment(R.id.fragment_container, recipesFragment)
            }
        } else {
            binding.functionTopBar.setCurrentFunType(FunType.Modes)
            if (isFromNew) {
                replaceFragment(R.id.fragment_container, modesFragment)
            } else {
                addFragment(R.id.fragment_container, modesFragment)
            }
        }
    }

    private fun initCallbackAndListener() {
        wifiHelp = WifiHelp.Build(this).setAlreadyConnectionCallback {
            it?.apply {
                binding.functionTopBar.setNetRssi(rssi)

            }
        }.build()

        binding.functionTopBar.onHomeFunctionClickListener =
            object : HomeFunctionTopBar.OnHomeFunctionClickListener {
                override fun onModeClick(funType: FunType) {
                    if (funType == FunType.LocalRecipes) {
                        replaceFragment(R.id.fragment_container, recipesFragment)
                        homeViewModel.recipesType = HomeViewModel.RecipesType.LOCAL
                        homeViewModel.refreshRecipesLiveData.postValue(true)
                    } else if (funType == FunType.Modes) {
                        replaceFragment(R.id.fragment_container, modesFragment)
                    }
                }

                override fun onNotifyClick() {
                    homeViewModel.getNotices()
                    newsPopupWindow.showAtLocation(binding.functionTopBar, Gravity.TOP, 0, 0)

                }

                override fun onTabClick() {
                    binding.contentView.openDrawer(binding.rightContentLayout)
                }

                override fun onWifiClick() {
                    navigateTo(Screens.Setting.WIFI) {
                        val bundle = Bundle()
                        bundle.putBoolean(WIFI_FROM_MAIN_SETTING, true)
                        with(bundle)
                    }
                }

                override fun onUserClick() {
                    navigateTo(Screens.Auth.MEMBER) {
                        withBoolean("enter_from_home", true)
                    }
                }

            }

        binding.rightContentLayout.setOnClickListener {

        }

        binding.settingLayout.setOnClickListener {
            binding.contentView.closeDrawers()
            navigateTo(Screens.Setting.MAIN_SETTING)
        }

        binding.favouriteLayout.setOnClickListener {
            binding.contentView.closeDrawers()
            val bundle = Bundle()
            bundle.putString(FOOL_LIST_TITLE, getString(R.string.favourite_recipes))
            bundle.putInt(FOOD_LIST_TYPE, Favourite)
            navigateTo(Screens.Main.FOOD_LIST) {
                with(bundle)
            }
        }

        binding.historyLayout.setOnClickListener {
            binding.contentView.closeDrawers()
            val bundle = Bundle()
            bundle.putString(FOOL_LIST_TITLE, getString(R.string.cook_history))
            bundle.putInt(FOOD_LIST_TYPE, History)
            navigateTo(Screens.Main.FOOD_LIST) {
                with(bundle)
            }
        }

        binding.policyLayout.setOnClickListener {
            binding.contentView.closeDrawers()
            val bundle = Bundle()
            bundle.putBoolean(POLICY_FROM_MAIN_SETTING, true)
            navigateTo(Screens.Setting.POLICY) {
                with(bundle)
            }
        }

        homeViewModel.apply {
            netFoodLiveData.observe(this@HomeActivity) {
                binding.functionTopBar.updateNetFunType()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        wifiHelp.scan()
        queryUserInfo()
    }

    override fun onDestroy() {
        super.onDestroy()
        NetWorkManager.get().stopTask()
        wifiHelp.destroy()
    }

    override fun onChange(manager: NetWorkManager?, type: Int) {
        if (type == NetWorkManager.SYS_CHANGE_NET_STATE) {
            val rssi = wifiHelp.getConnectionWifi()?.rssi ?: 0
            binding.functionTopBar.setNetRssi(rssi)
        }
    }

    @Subscribe
    fun onTokenInvalidateEvent(event: TokenInvalidateEvent) {
        GlobalToast.showToast(getString(R.string.login_expire_tips))
        navigateTo(Screens.Auth.MEMBER) {
            val bundle = Bundle()
            bundle.putBoolean("isTokenOut", true)
            with(bundle)
        }
        finish()
    }

    @Subscribe
    fun  onFinishAtyEvent(event: FinishAtyEvent){
        finish()
    }
}