import 'dart:async';
import 'dart:math';
import 'dart:typed_data';

import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/tool/CustomCard.dart';
import 'package:vbvs_app/controller/mh_controller/bedController.dart';
import 'package:vbvs_app/controller/mh_controller/sleeping_habit_controller.dart';
import 'package:vbvs_app/pages/common/selectDialog.dart';

class RxhxMht extends StatefulWidget {
  const RxhxMht({super.key});

  @override
  State<RxhxMht> createState() => _RxhxMhtState();
}

class _RxhxMhtState extends State<RxhxMht> {
  get controller => Get.find<SleepingHabitController>();
  get bedController => Get.find<BedController>();
  List location = ["床垫全局", "床垫左侧", "床垫右侧"];

  @override
  void initState() {
    super.initState();
    Timer(Duration.zero, () {
      resetRxhx();
      currentTimeSend();
    });
  }

  resetRxhx() {
    controller.model.rxhxIsStart = false;
    controller.model.rxhxWakeTime = [7, 0];
    controller.model.rxhxIsAnMo = true;
    controller.model.rxhxWeeks = [0, 0, 0, 0, 0, 0, 0];
    controller.model.rxhxLocation = 0;
    controller.updateAll();
  }

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

  alarmChange() async {
    // List<int> arr = [0x30, 0x01];
    // arr.add(controller.model.rxhxIsStart ? 0x01 : 0x00);
    // arr.add(int.parse("${controller.model.rxhxWakeTime[0]}", radix: 16));
    // arr.add(int.parse("${controller.model.rxhxWakeTime[1]}", radix: 16));
    // arr.add(0);
    // int value = int.parse("${controller.model.rxhxWeeks[0]}") * 2 +
    //     int.parse("${controller.model.rxhxWeeks[1]}") * 4 +
    //     int.parse("${controller.model.rxhxWeeks[2]}") * 8 +
    //     int.parse("${controller.model.rxhxWeeks[3]}") * 16 +
    //     int.parse("${controller.model.rxhxWeeks[4]}") * 32 +
    //     int.parse("${controller.model.rxhxWeeks[5]}") * 64 +
    //     int.parse("${controller.model.rxhxWeeks[6]}") * 128;
    // arr.add(value);
    // arr.add(value > 1 ? 1 : 0);
    // arr.add((controller.model.rxhxIsAnMo ? 1 : 0) +
    //     int.parse("${controller.model.rxhxLocation * 16}"));
    // var sendArr = getCode(arr);
    // List receive = [];
    // Function fun = (d) {
    //   receive.add(d);
    // };
    // bedController.deviceProp?.receiveLogArr.add(fun);
    // for (var i = 0; i < 3; i++) {
    //   bedController.bleSendCode(sendArr);
    //   await Future.delayed(const Duration(milliseconds: 500));
    //   print("$receive");
    //   if (receive.length > 0) {
    //     for (var i = 0; i < receive.length; i++) {
    //       List<int> r = receive[i];
    //       if (handleTimeResult(r, 0x30)) {
    //         bedController.deviceProp?.receiveLogArr.remove(fun);
    //         showToast("保存成功", color: color_success);
    //         return;
    //       }
    //     }
    //   }
    // }
    // showToast("保存失败");
    // bedController.deviceProp?.receiveLogArr.remove(fun);
  }

  handleTimeResult(List<int> r, int type) {
    if (r.length == 18 &&
        r[0] == 255 &&
        r[1] == 255 &&
        r[2] == 255 &&
        r[3] == 255 &&
        r[4] == 0 &&
        r[5] == 9 &&
        r[6] == type &&
        r[7] == 0x01) {
      if (r[8] == 0x01) {
        controller.model.rxhxIsStart = true;
      } else if (r[8] == 0x02 || r[8] == 0x00) {
        controller.model.rxhxIsStart = false;
      } else {
        return false;
      }
      controller.model.rxhxWakeTime[0] = int.parse(r[9].toRadixString(16));
      controller.model.rxhxWakeTime[1] = int.parse(r[10].toRadixString(16));
      for (var i = 0; i < 7; i++) {
        int v = pow(2, i + 1).toInt();
        controller.model.rxhxWeeks[i] = (v & r[12]) == v ? 1 : 0;
      }
      controller.model.rxhxIsAnMo = (r[14] & 0x0f) == 1 ? true : false;
      controller.model.rxhxLocation = (r[14] & 0xf0) >> 4;
      controller.updateAll();
      return true;
    }
    if (r[0] == 255 &&
        r[1] == 255 &&
        r[2] == 255 &&
        r[3] == 255 &&
        r[4] == 0 &&
        r[5] == 3 &&
        r[6] == type &&
        r[7] == 0x01 &&
        r[8] == 0x00 &&
        r.length == 12) {
      resetRxhx();
      return true;
    }
    return false;
  }

