import 'dart:async';

import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';


class HomeDeviceType extends StatefulWidget {
  HomeDeviceType({super.key});
  @override
  State<HomeDeviceType> createState() => _HomeDeviceTypeState();
}

class _HomeDeviceTypeState extends State<HomeDeviceType> {
  bool isExec = false;

  @override
  Widget build(BuildContext context) {
    // if (isExec == false) {
    //   Timer(const Duration(milliseconds: 10), () {
    //     controller.getDeviceType();
    //   });
    //   isExec = true;
    // }
    return LayoutBuilder(
      builder: (context, boxConstraints) => 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,
                automaticallyImplyLeading: false,
                iconTheme: const IconThemeData(color: Colors.white),
                titleSpacing: 0,
                // leading: returnIconButtom,
                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: returnIconButtom,
                      ),
                    ],
                  ),
                ),

                centerTitle: false,
              ),
              body: SafeArea(
                top: true,
                child: Container(
                  width: MediaQuery.sizeOf(context).width,
                  height: MediaQuery.sizeOf(context).height * 1.123,
                  // decoration: const BoxDecoration(
                  //   image: DecorationImage(
                  //     image: AssetImage("assets/images/new_background.png"),
                  //     fit: BoxFit.cover,
                  //   ),
                  // ),
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsetsDirectional.fromSTEB(
                              48.rpx, 24.rpx, 0, 0),
                          child: Text(
                            '选择类型',
                            style: TextStyle(
                              fontFamily: 'Readex Pro',
                              color: Colors.white,
                              fontSize: 30.rpx,
                              letterSpacing: 0,
                            ),
                          ),
                        ),
                        _buildControlCard(context),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          )),
    );
  }
}

Widget _buildControlCard(BuildContext context) {
  final List<Map<String, dynamic>> deviceTypeList = [
    {
      "id": 1,
      "name": "智能床垫",
      "desc": "SWES01 MHT01 SWES01 MHT01 SWES01 MHT01 ",
      "img": "assets/images/device_bed.png",
      "page": 1,
    },
    {
      "id": 2,
      "name": "智能电动床",
      "desc": "M300",
      "img": "assets/images/electric_bed.png",
      "page": 2,
    },
  ];

  return SizedBox(
      // height: 221.rpx,
      child: Padding(
          padding: EdgeInsets.only(left: 30.rpx, right: 30.rpx, top: 7.rpx),
          child: Column(
            children: List.generate(
              deviceTypeList.length,
              (index) => _buildDeviceItem(context, deviceTypeList[index]),
            ),
          )));
}

Widget _buildDeviceItem(BuildContext context, Map<String, dynamic> dtype) {
  return Padding(
    padding: EdgeInsetsDirectional.fromSTEB(0, 25.rpx, 0, 0),
    child: InkWell(
      onTap: () {
        // Get.offAndToNamed("/bindDevice", arguments: dtype["id"]);
      },
      child: Container(
        height: 221.rpx,
        decoration: BoxDecoration(
          // color: FlutterFlowTheme.of(context).secondaryBackground,
          borderRadius: BorderRadius.circular(6),
        ),
        constraints: BoxConstraints(minHeight: 221.rpx),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsetsDirectional.only(start: 59.rpx),
              child: Container(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(6.rpx),
                  child: Image.asset(
                    dtype["img"],
                    width: 180.rpx,
                    height: 109.rpx,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.fromLTRB(0, 59.rpx, 0, 0),
                    child: Text(
                      dtype["name"],
                      style: TextStyle(
                        fontFamily: 'Readex Pro',
                        fontSize: 30.rpx,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  SizedBox(height: 35.rpx),
                  Expanded(
                      child: Padding(
                    padding: EdgeInsets.only(left: 80.rpx, right: 80.rpx),
                    child: SizedBox(
                      height: 40.rpx, // 固定高度（两行高度 + 行间距）
                      child: LayoutBuilder(
                        builder: (context, constraints) {
                          final items = (dtype["desc"] as String)
                              .split(RegExp(r'\s+'))
                              .where((e) => e.trim().isNotEmpty)
                              .toList();
                          final limitedItems = items.take(6).toList();

                          final isSingleLine = limitedItems.length <= 3;

                          return Align(
                            alignment: isSingleLine
                                ? Alignment.topCenter
                                : Alignment.topLeft,
                            child: Wrap(
                              spacing: 20.rpx,
                              runSpacing: 10.rpx,
                              alignment: isSingleLine
                                  ? WrapAlignment.center
                                  : WrapAlignment.start,
                              children: limitedItems.map((item) {
                                return Container(
                                  width: 75.rpx,
                                  // height: 40.rpx,
                                  alignment: Alignment.center,
                                  child: Text(
                                    item,
                                    style: TextStyle(
                                      fontSize: 20.rpx,
                                      color: const Color(0xFF9AA0B3),
                                      height: 1,
                                    ),
                                    // overflow: TextOverflow.ellipsis,
                                    maxLines: 1,
                                  ),
                                );
                              }).toList(),
                            ),
                          );
                        },
                      ),
                    ),
                  ))
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  );
}
