import 'package:EasyDartModule/EasyDartModule.dart' as edm;
import 'package:easydevice/easydevice.dart';
import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/device/blueteeth_bind_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/model/BleDeviceData.dart';
import 'package:vbvs_app/model/api_response.dart';
import 'package:vbvs_app/pages/device_bind/blueteeth_device_page.dart';
import 'package:vbvs_app/pages/device_bind/componnet/bind_dialog.dart';

class SingleBlueteethDeviceCompoentWidget extends StatefulWidget {
  final bleDevice;

  const SingleBlueteethDeviceCompoentWidget({
    super.key,
    required this.bleDevice,
  });

  @override
  State<SingleBlueteethDeviceCompoentWidget> createState() =>
      _SingleBlueteethDeviceCompoentWidgetState();
}

class _SingleBlueteethDeviceCompoentWidgetState
    extends State<SingleBlueteethDeviceCompoentWidget> {
  ThemeController themeController = Get.find();
  BlueteethBindController blueteethBindController = Get.find();
  @override
  Widget build(BuildContext context) {
    List<int> rawData =
        widget.bleDevice.advertisementData.manufacturerData[0xFFED]!;
    BleDeviceData deviceData = parseBleData(rawData);
    deviceData.name = widget.bleDevice.advertisementData.advName;
    deviceData.rssi = widget.bleDevice.rssi;
    deviceData.mac = deviceData.deviceId.replaceAll(':', '');
    BleDeviceData device = deviceData;
    blueteethBindController.currentDeviceMac = device.mac;
    device = blueteethBindController.model.betDevicelist!.firstWhere(
      (d) => d.mac == device.mac,
      orElse: () => device,
    );

    return ClickableContainer(
      backgroundColor: themeController.currentColor.sc5,
      highlightColor: themeController.currentColor.sc21,
      borderRadius: 20.rpx,
      padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 36.rpx, 0, 52.rpx),
      onTap: () async {
        try {
          if (device.bind == true) {
            showHaveBindDialog(context);
            // showBindDoubleDialog(context, []);
          } else {
            showConfirmDialog(
              context,
              Container(),
              '蓝牙绑定.确定绑定提示'.tr,
              onConfirm: () async {
                ApiResponse response =
                    await blueteethBindController.bindDeviceAndMAC(device);
                TopSlideNotification.show(context, text: response.msg!);
                if (response.code == HttpStatusCodes.ok) {
                  showLoadingDialog(context); // 显示 loading
                  THapp bledevice = THapp(device: widget.bleDevice.device);
                  await bledevice.device.connect();
                  var res2 = bledevice.isConnected;
                  if (res2) {
                    Navigator.pop(context);
                    TopSlideNotification.show(
                      context,
                      text: "蓝牙绑定.连接成功".tr,
                      textColor: themeController.currentColor.sc2,
                    );
                    blueteethBindController.currentDevice = bledevice;
                    // Get.toNamed("/wifiPage", arguments: {bledevice});
                    Get.toNamed("/wifiPage");
                  } else {
                    Navigator.pop(context);
                    TopSlideNotification.show(
                      context,
                      text: "蓝牙绑定.连接失败".tr,
                      textColor: themeController.currentColor.sc9,
                    );
                  }
                } else {
                  TopSlideNotification.show(
                    context,
                    text: response.msg ?? "蓝牙绑定.连接异常".tr,
                    textColor: themeController.currentColor.sc9,
                  );
                }
              },
              onCancel: () {
                print('用户点击了取消');
                // 执行取消后的处理逻辑
              },
            );
        
          }
        } catch (e) {
          Navigator.pop(context);
          TopSlideNotification.show(
            context,
            text: "蓝牙绑定.连接异常".tr,
            textColor: themeController.currentColor.sc9,
          );
          edm.EasyDartModule.logger.info("蓝牙绑定.连接异常: $e");
          DailyLogUtils.writeLog("蓝牙绑定.连接异常: $e");
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: [
          Text(
            device.name ?? '蓝牙绑定.默认设备名称'.tr,
            style: FlutterFlowTheme.of(context).bodyMedium.override(
                  fontFamily: 'Inter',
                  color: const Color(0xFFF6FAFD),
                  fontSize: 30.rpx,
                  letterSpacing: 0.0,
                ),
          ),
          Row(
            children: [
              Text(
                "蓝牙绑定.信号强度".tr + '：${device.rssi ?? '-'}dBm',
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: 'Inter',
                      color: const Color(0xFFEBF2F8),
                      fontSize: 26.rpx,
                      letterSpacing: 0.0,
                    ),
              ),
              SizedBox(width: 40.rpx),
              Text(
                "蓝牙绑定.SN".tr + '：${device.sn ?? '-'}',
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: 'Inter',
                      color: const Color(0xFFF5F9FD),
                      fontSize: 26.rpx,
                      letterSpacing: 0.0,
                    ),
              ),
            ],
          ),
          Text(
            "蓝牙绑定.蓝牙地址".tr + '：${device.deviceId ?? '-'}',
            style: FlutterFlowTheme.of(context).bodyMedium.override(
                  fontFamily: 'Inter',
                  color: const Color(0xFFF6FAFD),
                  fontSize: 26.rpx,
                  letterSpacing: 0.0,
                ),
          ),
          Text(
            "蓝牙绑定.mac".tr + '：${device.mac ?? '-'}',
            style: FlutterFlowTheme.of(context).bodyMedium.override(
                  fontFamily: 'Inter',
                  color: const Color(0xFFF6FAFD),
                  fontSize: 26.rpx,
                  letterSpacing: 0.0,
                ),
          ),
          Row(
            children: [
              Text(
                "蓝牙绑定.网络".tr +
                    '：${device.isOnline == true ? '蓝牙绑定.在线'.tr : '蓝牙绑定.离线'.tr}',
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: 'Inter',
                      color: const Color(0xFFEBF2F8),
                      fontSize: 26.rpx,
                      letterSpacing: 0.0,
                    ),
              ),
              SizedBox(width: 145.rpx),
              Row(
                children: [
                  Text(
                    "蓝牙绑定.传感器".tr + "：",
                    style: FlutterFlowTheme.of(context).bodyMedium.override(
                          fontFamily: 'Inter',
                          color: const Color(0xFFEBF2F8),
                          fontSize: 26.rpx,
                          letterSpacing: 0.0,
                        ),
                  ),
                  Text(
                    device.bind == false ? '蓝牙绑定.可绑定'.tr : '蓝牙绑定.已被绑定'.tr,
                    style: FlutterFlowTheme.of(context).bodyMedium.override(
                          fontFamily: 'Inter',
                          color: device.bind == false
                              ? const Color(0xFF1AD2B5)
                              : themeController.currentColor.sc9,
                          fontSize: 26.rpx,
                          letterSpacing: 0.0,
                        ),
                  ),
                ],
              ),
            ],
          ),
          Text(
            "版本".tr + '${device.version ?? '-'}',
            style: FlutterFlowTheme.of(context).bodyMedium.override(
                  fontFamily: 'Inter',
                  color: const Color(0xFFF6FAFD),
                  fontSize: 26.rpx,
                  letterSpacing: 0.0,
                ),
          ),
        ].divide(SizedBox(height: 37.rpx)),
      ),
    );
  }
}
