package com.ys.bdtp.adm.mvvm.ui.screen.project

import android.net.ConnectivityManager
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import com.ys.bdtp.adm.app.tools.isNet
import com.ys.bdtp.adm.app.theme.underColor
import com.ys.bdtp.adm.mvvm.model.nt.FailureResponse
import com.ys.bdtp.adm.mvvm.model.nt.SuccessResponse
import com.ys.bdtp.adm.mvvm.model.db.entity.task.ProjectEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.UserEntity
import com.ys.bdtp.adm.mvvm.ui.compose.*
import com.ys.bdtp.adm.mvvm.ui.screen.main.LocalNavHostController
import com.ys.bdtp.adm.mvvm.ui.screen.main.Route
import com.ys.bdtp.adm.mvvm.vm.project.ProjectViewModel
import kotlinx.coroutines.launch
import org.kodein.di.compose.rememberInstance
import org.kodein.di.compose.rememberViewModel

/**
 * 项目界面
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Project() {
    val nav = LocalNavHostController.current!!
    val vm by rememberViewModel<ProjectViewModel>()
    val cm by rememberInstance<ConnectivityManager>()
    val scope = rememberCoroutineScope()
    // var user by remember { mutableStateOf<UserEntity?>(null) }
    var projects by remember { mutableStateOf<List<ProjectEntity>>(emptyList()) }
    var popupState by remember { mutableStateOf(false) }

    val lifecycleOwner = LocalLifecycleOwner.current
    /*val userFlow = vm.userFlow
    val userFlowLifecycleAware = remember(vm.userFlow, lifecycleOwner) {
        userFlow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
    }

    val user by userFlowLifecycleAware.collectAsState(null, scope.coroutineContext)*/
    val user by vm.userFlow.collectAsState()

    LaunchedEffect(Unit) {
        // isNet 联网，进行网络通信，获取账号信息也判断 token是否能用
        if (isNet(cm)) {
            when (val response = vm.getAccount()) {
                is SuccessResponse -> {
                    val account = response.data
                    vm.setCurrentAccount(account)
                    val up = vm.getUserWithProjectsById(account.id)

                    projects = up.projects
                }

                is FailureResponse -> {
                    val fail = response.fail
                    if (fail.code == "catch") {
                        // 提示网络问题
                    } else {
                        // 根据不同 code 进行不同操作
                    }
                }
            }
        } else {
            // 离线暂时有问题
            val u = vm.currentUser()
            if (u == null) {
                nav.navigate(Route.Login) {
                    popUpTo(Route.Project) {
                        inclusive = true
                    }
                }
            } else {
                val up = vm.getUserWithProjectsById(u.id)
                //user = up.user
                projects = up.projects
            }
        }
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        println("user:::::: $user ")
        println("user:::::: $user ")
        Head(
            left = {
                ProjectHeadLeft()
            },
            right = {
                HeadRight(
                    role = { "项目管家" },
                    click = {
                        popupState = !popupState
                    }
                )
            }
        )

        if (popupState) {
            LogoutPopup(
                click = {
                    scope.launch {
                        vm.logout()
                    }
                    popupState = false
                    nav.navigate(Route.Login) {
                        popUpTo(Route.Project) {
                            inclusive = true
                        }
                    }
                }
            )
        }

        Div(Div.Row)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .wrapContentWidth()
                .background(underColor)
                .padding(horizontal = 32.dp, vertical = 40.dp)
        ) {
            if (projects.isEmpty())
                Blank()
            else
                ProjectContent(projects)

        }
    }
}

@Preview(
    widthDp = 1280,
    heightDp = 800,
    showBackground = true,
    backgroundColor = 0xFFFFFFFF
)
@Composable
fun PreviewProject() {
    Project()
}