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/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/NullDataComponentWidget.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/controller/device/device_share_list_controller.dart';
import 'package:vbvs_app/model/BleDeviceData.dart';
import 'package:vbvs_app/pages/device_bind/componnet/DeviceShareInfoWidget.dart';

class DeviceShareListPage extends StatefulWidget {
  String device = "";
  DeviceShareListPage({super.key, required this.device});

  @override
  State<DeviceShareListPage> createState() => _DeviceShareListPageState();
}

class _DeviceShareListPageState extends State<DeviceShareListPage> {
  DeviceShareListController deviceShareListController = Get.find();

  @override
  void initState() {
    deviceShareListController.model.key = null;
    deviceShareListController.shareInfoList.value = [];
    deviceShareListController.selectedShareInfo.value = [];
    deviceShareListController.getDeviceShareList(widget.device);
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, boxConstraints) => 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(
              iconTheme: IconThemeData(color: themeController.currentColor.sc3),
              backgroundColor: themeController.currentColor.sc17,
              automaticallyImplyLeading: false,
              titleSpacing: 0,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Text(
                      '已分享'.tr,
                      style: FlutterFlowTheme.of(context).bodyMedium.override(
                            fontFamily: 'Readex Pro',
                            color: themeController.currentColor.sc3,
                            letterSpacing: 0,
                            fontSize: 30.rpx,
                          ),
                    ),
                    //todo 返回刷新列表
                    Positioned(
                      left: 0,
                      child: returnIconButtom,
                    ),
                  ],
                ),
              ),
              actions: [],
              centerTitle: false,
            ),
            body: SafeArea(
              top: true,
              child: Padding(
                padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 0, 30.rpx, 0),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    SizedBox(
                      height: 40.rpx,
                    ),
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        color: themeController.currentColor.sc3,
                        borderRadius: BorderRadius.circular(20.rpx),
                      ),
                      child: Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            35.rpx, 0, 35.rpx, 0),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Padding(
                                    padding: EdgeInsetsDirectional.fromSTEB(
                                        0, 0.rpx, 0, 0),
                                    child: Container(
                                      width: 25.rpx,
                                      height: 25.rpx,
                                      // width: double.infinity,
                                      decoration: BoxDecoration(),
                                      child: SvgPicture.asset(
                                        'assets/img/icon/query.svg',
                                        fit: BoxFit.cover,
                                        color: stringToColor("#333333"), //固定
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: Container(
                                      width: 100.rpx,
                                      height: 80.rpx,
                                      decoration: BoxDecoration(
                                        color: FlutterFlowTheme.of(context)
                                            .secondaryBackground,
                                      ),
                                      child: Align(
                                        alignment: AlignmentDirectional(-1, 0),
                                        child: TextFormField(
                                          onChanged: (value) {
                                            deviceShareListController
                                                .model.key = value;
                                          },
                                          autofocus: false,
                                          obscureText: false,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            labelStyle:
                                                FlutterFlowTheme.of(context)
                                                    .labelMedium
                                                    .override(
                                                      fontFamily: 'Inter',
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0.0,
                                                    ),
                                            hintText: '输入关键字'.tr,
                                            hintStyle:
                                                FlutterFlowTheme.of(context)
                                                    .labelMedium
                                                    .override(
                                                      fontFamily: 'Inter',
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0.0,
                                                    ),
                                            enabledBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                color: Color(0x00000000),
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            focusedBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                color: Color(0x00000000),
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            errorBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                color:
                                                    FlutterFlowTheme.of(context)
                                                        .error,
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            focusedErrorBorder:
                                                OutlineInputBorder(
                                              borderSide: BorderSide(
                                                color:
                                                    FlutterFlowTheme.of(context)
                                                        .error,
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            filled: false,
                                            fillColor: themeController
                                                .currentColor.sc22,
                                          ),
                                          style: FlutterFlowTheme.of(context)
                                              .bodyMedium
                                              .override(
                                                fontFamily: 'Inter',
                                                fontSize: 26.rpx,
                                                letterSpacing: 0.0,
                                              ),
                                          cursorColor:
                                              FlutterFlowTheme.of(context)
                                                  .primaryText,
                                        ),
                                      ),
                                    ),
                                  ),
                                ].divide(SizedBox(width: 6.rpx)),
                              ),
                            ),
                            Padding(
                              padding: EdgeInsetsDirectional.fromSTEB(
                                  26.rpx, 0, 0, 0),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  SizedBox(
                                    height: 50.rpx,
                                    child: VerticalDivider(
                                      thickness: 2.rpx,
                                      color: stringToColor("#333333"), //固定
                                    ),
                                  ),
                                  ClickableContainer(
                                    onTap: () async {
                                      // ApiResponse apiResponse =
                                      //     await deviceShareListController
                                      //         .getDeviceShareList(
                                      //             key: deviceShareListController
                                      //                 .model.key);
                                      // if (apiResponse.code ==
                                      //     HttpStatusCodes.ok) {
                                      //   TopSlideNotification.show(
                                      //     context,
                                      //     text: apiResponse.msg!,
                                      //     textColor:
                                      //         themeController.currentColor.sc2,
                                      //   );
                                      //   deviceShareListController.updateAll();
                                      // } else {
                                      //   TopSlideNotification.show(
                                      //     context,
                                      //     text: apiResponse.msg!,
                                      //     textColor:
                                      //         themeController.currentColor.sc9,
                                      //   );
                                      // }
                                    },
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 10.rpx, vertical: 6.rpx),
                                    borderRadius: 12.rpx,
                                    backgroundColor: Colors.transparent,
                                    highlightColor: stringToColor("#333333")
                                        .withOpacity(0.08), // 可选点击反馈色
                                    child: Text(
                                      '搜索'.tr,
                                      style: FlutterFlowTheme.of(context)
                                          .bodyMedium
                                          .override(
                                            fontFamily: 'Inter',
                                            fontSize: 30.rpx,
                                            letterSpacing: 0.0,
                                            color:
                                                stringToColor("#333333"), //固定
                                          ),
                                    ),
                                  ),
                                ].divide(SizedBox(width: 26.rpx)),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      constraints: BoxConstraints(
                        minHeight: 100.rpx,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            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:
                                          deviceShareListController.model.all ==
                                                  0
                                              ? false
                                              : true,
                                      onChanged: (newValue) async {
                                        if (newValue == true) {
                                          // 设置为全选
                                          deviceShareListController.model.all =
                                              1;
                                          deviceShareListController
                                                  .selectedShareInfo.value =
                                              deviceShareListController
                                                  .shareInfoList
                                                  .map((e) => e['id'] as String)
                                                  .toList();
                                        } else {
                                          // 取消全选
                                          deviceShareListController.model.all =
                                              0;
                                          deviceShareListController
                                              .selectedShareInfo
                                              .clear();
                                        }

                                        deviceShareListController
                                            .selectedShareInfo
                                            .refresh();
                                        deviceShareListController.updateAll();
                                      },
                                      side: BorderSide(
                                        width: 1.5,
                                        color: FlutterFlowTheme.of(context)
                                            .secondaryText,
                                      ),
                                      activeColor: stringToColor("#16C89F"),
                                      checkColor:
                                          FlutterFlowTheme.of(context).info,
                                    ),
                                  )),
                              Text(
                                "全选".tr,
                                style: TextStyle(
                                  fontSize: AppConstants().normal_text_fontSize,
                                  color: themeController.currentColor.sc3,
                                ),
                              ),
                            ].divide(SizedBox(
                              width: 10.rpx,
                            )),
                          ),
                          ClickableContainer(
                            onTap: () async {
                              //todo 删除分享
                              // ApiResponse apiResponse =
                              //     await deviceShareListController
                              //         .deleteShareDevice();
                              // if (apiResponse.code == HttpStatusCodes.ok) {
                              //   TopSlideNotification.show(context,
                              //       text: apiResponse.msg!);
                              // } else {
                              //   TopSlideNotification.show(context,
                              //       text: apiResponse.msg!,
                              //       textColor:
                              //           themeController.currentColor.sc9);
                              // }
                            },
                            padding: EdgeInsets.symmetric(
                                horizontal: 20.rpx, vertical: 10.rpx),
                            borderRadius: 20.rpx,
                            backgroundColor: Colors.transparent,
                            highlightColor: themeController.currentColor.sc3
                                .withOpacity(0.1),
                            child: Text(
                              "删除".tr,
                              style: TextStyle(
                                fontSize: AppConstants().normal_text_fontSize,
                                color: themeController.currentColor.sc3,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: deviceShareListController
                              .shareInfoList.value.isNotEmpty
                          ? SingleChildScrollView(
                              child: Obx(() {
                                var selected = deviceShareListController
                                    .selectedShareInfo.value;
                                return Column(
                                  children: deviceShareListController
                                      .shareInfoList.value
                                      .map((item) =>
                                          DeviceShareInfoWidget(data: item))
                                      .toList()
                                      .divide(SizedBox(height: 30.rpx))
                                      .addToEnd(SizedBox(
                                        height: 30.rpx,
                                      )),
                                );
                              }),
                            )
                          : NullDataWidget(),
                    ),
                  ].divide(SizedBox(height: 30.rpx)),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

BleDeviceData parseBleData(List<int> data) {
  if (data.length < 18) {
    throw Exception('BLE广播数据长度不足18字节');
  }

  int type = data[0];
  int sn = data[1];

  // 设备唯一ID (6字节)，格式化为 MAC 地址样式
  String deviceId =
      List.generate(6, (i) => data[2 + i].toRadixString(16).padLeft(2, '0'))
          .join(":")
          .toUpperCase();

  int bre = data[8];
  int ht = data[9];
  int active = data[10];
  int flag = data[11];

  // version 是4字节 uint，大端字节序
  int version =
      (data[12] << 24) | (data[13] << 16) | (data[14] << 8) | data[15];

  // qsn 是2字节 ushort，大端字节序
  int qsn = (data[16] << 8) | data[17];

  return BleDeviceData(
    type: type,
    sn: sn,
    deviceId: deviceId,
    bre: bre,
    ht: ht,
    active: active,
    flag: flag,
    version: version,
    qsn: qsn,
  );
}
