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/ServiceConstant.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/common/util/requestWithLog.dart';
import 'package:vbvs_app/component/NullDataComponentWidget.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/device/device_share_list_controller.dart';
import 'package:vbvs_app/pages/device_bind/componnet/DeviceShareInfoWidget.dart';
import 'package:vbvs_app/pages/device_bind/componnet/bind_dialog.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.model.all = 0;
    deviceShareListController.getDeviceShareList(widget.device).then((value) {
      deviceShareListController.updateAll();
    });
    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: 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: 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: Colors.white,
                                      ),
                                      child: Align(
                                        alignment: AlignmentDirectional(-1, 0),
                                        child: TextFormField(
                                          onChanged: (value) {
                                            deviceShareListController
                                                .model.key = value;
                                          },
                                          autofocus: false,
                                          obscureText: false,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            labelStyle: TextStyle(
                                              fontFamily: 'Inter',
                                              fontSize: 26.rpx,
                                              letterSpacing: 0.0,
                                            ),
                                            hintText: '输入关键字'.tr,
                                            hintStyle: TextStyle(
                                              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:
                                                    Colors.white,
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            focusedErrorBorder:
                                                OutlineInputBorder(
                                              borderSide: BorderSide(
                                                color:
                                                    Colors.white,
                                                width: 1.rpx,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(8.rpx),
                                            ),
                                            filled: false,
                                            fillColor: themeController
                                                .currentColor.sc22,
                                          ),
                                          style: TextStyle(
                                            fontFamily: 'Inter',
                                            fontSize: 26.rpx,
                                            letterSpacing: 0.0,
                                          ),
                                          cursorColor:
                                              themeController.currentColor.sc3,
                                        ),
                                      ),
                                    ),
                                  ),
                                ].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,
                                      //   );
                                      // }
                                      deviceShareListController
                                          .getDeviceShareList(widget.device,
                                              key: deviceShareListController
                                                  .model.key);
                                    },
                                    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: TextStyle(
                                        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) {
                                          try {
                                            deviceShareListController
                                                .model.all = 1;

                                            final key =
                                                deviceShareListController
                                                    .model.accountKey;
                                            final List<String> selectedList =
                                                [];

                                            final allShareInfo =
                                                deviceShareListController
                                                    .shareInfoList;
                                            for (final sublist
                                                in allShareInfo) {
                                              if (sublist is List) {
                                                for (final item in sublist) {
                                                  if (item is Map &&
                                                      item.containsKey(key)) {
                                                    selectedList.add(item[key]);
                                                    break;
                                                  }
                                                }
                                              }
                                            }

                                            deviceShareListController
                                                .selectedShareInfo
                                                .value = selectedList;

                                            print("已全选: $selectedList");
                                          } catch (e) {
                                            print("全选失败: $e");
                                          }
                                        } else {
                                          // 取消全选
                                          deviceShareListController.model.all =
                                              0;
                                          deviceShareListController
                                              .selectedShareInfo
                                              .clear();
                                        }

                                        deviceShareListController
                                            .selectedShareInfo
                                            .refresh();
                                        deviceShareListController.updateAll();
                                      },
                                      side: BorderSide(
                                        width: 1.5,
                                        color: Colors.white,
                                      ),
                                      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 {
                              showConfirmDialog(context, Container(), "删除提示".tr,
                                  onConfirm: () async {
                                if (deviceShareListController
                                            .selectedShareInfo ==
                                        null ||
                                    deviceShareListController
                                        .selectedShareInfo.isEmpty) {
                                  TopSlideNotification.show(context,
                                      text: "删除错误提示".tr,
                                      textColor:
                                          themeController.currentColor.sc9);
                                  return;
                                }
                                String serviceAddress =
                                    ServiceConstant.service_address;
                                String serviceName =
                                    ServiceConstant.server_service;
                                String serviceApi = ServiceConstant.device_bind;
                                String queryUrl =
                                    "${serviceAddress}${serviceName}${serviceApi}";
                                final data = {
                                  "mac": widget.device,
                                  "uid": deviceShareListController
                                      .selectedShareInfo.value
                                      .join(','),
                                };
                                await requestWithLog(
                                  logTitle: "删除分享设备",
                                  method: MyHttpMethod.delete,
                                  queryUrl: queryUrl,
                                  data: data,
                                  onSuccess: (res) {
                                    TopSlideNotification.show(context,
                                        text: res.msg!);
                                    deviceShareListController.model.all = 0;
                                    deviceShareListController
                                        .selectedShareInfo.value = [];
                                    deviceShareListController
                                        .getDeviceShareList(widget.device);
                                    deviceShareListController.updateAll();
                                  },
                                  onFailure: (res) {
                                    TopSlideNotification.show(context,
                                        text: res.msg!,
                                        textColor:
                                            themeController.currentColor.sc9);
                                    deviceShareListController.updateAll();
                                  },
                                );
                              }, onCancel: () {});
                            },
                            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,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Obx(() {
                      final list =
                          deviceShareListController.shareInfoList.value;
                      final selected =
                          deviceShareListController.selectedShareInfo.value;

                      return Expanded(
                        child: list.isNotEmpty
                            ? SingleChildScrollView(
                                child: Column(
                                  children: list
                                      .map((item) =>
                                          DeviceShareInfoWidget(data: item))
                                      .toList()
                                      .divide(SizedBox(height: 30.rpx))
                                      .addToEnd(SizedBox(height: 30.rpx)),
                                ),
                              )
                            : NullDataWidget(),
                      );
                    })
                  ].divide(SizedBox(height: 30.rpx)),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