  currentTimeSend() async {
    // DateTime date = DateTime.now();
    // List<int> arr = [0x20, 0x01];
    // arr.add(int.parse("${date.hour}", radix: 16));
    // arr.add(int.parse("${date.minute}", radix: 16));
    // arr.add(int.parse("${date.second}", radix: 16));
    // arr.add(int.parse("${date.weekday}", radix: 16));
    // arr.add(int.parse("${date.year}".substring(2), radix: 16));
    // arr.add(int.parse("${date.month}", radix: 16));
    // arr.add(int.parse("${date.day}", radix: 16));
    // var sendArr = getCode(arr);
    // List receive = [];
    // Function fun = (d) {
    //   receive.add(d);
    // };
    // bedController.deviceProp?.receiveLogArr.add(fun);
    // bedController.bleSendCode(sendArr);
    // for (var i = 0; i < 3; i++) {
    //   await Future.delayed(const Duration(milliseconds: 500));
    //   print("$receive");
    //   if (receive.length > 0) {
    //     for (var i = 0; i < receive.length; i++) {
    //       List<int> r = receive[i];
    //       if (handleTimeResult(r, 0x20)) {
    //         bedController.deviceProp?.receiveLogArr.remove(fun);
    //         return;
    //       }
    //     }
    //   }
    // }
    // bedController.deviceProp?.receiveLogArr.remove(fun);
  }

  getLine() {
    return Divider(
      color: const Color(0XFF929699),
      thickness: 0.5.rpx,
      height: 0,
    );
  }

  List weeks = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

