package com.lanyun.wanglaotou.composable

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.*

import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.insets.navigationBarsHeight
import com.google.accompanist.insets.statusBarsHeight

import com.lanyun.common.baseDate.Nav
import com.lanyun.common.baseDate.refreshMainNodeData
import com.lanyun.common.baseDate.refreshUserMessageData
import com.lanyun.common.baseDate.updateMainEvent
import com.lanyun.common.model.MainEvent
import com.lanyun.wanglaotou.KeyNavigationRoute
import com.lanyun.wanglaotou.NavigationHost
import com.lanyun.wanglaotou.public.AppBar
import com.lanyun.wanglaotou.public.AppBarDropDown
import com.lanyun.wanglaotou.public.BottomNavBar
import com.lanyun.wanglaotou.public.FollowMouseDropdownMenu
import com.lanyun.wanglaotou.ui.theme.*
import com.lanyun.wanglaotou.viewModel.MainViewModel
import okhttp3.internal.wait


/**
 * 主界面
 * [onFinish] 点击两次返回关闭页面
 */
@Composable
fun MainCompose(
    mainViewModel: MainViewModel,
    navHostController: NavHostController = rememberNavController(),
    onFinish: () -> Unit
) {
    //返回back堆栈的顶部条目
    val navBackStackEntry by navHostController.currentBackStackEntryAsState()
    //返回当前route
    val currentRoute = navBackStackEntry?.destination?.route ?: Nav.BottomNavScreen.HomeScreen.route
    if (isMainScreen(currentRoute)) {
        Scaffold (
            contentColor = MaterialTheme.colors.primary,
            topBar = {
                Column {
                    //内容不挡住状态栏 如果不设置颜色这里会自己适配，但可能产生闪烁
                    Spacer(
                        modifier = Modifier
                            .background(MaterialTheme.colors.background)
                            .statusBarsHeight()
                            .fillMaxWidth()
                    )

                    MainTopBar(mainViewModel,Nav.bottomNavRoute.value, navHostController)
                }
            },
            floatingActionButton = {
                MyFloatingActionButton(mainViewModel)
            },
            isFloatingActionButtonDocked = true,
            //底部导航栏
            bottomBar = {
                Column {
                   // BottomNavBar(Nav.bottomNavRoute.value, navHostController)
                    //内容不挡住导航栏 如果不设置颜色这里会自己适配，但可能产生闪烁
                    val isRunning = mainViewModel.isRunning.observeAsState()
                    Row (
                        modifier = Modifier
                            .height(BottomNavBarHeight)
                            .fillMaxWidth()
                            .background(grey4)
                            .clickable(onClick = {
                                mainViewModel.testCurrentServerRealPing()
                            }),
                        verticalAlignment = Alignment.CenterVertically

                            ){

                        Text(text = mainViewModel.viewStates.updateTestResultAction, color = Color.White, modifier = Modifier.padding(10.dp))


                    }

                    Spacer(
                        modifier = Modifier
                            .background(red)
                            .navigationBarsHeight()
                            .fillMaxWidth()
                    )
                }
            },
            //内容
            content = { paddingValues: PaddingValues ->
                //内容嵌套在Scaffold中
                NavigationHost(mainViewModel, navHostController, paddingValues, onFinish)

                OnTwoBackContent(navHostController)
            }
        )
    } else
    //独立页面
        NavigationHost(mainViewModel, navHostController, onFinish = onFinish)
}

//@Composable
//private  fun MyDropdownMenu(
//    mainViewModel: MainViewModel
//) {
//
//
//    DropdownMenu(
//        expanded = mainViewModel.viewStates.expanded,
//        onDismissRequest = { mainViewModel.updateExpanded(false) },
//    ) {
//        DropdownMenuItem(onClick = {
//            updateMainEvent(MainEvent.MainNodeUpdate)
////            refreshUserMessageData.value = System.currentTimeMillis().toString()
////            refreshMainNodeData.value = MainEvent.MainNodeUpdate
//            mainViewModel.updateExpanded(false)
//        }) {
//            Text("刷新线路")
//        }
//        DropdownMenuItem(onClick = {
//            updateMainEvent(MainEvent.MainTcpPing)
//            mainViewModel.updateExpanded(false)
//        }) {
//            Text("线路延迟检测")
//        }
//
//    }
//}

/**
 * 主页面的标题栏
 */
@Composable
private fun MainTopBar(   mainViewModel: MainViewModel,bottomNavScreen: Nav.BottomNavScreen, navHostController: NavHostController) {
    when (bottomNavScreen) {
        //首页
        Nav.BottomNavScreen.HomeScreen -> {


               // rightIcon = Icons.Default.Search,
                //跳转到搜索页面
               // onRightClick = { navHostController.navigate(KeyNavigationRoute.SEARCH.route) })
        }
        //项目
        Nav.BottomNavScreen.SettingsScreen -> {
            AppBar(
                "设置",
            )
//            val projectViewModel: ProjectViewModel = viewModel()
//
//            //请求项目列表数据
//            projectViewModel.getProjectTreeData()

   //         val projectTreeData = projectViewModel.projectTreeData.observeAsState()

        }

    }
}

/**
 * 在主界面点击两次返回按钮,返回到手机桌面,再重新打开app,此时显示退出时的主界面
 */
@Composable
private fun OnTwoBackContent(navHostController: NavHostController) {
    if (Nav.twoBackFinishActivity) {
        LaunchedEffect(Unit) {
            navHostController.navigate(Nav.bottomNavRoute.value.route) {
                popUpTo(navHostController.graph.findStartDestination().id) {
                    saveState = true
                }
                //避免重建
                launchSingleTop = true
                //重新选择以前选择的项目时，恢复状态
                restoreState = true
            }
            Nav.twoBackFinishActivity = false
        }
    }
}


/**
 * 是否是首页的内容
 */
fun isMainScreen(route: String): Boolean = when (route) {
    Nav.BottomNavScreen.HomeScreen.route,
    Nav.BottomNavScreen.SettingsScreen.route -> true
    else -> false
}