import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:vbvs_app/common/color/ServiceConstant.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/tool/CustomCard.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/mh_controller/device_list_controller.dart';
import 'package:vbvs_app/pages/mh_page/test/WebviewTestModel.dart';

class RoomPickerPage extends StatefulWidget {
  final Map data;
  RoomPickerPage({Key? key, required this.data});
  @override
  _RoomPickerPageState createState() => _RoomPickerPageState();
}

class _RoomPickerPageState extends State<RoomPickerPage> {
  late Map<String, dynamic> editedData;
  RxList rooms = [].obs;
  DeviceListController deviceListController = Get.find();
  @override
  void initState() {
    super.initState();
    editedData = Map.from(widget.data); // 创建副本
    getRoomList();
  }

  getRoomList() async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.room_list;
    String queryUrl = "$serviceAddress$serviceName$serviceApi";
    requestWithLog(
      logTitle: '查询房间列表',
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        rooms.assignAll(res.data);
        setState(() => selectedIndex = 0);
      },
    );
  }

  int selectedIndex = 1;
  BoxConstraints? bodysize;
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, cc) {
      bodysize = cc;
      return GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/new_background.png'), // 本地图片
                  fit: BoxFit.fill, // 填满整个 Container
                ),
              ),
              child: Scaffold(
                backgroundColor: Colors.transparent, // 深蓝背景
                appBar: AppBar(
                  backgroundColor: Colors.transparent,
                  iconTheme: const IconThemeData(color: Colors.white),
                  automaticallyImplyLeading: false,
                  titleSpacing: 0,
                  title: SizedBox(
                    width: double.infinity,
                    height: 180.rpx,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 中间居中的标题
                        Text(
                          '房间选择',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 30.rpx,
                          ),
                        ),
                        // 左侧图标
                        Positioned(
                          left: 0.rpx,
                          child: returnIconButtomNew,
                        ),
                      ],
                    ),
                  ),
                  centerTitle: false,
                ),
                body: SafeArea(
                  child: Column(
                    children: [
                      const Spacer(),
                      // 滚轮选择器
                      SizedBox(
                        height: 360.rpx,
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            // 滚轮列表
                            Obx(
                              () => ListWheelScrollView.useDelegate(
                                itemExtent: 120.rpx,
                                perspective: 0.003,
                                physics: const FixedExtentScrollPhysics(),
                                onSelectedItemChanged: (index) {
                                  setState(() => selectedIndex = index);
                                },
                                childDelegate: ListWheelChildBuilderDelegate(
                                  builder: (context, index) {
                                    if (index >= rooms.length) return null;
                                    final isSelected = index == selectedIndex;
                                    return Center(
                                      child: Text(
                                        rooms[index]['name'],
                                        style: TextStyle(
                                          fontSize:
                                              isSelected ? 36.rpx : 30.rpx,
                                          color: isSelected
                                              ? Colors.white
                                              : const Color(0xFF929699),
                                        ),
                                      ),
                                    );
                                  },
                                  childCount: rooms.length,
                                ),
                              ),
                            ),

                            // 上边线
                            Positioned(
                              top: 120.rpx,
                              left: 60.rpx,
                              right: 60.rpx,
                              child: Container(
                                height: 1,
                                color: const Color(0xFF929699),
                              ),
                            ),

                            // 下边线
                            Positioned(
                              top: 240.rpx,
                              left: 60.rpx,
                              right: 60.rpx,
                              child: Container(
                                height: 1,
                                color: const Color(0xFF929699),
                              ),
                            ),
                          ],
                        ),
                      ),
                      const Spacer(),
                      // 完成按钮
                      Padding(
                        padding: EdgeInsets.only(
                          left: 30.rpx,
                          right: 30.rpx,
                          bottom: 83.rpx,
                        ),
                        child: SizedBox(
                            width: double.infinity,
                            height: 50,
                            child: CustomCard(
                              borderRadius: 16.rpx,
                              gradientDirection: GradientDirection.vertical,
                              onTap: () async {
                                // Get.toNamed("/applyRepairPage");
                                try {
                                  String serviceAddress =
                                      ServiceConstant.service_address;
                                  String serviceName =
                                      ServiceConstant.server_service;
                                  String serviceApi =
                                      ServiceConstant.device_show;
                                  String queryUrl =
                                      "$serviceAddress$serviceName$serviceApi";
                                  await requestWithLog(
                                    logTitle: "更新设备信息",
                                    method: MyHttpMethod.put,
                                    queryUrl: queryUrl,
                                    data: {
                                      "id": editedData["_id"],
                                      "roomId": rooms[selectedIndex]['_id'],
                                    },
                                    onSuccess: (res) {
                                  
                                      TopSlideNotification.show(context,
                                          text: "更新成功".tr,
                                          textColor: Color(0XFF00C1AA));
                                      deviceListController.getDeviceList();
                                      try {
                                        WebviewTestController
                                            webviewTestController = Get.find();
                                        webviewTestController.web.jsbridge?.dart
                                            .alterDevice();
                                      } catch (e) {
                                        ef.log("[h5]通知列表更新错误：$e");
                                      }
                                  Get.back(result:editedData);
                                    },
                                    onFailure: (res) {
                                      TopSlideNotification.show(context,
                                          text: "更新失败".tr,
                                          textColor: Color(0xFFFF7159));
                                    },
                                  );
                                } catch (e) {
                                  print(e);
                                }
                              },
                              colors: const [
                                Color(0xFFFCFCFC),
                                Color(0xFFF8FAF9),
                                Color(0XFFECF6F3),
                                Color(0XFFD9F0E9),
                                Color(0xFFCEECE3)
                              ],
                              child: Container(
                                width: double.infinity,
                                height: 90.rpx,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                child: Text("完成".tr,
                                    style: TextStyle(
                                      color: const Color(0xFF003058),
                                      fontSize: 30.rpx,
                                    )),
                              ),
                            )),
                      ),
                    ],
                  ),
                ),
              )));
    });
  }
}