  @override
  Widget build(BuildContext context) {
    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,
                title: Container(
                  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: 20.rpx,
                        child: returnIconButtomNew,
                      ),
                    ],
                  ),
                ),
                actions: [],
                centerTitle: false,
              ),
              body: SafeArea(
                top: true,
                child: Obx(
                  () => Container(
                    padding: EdgeInsets.only(left: 30.rpx, right: 30.rpx),
                    width: MediaQuery.sizeOf(context).width,
                    height: MediaQuery.sizeOf(context).height * 1.123,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Container(
                          margin: EdgeInsets.only(left: 40.rpx, right: 16.rpx),
                          width: double.infinity,
                          height: 90.rpx,
                          decoration: const BoxDecoration(),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '柔性唤醒功能',
                                style: TextStyle(
                                  fontFamily: 'Readex Pro',
                                  color: Colors.white,
                                  fontSize: 26.rpx,
                                  letterSpacing: 0,
                                ),
                              ),
                              Container(

                                  // height:
                                  //     MediaQuery.sizeOf(context).height *
                                  //         0.04,
                                  child: FlutterSwitch(
                                width: 70.rpx,
                                height: 36.rpx,
                                toggleSize: 30.rpx,
                                activeColor: Color(0XFF6BFDAC),
                                inactiveColor: Color(0XFF003058),
                                toggleColor: Color(0xFF011D33),
                                value: controller.model.smysIsStart,
                                onToggle: (val) {
                                  controller.attr.update((getmodel) {
                                    getmodel.model.smysIsStart = val;
                                  });
                                },
                              )),
                              // Container(
                              //   height:
                              //       MediaQuery.sizeOf(context).height * 0.04,
                              //   child: Switch.adaptive(
                              //     value: controller.model.rxhxIsStart,
                              //     onChanged: (newValue) async {
                              //       controller.attr.update((getmodel) {
                              //         getmodel.model.rxhxIsStart = newValue;
                              //       });
                              //     },
                              //     activeTrackColor: const Color(0xFFD3B684),
                              //     inactiveTrackColor: const Color(0xFF0A1562),
                              //     inactiveThumbColor: const Color(0xFF182B7C),
                              //     trackOutlineWidth: MaterialStateProperty
                              //         .resolveWith<double?>(
                              //             (Set<MaterialState> states) {
                              //       if (states
                              //           .contains(MaterialState.disabled)) {
                              //         return null;
                              //       }
                              //       return null; // Use the default width.
                              //     }),
                              //   ),
                              // ),
                            ],
                          ),
                        ),
                        getLine(),
                        InkWell(
                          onTap: () async {
                            showDayTimeSelectionDialog(context,
                                dayTimeArr: controller.model.rxhxWakeTime,
                                title: "唤醒时间", checkChange: (d) {
                              controller.attr.update((getmodel) {
                                getmodel.model.rxhxWakeTime = [
                                  int.parse("${d[0]}"),
                                  int.parse("${d[1]}")
                                ];
                              });
                              print("$d");
                            });
                          },
                          child: Container(
                            margin:
                                EdgeInsets.only(left: 40.rpx, right: 30.rpx),
                            width: double.infinity,
                            height: 90.rpx,
                            decoration: const BoxDecoration(),
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '唤醒时间',
                                  style: TextStyle(
                                    fontFamily: 'Readex Pro',
                                    color: Colors.white,
                                    fontSize: 26.rpx,
                                    letterSpacing: 0,
                                  ),
                                ),
                                Row(
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    Text(
                                      "${controller.model.rxhxWakeTimeToString}",
                                      style: TextStyle(
                                        fontFamily: 'Readex Pro',
                                        color: Colors.white,
                                        fontSize: 26.rpx,
                                        letterSpacing: 0,
                                      ),
                                    ),
                                    SizedBox(
                                      width: 16.rpx,
                                    ),
                                    Container(
                                        height: 30.rpx,
                                        width: 30.rpx,
                                        child: SvgPicture.asset(
                                          'assets/img/icon/expand_more.svg',
                                          color: Colors.white,
                                        ))
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                        getLine(),
                        InkWell(
                          onTap: () {
                            showOneSelectionDialog(
                              context,
                              arr: ['开', "关"],
                              checkIndex: controller.model.rxhxIsAnMo ? 0 : 1,
                              title: "按摩",
                              checkChange: (index) {
                                controller.attr.update((getmodel) {
                                  getmodel.model.rxhxIsAnMo =
                                      index == 0 ? true : false;
                                });
                              },
                            );
                          },
                          child: Container(
                              margin:
                                  EdgeInsets.only(left: 40.rpx, right: 30.rpx),
                              width: double.infinity,
                              height: 90.rpx,
                              decoration: const BoxDecoration(),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '按摩',
                                    style: TextStyle(
                                      fontFamily: 'Readex Pro',
                                      color: Colors.white,
                                      fontSize: 26.rpx,
                                      letterSpacing: 0,
                                    ),
                                  ),
                                  Row(
                                    mainAxisSize: MainAxisSize.max,
                                    children: [
                                      Text(
                                        controller.model.rxhxIsAnMo ? '开' : '关',
                                        style: TextStyle(
                                          fontFamily: 'Readex Pro',
                                          color: Colors.white,
                                          fontSize: 26.rpx,
                                          letterSpacing: 0,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 16.rpx,
                                      ),
                                      Container(
                                          height: 30.rpx,
                                          width: 30.rpx,
                                          child: SvgPicture.asset(
                                            'assets/img/icon/expand_more.svg',
                                            color: Colors.white,
                                          ))
                                    ],
                                  ),
                                ],
                              )),
                        ),
                        getLine(),
                        InkWell(
                          onTap: () {
                            showOneSelectionDialog(
                              context,
                              arr: location,
                              checkIndex: controller.model.rxhxLocation,
                              title: "唤醒部位",
                              checkChange: (index) {
                                controller.attr.update((getmodel) {
                                  getmodel.model.rxhxLocation = index;
                                });
                              },
                            );
                          },
                          child: Container(
                              margin:
                                  EdgeInsets.only(left: 40.rpx, right: 30.rpx),
                              width: double.infinity,
                              height: 90.rpx,
                              decoration: const BoxDecoration(),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '唤醒部位',
                                    style: TextStyle(
                                      fontFamily: 'Readex Pro',
                                      color: Colors.white,
                                      fontSize: 26.rpx,
                                      letterSpacing: 0,
                                    ),
                                  ),
                                  Row(
                                    mainAxisSize: MainAxisSize.max,
                                    children: [
                                      Text(
                                        location[controller.model.rxhxLocation],
                                        style: TextStyle(
                                          fontFamily: 'Readex Pro',
                                          color: Colors.white,
                                          fontSize: 26.rpx,
                                          letterSpacing: 0,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 16.rpx,
                                      ),
                                      Container(
                                          height: 30.rpx,
                                          width: 30.rpx,
                                          child: SvgPicture.asset(
                                            'assets/img/icon/expand_more.svg',
                                            color: Colors.white,
                                          ))
                                    ],
                                  ),
                                ],
                              )),
                        ),
                        getLine(),
                        Container(
                          margin: EdgeInsets.only(
                              top: 30.rpx,
                              bottom: 30.rpx,
                              left: 40.rpx,
                              right: 30.rpx),
                          width: double.infinity,
                          decoration: const BoxDecoration(),
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '自定义',
                                style: TextStyle(
                                  fontFamily: 'Readex Pro',
                                  color: Colors.white,
                                  fontSize: 26.rpx,
                                  letterSpacing: 0,
                                ),
                              ),
                              // Padding(
                              //   padding: EdgeInsetsDirectional.fromSTEB(
                              //       0, 20.rpx, 0, 0),
                              //   child: Container(
                              //     width: double.infinity,
                              //     height:
                              //         MediaQuery.sizeOf(context).height * 0.046,
                              //     decoration: const BoxDecoration(),
                              //     child: Row(
                              //       mainAxisSize: MainAxisSize.max,
                              //       mainAxisAlignment:
                              //           MainAxisAlignment.spaceBetween,
                              //       children: [
                              //         ...List.generate(7, (index) {
                              //           return InkWell(
                              //             onTap: () {
                              //               controller.attr.update((getmodel) {
                              //                 getmodel.model
                              //                     .rxhxWeeks[index] = getmodel
                              //                             .model
                              //                             .rxhxWeeks[index] ==
                              //                         0
                              //                     ? 1
                              //                     : 0;
                              //               });
                              //             },
                              //             child: AspectRatio(
                              //               aspectRatio: 1,
                              //               child: ClipOval(
                              //                 child: Container(
                              //                   height: double.infinity,
                              //                   decoration: BoxDecoration(
                              //                       color: controller.model
                              //                                       .rxhxWeeks[
                              //                                   index] ==
                              //                               1
                              //                           ? Color(0xFF84F5FF)
                              //                           : Color(0XFF003058)),
                              //                   child: Center(
                              //                     child: Text(
                              //                       weeks[index],
                              //                       style: TextStyle(
                              //                           color: controller.model
                              //                                           .rxhxWeeks[
                              //                                       index] ==
                              //                                   1
                              //                               ? Color(0XFF003058)
                              //                               : Colors.white),
                              //                     ),
                              //                   ),
                              //                 ),
                              //               ),
                              //             ),
                              //           );
                              //         }),
                              //       ],
                              //     ),
                              //   ),
                              // ),
                              Padding(
                                padding: EdgeInsetsDirectional.fromSTEB(
                                    0, 20.rpx, 0, 0),
                                child: SizedBox(
                                  width: double.infinity,
                                  height:
                                      MediaQuery.sizeOf(context).height * 0.046,
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: List.generate(7, (index) {
                                      final bool selected =
                                          controller.model.rxhxWeeks[index] ==
                                              1;
                                      return InkWell(
                                        onTap: () {
                                          controller.attr.update((getmodel) {
                                            getmodel.model.rxhxWeeks[index] =
                                                getmodel.model
                                                            .rxhxWeeks[index] ==
                                                        0
                                                    ? 1
                                                    : 0;
                                          });
                                        },
                                        borderRadius: BorderRadius.circular(
                                            50), // 点击水波圆角区域
                                        child: Container(
                                          width: MediaQuery.sizeOf(context)
                                                  .height *
                                              0.046, // 保证是正圆
                                          height: MediaQuery.sizeOf(context)
                                                  .height *
                                              0.046,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: selected
                                                ? const Color(0xFF84F5FF)
                                                : const Color(0xFF003058),
                                          ),
                                          alignment: Alignment.center,
                                          child: Text(
                                            weeks[index],
                                            style: TextStyle(
                                              color: selected
                                                  ? const Color(0xFF003058)
                                                  : Colors.white,
                                            ),
                                          ),
                                        ),
                                      );
                                    }),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        getLine(),
                        SizedBox(
                          height: 30.rpx,
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 26.rpx, right: 26.rpx),
                          width: double.infinity,
                          decoration: const BoxDecoration(),
                          child: Text(
                            '*注：开启该功能后，在设置的时间点，设备将启动一段固定时长的柔性唤醒功能。',
                            style: TextStyle(
                              fontFamily: 'Readex Pro',
                              color: Color(0xFF929699),
                              fontSize: 20.rpx,
                              letterSpacing: 0,
                            ),
                          ),
                        ),
                        Spacer(),
                        Padding(
                            padding: EdgeInsets.only(bottom: 85.rpx),
                            child: CustomCard(
                              borderRadius: 16.rpx,
                              gradientDirection: GradientDirection.vertical,
                              onTap: () {},
                              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("完成",
                                    style: TextStyle(
                                        color: const Color(0xFF003058),
                                        fontSize: 26.rpx)),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
              ),
            ),
          )),
    );
  }
}
