package com.lanyun.wanglaotou.composable

import android.util.Log
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.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.AndroidUiFrameClock
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
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.extension.toTrafficString
import com.lanyun.wanglaotou.model.UserSubModel
import com.lanyun.wanglaotou.public.*
import com.lanyun.wanglaotou.ui.theme.*
import com.lanyun.wanglaotou.util.Utils
import com.lanyun.wanglaotou.viewModel.*


@Composable
fun HomeCompose(
    mainViewModel: MainViewModel,
    navHostController: NavHostController,
    viewModel: HomeViewModel = viewModel()
) {
    val context = LocalContext.current
    val viewStates = viewModel.viewStates
    viewModel.apply {
        if (isLogin()) {
            //监听 登录状态
            LaunchedEffect(refreshUserMessageData.value) {
                when(refreshMainNodeData.value){
                    MainEvent.MainLegacy->{
                        viewModel.updateLegacyItme()
                        updateMainEvent(MainEvent.IsReqFsh,false)
                    }
                    MainEvent.UserSubData -> {
                        viewModel.dispatch(HomeViewAction.updateSubModel)
                       // updateMainEvent(MainEvent.IsReq,false)
                    }
                    MainEvent.Login -> {
                        viewModel.dispatch(HomeViewAction.UserSubData)
                        updateMainEvent(MainEvent.IsReq,false)
                    }
                    MainEvent.MainNodeUpdate -> {
                        viewModel.getNodes()
                        updateMainEvent(MainEvent.IsReq,false)
                    }
                    MainEvent.MainTcpPing -> {
                        viewModel.testAllTcping()
                        updateMainEvent(MainEvent.IsReqFsh,false)
                    }
                    MainEvent.UserData -> {
                        viewModel.dispatch(HomeViewAction.UserData)
                    }
                    MainEvent.MainAppUpdate -> {
                        if (viewStates.versionData?.isUpdate == 1)
                        {
                            AllenVersionChecker
                                .getInstance()
                                .downloadOnly(
                                    UIData.create().setTitle("更新提示").setContent(viewStates.versionData.appmsg).setDownloadUrl(viewModel.viewStates.versionData?.download_url)
                                )
                                .executeMission(context);
                        }

                        updateMainEvent(MainEvent.IsReqFsh)
                    }
                    MainEvent.MainGetUpdate->{
                        viewModel.dispatch(HomeViewAction.VerionUpdate)
                    }
                    else -> {

                    }
                }

//                homeViewModel.viewEvents.collect {
//                    if (it is HomeViewEvent.UserNode){
//                        homeViewModel.dispatch(HomeViewAction.UserSubData)
//                    } else if (it is HomeViewEvent.ErrorMessage) {
//
//                    }
//                }
            }
        }

    }
    //未登录才跳转到登录页面
    if (!viewModel.isLogin()) {
        NoLogin(navHostController)
    } else {



        LcePage(pageState = viewStates.pageState, onRetry = {
            viewModel.dispatch(HomeViewAction.UserSubData)
        }) {
            Column {
                AppBarDropDown(
                    "首页",
                    rightIcon = Icons.Default.Settings,
                    items=listOf("测试服务器延迟","真实延迟测试", "刷新线路", "刷新用户信息"),
                    onRightClick = {
                        navHostController.navigate(KeyNavigationRoute.SETTING.route)
                    },
                    onItemSelected = {
                        when(it){
                            0 -> {
                                updateMainEvent(MainEvent.MainTcpPing)
                            }
                            1 -> {
                                viewModel.testAllRealPing()
                            }
                            2 -> {
                                updateMainEvent(MainEvent.MainNodeUpdate)
                            }
                            3->{
                                updateMainEvent(MainEvent.Login)
                            }
                        }
                    }
                )

                SwipeRefreshContent(
                    viewModel = viewModel,
                    listData = viewStates.dataList,
                    state = viewStates.listState,
                    itemContent = {
                        item {
                            MySubInfo(navHostController,viewStates.userSubInfoData)
                        }
                    },
                    noData = {
                        updateMainEvent(MainEvent.Login)
                    },
                    content = { index,data ->
                        val ms = viewModel.getMs(data.guid)
                        Log.d("ms","index${index},ms{$ms},name{${data.nodeModel.name}}")
                        HomeCardItemContent(data.nodeModel, ms = ms, selected = viewStates.selectedIndex == index,onClick = {
                            viewModel.dispatch(HomeViewAction.UpdateSelect(selectedIndex = index))
                            viewModel.selectNode(data)
                            mainViewModel.road()
                        })
                    },
                    bottomContent = {
                        Text(
                            "版本",
                            fontSize = 14.sp,
                            color = MaterialTheme.colors.primary,
                            modifier = Modifier.padding(start = 20.dp, top = 5.dp, bottom = 5.dp)
                        )

                        SimpleCard(
                            content = {
                                Row(
                                    modifier = Modifier
                                        .padding(10.dp)
                                        .clickable {
                                            updateMainEvent(MainEvent.MainAppUpdate)
                                        },
                                    verticalAlignment = Alignment.CenterVertically
                                ){

                                    Text(text = viewStates.version)
                                }

                            }
                        )
                    }
                )


            }

        }

    }

}



