package com.develop.main.ui

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.databinding.ViewDataBinding
import androidx.drawerlayout.widget.DrawerLayout.DrawerListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.manager.WifiHelp
import com.develop.base.widgets.CommonPopupWindow
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.DataFactory
import com.develop.common.data_repo.db.FunType
import com.develop.common.data_repo.db.NewsModel
import com.develop.common.data_repo.db.RecipesType
import com.develop.common.data_repo.db.entity.UserInfo
import com.develop.common.router.Screens
import com.develop.common.tag.*
import com.develop.common.ui.CommonBVMActivity
import com.develop.common.widget.HomeFunctionTopBar
import com.develop.common.widget.HomeOrBack
import com.develop.common.widget.NewsLayout
import com.develop.main.R
import com.develop.main.databinding.ActivityHomeBinding
import com.develop.main.viewmodel.HomeViewModel

@Route(path = Screens.Main.HOME)
class HomeActivity : CommonBVMActivity<ActivityHomeBinding, HomeViewModel>() {

    private val modesFragment by lazy {
        ModesFragment()
    }

    private val recipesFragment by lazy {
        RecipesFragment()
    }
    private var newsLayout: NewsLayout? = null

    private var newsList = mutableListOf<NewsModel>()

    private val newsPopupWindow by lazy {
        CommonPopupWindow.ViewBuilder<NewsLayout>().width(dp750)
            .height(LinearLayout.LayoutParams.MATCH_PARENT).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 currModeEntrance = Recipes

    private lateinit var wifiHelp: WifiHelp

    override fun createViewModel(): HomeViewModel {
        return getViewModel(HomeViewModel::class.java)
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initFragment(intent)
        initCallbackAndListener()
    }

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

    private fun initFragment(intent: Intent?, isFromNewIntent: Boolean = false) {
        val extras = intent?.extras
        currModeEntrance = extras?.getInt(MODE_ENTRANCE) ?: Recipes
        binding.functionTopBar.setTitle(extras?.getString(HOME_TITLE) ?: "")
        if ((extras?.getInt(RECIPES_TYPE) ?: LocalFood) == LocalFood) {
            viewModel.apply {
                recipesType = RecipesType.LOCAL
                isFromDownloadNewRecipesEntrance = false
            }
        } else {
            viewModel.apply {
                recipesType = RecipesType.ONLINE
                isFromDownloadNewRecipesEntrance = true
            }
        }
        binding.functionTopBar.setHomeOrBack(HomeOrBack.Home)
        if (currModeEntrance == Recipes) {
            if (isFromNewIntent) {
                replaceFragment(R.id.fragment_container, recipesFragment)
            } else {
                addFragment(R.id.fragment_container, recipesFragment)
            }
        } else {
            if (isFromNewIntent) {
                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 onNotifyClick() {
                    viewModel.getNotices()
                    newsPopupWindow.showAtLocation(binding.functionTopBar, Gravity.END, 0, 0)
                }

                override fun onHomeOrBackClick(homeOrBack: HomeOrBack) {
                    if (homeOrBack == HomeOrBack.Home) {
                        navigateTo(Screens.Main.ENTRANCE_CHOSEN)
                        finish()
                    } else {
                        //搜索后，返回后当前还是onLine的菜谱，还是显示返回，可以返回本地菜谱
                        if (viewModel.recipesType == RecipesType.ONLINE && viewModel.isSearch
                            && !viewModel.isFromDownloadNewRecipesEntrance
                        ) {
                            binding.functionTopBar.setHomeOrBack(HomeOrBack.Back)
                        } else {
                            binding.functionTopBar.setHomeOrBack(HomeOrBack.Home)
                        }
                        viewModel.apply {
                            refreshRecipesLiveData.postValue(true)
                            isSearch = false
                        }
                    }
                }

                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 {
            navigateTo(Screens.Setting.MAIN_SETTING)
            binding.contentView.closeDrawers()
        }

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

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

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

        viewModel.apply {
            homeOrBackLiveData.observe(this@HomeActivity) {
                binding.functionTopBar.setHomeOrBack(it)
            }
        }
        viewModel.noticesLiveData.observe(this) { data ->
            val newsModelList = mutableListOf<NewsModel>()
            data?.forEach {
                newsModelList.add(NewsModel(it.title, it.content, false))
            }
            newsList.clear()
            newsList.addAll(newsModelList)
            newsLayout?.updateNewsData(newsList)
        }

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

    private fun updateUserInfoUi(userInfo: UserInfo?) {
        if (userInfo?.userName != null) {
            binding.functionTopBar.setUserName(userInfo.userName ?: "")
            binding.tvUserName.text = userInfo.userName ?: ""
            val icon = when (userInfo.userAvatar?.toInt() ?: 0) {
                0 -> {
                    com.develop.common.R.drawable.ic_icon1
                }
                1 -> {
                    com.develop.common.R.drawable.ic_icon2
                }
                2 -> {
                    com.develop.common.R.drawable.ic_icon3
                }
                3 -> {
                    com.develop.common.R.drawable.ic_icon4
                }
                4 -> {
                    com.develop.common.R.drawable.ic_icon5
                }
                else -> {
                    com.develop.common.R.drawable.ic_icon6
                }
            }
            binding.ivAvatar.setImageResource(icon)
        } else {
            binding.ivAvatar.setImageResource(com.develop.common.R.drawable.ic_no_user)
            binding.functionTopBar.setUserName(getString(com.develop.common.R.string.login))
            binding.tvUserName.text = getString(com.develop.common.R.string.login)
        }
    }

    companion object {
        var dp1080 = (com.develop.base.R.dimen.convert_1080px).resId2Dimension().toInt()
        var dp160 = (com.develop.base.R.dimen.convert_160px).resId2Dimension().toInt()
        var dp750 = (com.develop.base.R.dimen.convert_750px).resId2Dimension().toInt()
    }

    override fun onResume() {
        super.onResume()
        wifiHelp.scan()
        val userInfo = FoodDataProvider
            .getUserDatabase()
            .userInfoDao()
            .queryUserInfoByUserId(CURRENT_USER_ID)
        updateUserInfoUi(userInfo)
    }

    override fun onDestroy() {
        super.onDestroy()
        wifiHelp.destroy()
    }
}