import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/tool/CustomCard.dart';
import 'package:vbvs_app/component/tool/FrostedDialog.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/device/blueteeth_bind_controller.dart';
import 'package:vbvs_app/controller/device/device_type_controller.dart';
import 'package:vbvs_app/controller/main_bottom/global_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';

class DeviceTypePage extends StatefulWidget {
  int type = 0; //0绑定设备 1.查询我的设备
  DeviceTypePage({super.key, this.type = 0});

  @override
  State<DeviceTypePage> createState() => _EPageState();
}

class _EPageState extends State<DeviceTypePage> {
  GlobalController globalController = Get.find();
  UserInfoController userInfoController = Get.find();
  BlueteethBindController blueteethBindController = Get.find();
  ThemeController themeController = Get.find();
  DeviceTypeController deviceTypeController = Get.find();

  @override
  void initState() {
    super.initState();
    deviceTypeController.getDeviceType().then((response) {
      if (response.code != HttpStatusCodes.ok) {
        // 延迟到 widget 构建后再执行 show
        TopSlideNotification.show(
          context, // 用当前页面 context 替代 Get.context!
          text: response.msg ?? "服务器.失败".tr,
          textColor: themeController.currentColor.sc9,
        );
      }
    });
    // 延迟到 build 完成后执行弹窗逻辑
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (blueteethBindController.model.read == 1 && widget.type == 0) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return FrostedDialog(
                child: Padding(
              padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 0, 30.rpx, 0),
              child: Container(
                width: double.infinity,
                constraints: BoxConstraints(
                  maxHeight: MediaQuery.sizeOf(context).height * 0.656,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Expanded(
                      child: Container(
                        width: double.infinity,
                        child: SingleChildScrollView(
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Padding(
                                padding: EdgeInsetsDirectional.fromSTEB(
                                    0, 26.rpx, 0, 0),
                                child: Container(
                                  width: MediaQuery.sizeOf(context).width,
                                  decoration: BoxDecoration(
                                    color: Color(0xFFFBF5D5),
                                    borderRadius: BorderRadius.circular(
                                        AppConstants()
                                            .normal_container_radius), // 圆角半径
                                  ),
                                  child: Padding(
                                    padding: EdgeInsetsDirectional.fromSTEB(
                                        25.rpx, 25.rpx, 25.rpx, 25.rpx),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.max,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Padding(
                                          padding:
                                              EdgeInsetsDirectional.fromSTEB(
                                                  0, 8.rpx, 0, 0),
                                          child: Container(
                                            width: 25.rpx,
                                            height: 25.rpx,
                                            // width: double.infinity,
                                            decoration: BoxDecoration(),
                                            child: SvgPicture.asset(
                                              'assets/img/icon/sound.svg',
                                              fit: BoxFit.fill,
                                              color: stringToColor("#ff9f66"),
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          child: Column(
                                            mainAxisSize: MainAxisSize.max,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                '绑定引导.说明标题'.tr,
                                                style: TextStyle(
                                                  fontFamily: 'Inter',
                                                  fontSize: AppConstants()
                                                      .normal_text_fontSize,
                                                  letterSpacing: 0.0,
                                                  fontWeight: FontWeight.w500,
                                                  color:
                                                      stringToColor("#916d46"),
                                                ),
                                              ),
                                              Text(
                                                '绑定引导.说明正文'.tr,
                                                style: TextStyle(
                                                  fontFamily: 'Inter',
                                                  fontSize: AppConstants()
                                                      .normal_text_fontSize,
                                                  letterSpacing: 0.0,
                                                  color:
                                                      stringToColor("#916d46"),
                                                ),
                                              ),
                                            ].divide(SizedBox(
                                                height: AppConstants()
                                                    .text_padding_up_dowm_p)),
                                          ),
                                        ),
                                      ].divide(SizedBox(width: 20.rpx)),
                                    ),
                                  ),
                                ),
                              ),
                              Container(
                                width: double.infinity,
                                height:
                                    (MediaQuery.sizeOf(context).width) * 0.13,
                                constraints: BoxConstraints(
                                  minHeight: 200.rpx,
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(20.rpx),
                                  // child: Image.network(
                                  //   'https://picsum.photos/seed/861/600',
                                  //   fit: BoxFit.cover,
                                  // ),
                                  child: Image.asset(
                                    "assets/img/help_op.png",
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ].divide(SizedBox(height: 25.rpx)),
                          ),
                        ),
                      ),
                    ),
                    Flexible(
                      child: Padding(
                        padding:
                            EdgeInsetsDirectional.fromSTEB(0, 210.rpx, 0, 0),
                        child: Container(
                          width: double.infinity,
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Container(
                                width: double.infinity,
                                child: Row(
                                  mainAxisSize: MainAxisSize.max,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Theme(
                                        data: ThemeData(
                                          checkboxTheme: CheckboxThemeData(
                                            visualDensity:
                                                VisualDensity.compact,
                                            materialTapTargetSize:
                                                MaterialTapTargetSize
                                                    .shrinkWrap,
                                            shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(64),
                                            ),
                                          ),
                                          unselectedWidgetColor:
                                              Color(0xFFD3D3D3),
                                        ),
                                        child: Obx(
                                          () => Checkbox(
                                            value: blueteethBindController
                                                        .model.read ==
                                                    1
                                                ? false
                                                : true,
                                            onChanged: (newValue) async {
                                              blueteethBindController
                                                      .model.read =
                                                  newValue == true ? 0 : 1;
                                              blueteethBindController
                                                  .updateAll();
                                              // 获取设备信息,需要用户点击确认隐私协议与用户协议选择框时才能获取
                                              // if (newValue == true) {
                                              //   Deviceconfig
                                              //       .initPlatformState();
                                              // }
                                            },
                                            side: BorderSide(
                                              width: 1.5,
                                              color:
                                                  Colors.white,
                                            ),
                                            activeColor:
                                                stringToColor("#16C89F"),
                                            // checkColor:
                                            //     FlutterFlowTheme.of(context)
                                            //         .info,
                                          ),
                                        )),
                                    Text(
                                      '绑定引导.不再提示'.tr,
                                      style: TextStyle(
                                        fontFamily: 'Inter',
                                        fontSize: 26.rpx,
                                        letterSpacing: 0.0,
                                        color: themeController.currentColor.sc3,
                                      ),
                                    ),
                                  ].divide(SizedBox(width: 22.rpx)),
                                ),
                              ),
                              CustomCard(
                                borderRadius: 50.rpx,
                                onTap: () async {
                                  await Future.delayed(
                                      Duration(milliseconds: 500));
                                  Get.back(); // 关闭当前弹窗或页面
                                },
                                colors: [
                                  themeController.currentColor.sc1,
                                  themeController.currentColor.sc2,
                                ], // 单色背景也用渐变写法

                                child: Container(
                                  width:
                                      MediaQuery.sizeOf(context).width * 0.66,
                                  height:
                                      MediaQuery.sizeOf(context).height * 0.055,
                                  constraints: BoxConstraints(
                                    minWidth: 500.rpx,
                                    minHeight: 90.rpx,
                                  ),
                                  alignment: Alignment.center, // 居中对齐
                                  child: Text(
                                    '确认'.tr,
                                    style: TextStyle(
                                      fontFamily: 'Inter',
                                      fontSize: 26.rpx,
                                      letterSpacing: 0.0,
                                    ),
                                  ),
                                ),
                              )
                            ].divide(SizedBox(height: 42.rpx)),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ));
          },
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    int read = blueteethBindController.model.read!;
    if (blueteethBindController.model.read == 1) {
      //需要弹窗显示教程
    }
    return LayoutBuilder(
      builder: (context, bodySize) => GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/img/bgNoImg.png'), // 本地图片
              fit: BoxFit.fill, // 填满整个 Container
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent, // 加上这一行
            appBar: AppBar(
              backgroundColor: themeController.currentColor.sc17,
              // backgroundColor: Colors.transparent,
              automaticallyImplyLeading: false,
              iconTheme: IconThemeData(color: themeController.currentColor.sc3),
              titleSpacing: 0,
              // leading: returnIconButtom,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    /// 居中标题
                    Text(
                      '设备列表'.tr,
                      style: TextStyle(
                        fontFamily: 'Readex Pro',
                        color: themeController.currentColor.sc3,
                        letterSpacing: 0,
                        fontSize: 30.rpx,
                      ),
                    ),

                    /// 左边返回按钮
                    Positioned(
                      left: 0,
                      child: returnIconButtom,
                    ),
                  ],
                ),
              ),

              actions: [],
              centerTitle: false,
            ),

            body: SafeArea(
              top: true,
              child: Padding(
                padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 0, 30.rpx, 0),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      // 使用 Obx 来监听 deviceTypeList 的变化
                      Obx(() {
                        return Column(
                          children: [
                            SizedBox(height: 26.rpx), // 开始的间隔
                            ...deviceTypeController.deviceTypeList.value
                                .map((device) {
                              return Padding(
                                padding: EdgeInsets.only(
                                    bottom: 26.rpx), // 添加每个设备之间的间隔
                                child: _buildDeviceCard(
                                  context,
                                  title: device['name'], // 这里假设 device 是一个 Map
                                  imageUrl: device['image'],
                                  type: device['type'],
                                ),
                              );
                            }).toList(),
                            SizedBox(height: 26.rpx), // 结束的间隔
                          ],
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDeviceCard(BuildContext context,
      {required String title, required String imageUrl, required double type}) {
    return CustomCard(
      borderRadius: 20.rpx, // 圆角大小
      onTap: () {
        if (type != null) {
          if (type == 1) {
            Get.toNamed("/blueteethDevice");
          }
          if (type == 2) {
            TopSlideNotification.show(
              context,
              text: "待开发.提示".tr,
              textColor: themeController.currentColor.sc2,
            );
          }
        }
      },
      colors: [themeController.currentColor.sc17], // 背景色
      child: Container(
        width: double.infinity,
        height: MediaQuery.sizeOf(context).height * 0.135,
        constraints: BoxConstraints(
          minHeight: 220.rpx,
        ),
        padding: EdgeInsetsDirectional.fromSTEB(77.rpx, 0, 21.rpx, 0),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  fontFamily: 'Inter',
                  color: themeController.currentColor.sc3,
                  fontSize: 30.rpx,
                  letterSpacing: 0.0,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            ClipRRect(
              borderRadius: BorderRadius.circular(8.rpx),
              // child: Image.asset(
              //   imageUrl,
              //   width: 212.rpx,
              //   height: 168.rpx,
              // ),
              child: Image.network(
                imageUrl,
                // fit: BoxFit.cover,
                width: 212.rpx,
                height: 168.rpx,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
