import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:naiyouwl/app/component/sys_app_bar.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_manager/window_manager.dart';
import '../../../component/connection_status.dart';
import '../../../component/connection_widget.dart';

import '../../../global_controller/GlobalController.dart';
import '../../../service/clash_service.dart';
import '../controllers/home_controller.dart';


class HomeView extends GetView<HomeController> {

  const HomeView({Key? key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/main/main.png"),
          fit: BoxFit.fill,
        ),
      ),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: SysAppBar(title: Text("首页"),actions: [
            Row(
              children: [
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: () {
                    controller.fetchNode();
                  },
                ),
                const Text('刷新节点'), // 这里是您的标题
              ],
            ),
          ],),

          body: Obx(() {
            if(controller.errorMsg.isNotEmpty){
              WidgetsBinding.instance.addPostFrameCallback((_) {
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(controller.errorMsg.value))
                );
              });
            }
            return controller.isLoading.value ? const Center(child: CircularProgressIndicator()) : Column(
              children: [
                // 错误消息展示


                UserStatusWidget(isActive: controller.GetEnable(),isLoading: controller.isLoading.value,username:controller.GetUserName(),expiryDate: controller.GetExpiredAt(),userTraffic:controller.GetTraffic(),onRefresh: () async {
                  // 这里插入刷新操作代码
                  //await Future.delayed(Duration(seconds: 2));
                  if(controller.isLoading.value != true){
                    controller.fetchUserinfo();
                  }
                },),
                Padding(
                    padding: const EdgeInsets.fromLTRB(20, 20, 0, 0),
                    child: Row(
                      children: controller.imageMap.entries.expand((entry) {
                        return [
                          GestureDetector(
                            onTap: () => controller.onImageTap(entry.key),
                            child: Image(
                              image: AssetImage(entry.value),
                              width: 60,
                              height: 60,
                            ),
                          ),
                          //Spacer(), // 平均分配间隔
                          const SizedBox(width: 30),
                        ];
                      }).toList()
                        ..removeLast(), // 删除最后一个Spacer
                    )

                ),
                const SizedBox(height: 35,),
                const Padding(
                  padding: EdgeInsets.fromLTRB(30, 0, 30, 0),
                  child: Row(
                    children: [

                      Text("http://127.0.0.1:5336"),
                      Spacer(),
                      Text("socks://127.0.0.1:5337"),
                    ],
                  ),
                ),
                ConnectionWidget(
                  status: ConnectionStatus.disconnected, onStatusChange: (con) {

                },),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: SizedBox(
                    width: 200,
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                           controller.RouteNode();
                      },
                      style: ElevatedButton.styleFrom(
                        primary: Colors.white, // 设置背景颜色为白色
                        onPrimary: Colors.black, // 设置文字颜色为黑色，确保在白色背景上可见
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20), // 设置圆角
                        ),
                      ),
                      child: Text(controller.GetNode()),
                    ),
                  ),
                ),

              ],
            );
          })
      ),
    );
  }
}

class UserStatusWidget extends StatefulWidget {

  final Future<void> Function() onRefresh; // 新增的回调
  final bool isActive;
  final bool isLoading; // 新增的变量
  final String username;
  final String userTraffic;
  final String expiryDate;
  const UserStatusWidget({Key? key, required this.isActive, required this.isLoading,required this.username, required this.userTraffic, required this.expiryDate, required this.onRefresh}) : super(key: key);

  @override
  _UserStatusWidgetState createState() => _UserStatusWidgetState();
}

class _UserStatusWidgetState extends State<UserStatusWidget> {
  @override
  Widget build(BuildContext context) {
    String imagePath = widget.isActive
        ? "assets/images/main/userstatus.png"
        : "assets/images/main/userstatusoff.png";

    return Align(
      alignment: Alignment.topCenter,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(10.0, 0, 10.0, 10.0),
        child:
        Row(
          children: [
            const SizedBox(
              width: 80,
              height: 20,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start, // 这将使子组件从左边开始对齐
              children: [

                Row(
                  children: [
                    Text(widget.username),
                    const SizedBox(width: 10,),
                    Image(
                      image: AssetImage(imagePath),
                      width: 80,
                      height: 30,
                    ),
                    const SizedBox(width: 10,),
                    IconButton(
                      icon: widget.isLoading ? const CircularProgressIndicator() : Image.asset("assets/images/main/refresh.png"),
                      onPressed: () {
                        // 刷新操作
                        if(!widget.isLoading){
                          widget.onRefresh();
                        }
                      },
                    )
                  ],
                ),
                 Text(
                  widget.expiryDate,
                  style: const TextStyle(
                    fontSize: 8.0, // 设置字体大小为20像素
                  ),
                ),
                Text(
                  widget.userTraffic,
                  style: const TextStyle(
                    fontSize: 8.0, // 设置字体大小为20像素
                  ),
                )
              ],
            ),
          ],
        ),
        // const SizedBox(height: 10,),  // 可调整间隔
      ),
    );
  }
}