@Composable
fun MySubInfo(
    navHostController:NavHostController,
    userSubInfoData: UserSubModel?
){

    if (userSubInfoData == null){
        SimpleCard(

            content = {
                Column(
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(text = "点击重新获取")
                    Spacer(modifier = Modifier.weight(1f,true))
                    Button(onClick = {
                        updateMainEvent(MainEvent.Login,false)
                    }) {
                        Text(text = "点击重新获取")
                    }
                }
            }
        )
    }
    else {
        userSubInfoData.let {
            SimpleCard(
                content = {
                    Column(
                        modifier = Modifier
                            .padding(10.dp)

                    ) {
                        if (it.paid == 1) {
                            Row(
                                modifier = Modifier.clickable {
                                    navHostController.navigate("${KeyNavigationRoute.WEBVIEW.route}?url=/order&title=我的订单")
                                },
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(text = "您还有未支付订单:立即支付", color = red)
                            }
                        }

                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {

                            Text(text = "用户名:${it.email} : ${it.plan.name}")
                            Spacer(modifier = Modifier.weight(1f,true))
                        }
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column() {
                                if(it.expired_at != null){
                                    Text(text = "${Utils.timeStamp2DateStr(it.expired_at.toLong())}过期")
                                } else {
                                    Text(text = "长期有效")
                                }

                                Spacer(modifier = Modifier.height(5.dp))
                                val ud = (it.u + it.d).toDouble()
                               // Log.e("LinearProgressIndicator","ud$ud")
                                val result = ud / it.transfer_enable.toDouble()
                                val percentage:Float = result.toFloat()
                                val formattedValue = "%.4f".format(percentage)
                                Log.e("LinearProgressIndicator","percentage${percentage}")
                                Log.e("LinearProgressIndicator","proress --- ${formattedValue.toFloat()}---u+d--${it.u + it.d}---transfer_enable--${it.transfer_enable}")
                                LinearProgressIndicator(
                                    modifier=Modifier.height(10.dp),
                                    backgroundColor = colorUnselected,
                                    color = colorSelected,
                                    progress = formattedValue.toFloat()
                                )
                            }
                            Spacer(modifier = Modifier.weight(1f,true))
                            Button(onClick = {
                                navHostController.navigate(KeyNavigationRoute.BUY.route)
                            }) {
                                Text(text = "续费")
                            }
                        }

                        Row() {
                            Text(text = "已用:${(it.u + it.d).toLong().toTrafficString()} / 总计:${it.transfer_enable.toTrafficString()}")

                        }
                    }
                }
            )
        }
    }

}

