import 'dart:async';

import 'package:ef/ef.dart';
import 'package:flutter/material.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/base/GradientSwitch.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/message/common_message_setting_controller.dart';
import 'package:vbvs_app/controller/message/message_setting_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';

class MessageSettingPage extends StatefulWidget {
  var data;
  MessageSettingPage({super.key, required this.data});

  @override
  State<MessageSettingPage> createState() => _MessageSettingPageState();
}

class _MessageSettingPageState extends State<MessageSettingPage> {
  final ThemeController themeController = Get.find();
  MessageSettingController messageSettingController = Get.find();
  CommonMessageSettingController commonMessageSettingController = Get.find();

  @override
  void initState() {
    super.initState();
    _fetchCommonMessageSetting();
    _fetchDeviceMessageSetting();
  }

  Future<void> _fetchCommonMessageSetting() async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.user_setting;
    String type = "user_message_setting";
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}?type=$type";
    requestWithLog(
      logTitle: "查询用户消息配置",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,      
      onSuccess: (res) {
        if (res.data == null || res.data.isEmpty) {
          var data = {
            "type": type,
            "setting": 1,
            "appSetting": 1,
            "serviceSetting": 1,
            "tipSetting": 1,
            "deviceUpgradeSetting": 1,
            "deviceIssueSetting": 1,
          };
          requestWithLog(
            logTitle: "更新用户消息配置",
            method: MyHttpMethod.put,
            queryUrl: queryUrl,
            data: data,
            onSuccess: (res) {
              requestWithLog(
                logTitle: "查询用户消息配置",
                method: MyHttpMethod.get,
                queryUrl: queryUrl,
                onSuccess: (res) {
                  if (res.data != null && res.data.isNotEmpty) {
                    var datalist = res.data;
                    commonMessageSettingController.model.setting =
                        datalist['setting'];
                    commonMessageSettingController.model.appSetting =
                        datalist['appSetting'];
                    commonMessageSettingController.model.serviceSetting =
                        datalist['serviceSetting'];
                    commonMessageSettingController.model.tipSetting =
                        datalist['tipSetting'];
                    commonMessageSettingController.model.deviceUpgradeSetting =
                        datalist['deviceUpgradeSetting'];
                    commonMessageSettingController.model.deviceIssueSetting =
                        datalist['deviceIssueSetting'];
                    commonMessageSettingController.updateAll();
                  }
                },
              );

              //
            },
          );
        } else {
          var datalist = res.data;
          commonMessageSettingController.model.setting = datalist['setting'];
          commonMessageSettingController.model.appSetting =
              datalist['appSetting'];
          commonMessageSettingController.model.serviceSetting =
              datalist['serviceSetting'];
          commonMessageSettingController.model.tipSetting =
              datalist['tipSetting'];
          commonMessageSettingController.model.deviceUpgradeSetting =
              datalist['deviceUpgradeSetting'];
          commonMessageSettingController.model.deviceIssueSetting =
              datalist['deviceIssueSetting'];
          commonMessageSettingController.updateAll();
        }
      },
      onFailure: (res) {
        print(res);
      },
    );
  }

  Future<void> _fetchDeviceMessageSetting() async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.user_setting;
    String mac = widget.data['mac'];
    String type = "user_device_message_setting_$mac";
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}?type=$type";
    requestWithLog(
      logTitle: "查询用户消息配置",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        if (res.data == null || res.data.isEmpty) {
          var data = {
            "type": type,
            "setting": 1,
            "appSetting": 1,
            "serviceSetting": 1,
          };
          requestWithLog(
            logTitle: "更新用户消息配置",
            method: MyHttpMethod.put,
            queryUrl: queryUrl,
            data: data,
            onSuccess: (res) {
              requestWithLog(
                logTitle: "查询用户消息配置",
                method: MyHttpMethod.get,
                queryUrl: queryUrl,
                onSuccess: (res) {
                  if (res.data != null && res.data.isNotEmpty) {
                    var datalist = res.data;
                    messageSettingController.model.setting =
                        datalist['setting'];
                    messageSettingController.model.appSetting =
                        datalist['appSetting'];
                    messageSettingController.model.serviceSetting =
                        datalist['serviceSetting'];
                    messageSettingController.updateAll();
                  }
                },
              );

              //
            },
          );
        } else {
          var datalist = res.data;
          messageSettingController.model.setting = datalist['setting'];
          messageSettingController.model.appSetting = datalist['appSetting'];
          messageSettingController.model.serviceSetting =
              datalist['serviceSetting'];
          messageSettingController.updateAll();
        }
      },
      onFailure: (res) {
        print(res);
      },
    );
  
  }

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

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, bodysize) => GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/img/bgNoImg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              backgroundColor: themeController.currentColor.sc17,
              automaticallyImplyLeading: false,
              iconTheme: IconThemeData(
                color: themeController.currentColor.sc3,
              ),
              titleSpacing: 0,
              title: Container(
                width: double.infinity,
                height: 180.rpx,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    /// 居中标题
                    Text(
                      '消息设置'.tr,
                      style: TextStyle(
                        fontFamily: 'ReadexPro',
                        color: themeController.currentColor.sc3,
                        letterSpacing: 0,
                        fontSize: 30.rpx,
                      ),
                    ),
                    Positioned(
                      left: 0,
                      child: returnIconButtomAddCallback(() {}),
                    ),
                  ],
                ),
              ),
              actions: [],
              centerTitle: false,
            ),
            body: GestureDetector(
              child: SafeArea(
                top: true,
                child: Padding(
                  padding: EdgeInsetsDirectional.fromSTEB(0.rpx, 0, 0.rpx, 0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Padding(
                        padding:
                            EdgeInsetsDirectional.fromSTEB(0, 30.rpx, 0, 0),
                        child: Container(
                          width: double.infinity,
                          constraints: BoxConstraints(
                            minHeight: 90.rpx,
                          ),
                          decoration: BoxDecoration(
                              color: themeController.currentColor.sc5),
                          child: Padding(
                            padding: EdgeInsetsDirectional.fromSTEB(
                                30.rpx, 15.rpx, 30.rpx, 15.rpx),
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Text(
                                    "消息提醒设置".tr,
                                    style: TextStyle(
                                        color: themeController.currentColor.sc3,
                                        fontSize:
                                            AppConstants().title_text_fontSize),
                                  ),
                                ),
                                Obx(() {
                                  return GradientSwitch(
                                    value: commonMessageSettingController
                                                .model.setting ==
                                            1
                                        ? (messageSettingController
                                                    .model.setting ==
                                                1
                                            ? true
                                            : false)
                                        : false,
                                    onChanged: (val) {
                                      if (commonMessageSettingController
                                              .model.setting ==
                                          0) {
                                        TopSlideNotification.show(context,
                                            text: "请先在设置里的消息通知打开全部消息配置".tr,
                                            textColor: themeController
                                                .currentColor.sc9);
                                        return;
                                      }
                                      String serviceAddress =
                                          ServiceConstant.service_address;
                                      String serviceName =
                                          ServiceConstant.server_service;
                                      String serviceApi =
                                          ServiceConstant.user_setting;
                                      String mac = widget.data['mac'];
                                      String type =
                                          "user_device_message_setting_$mac";
                                      String queryUrl =
                                          "${serviceAddress}${serviceName}${serviceApi}";
                                      var data = {
                                        "type": type,
                                        "setting": val == true ? 1 : 0,
                                        "appSetting": messageSettingController
                                            .model.appSetting,
                                        "serviceSetting":
                                            messageSettingController
                                                .model.serviceSetting,
                                      };
                                      requestWithLog(
                                          logTitle: "更新消息推送状态",
                                          method: MyHttpMethod.put,
                                          queryUrl: queryUrl,
                                          data: data,
                                          onSuccess: (res) {
                                            _fetchDeviceMessageSetting();
                                            messageSettingController
                                                .updateAll();
                                          });
                                    },
                                    activeGradient: LinearGradient(
                                      colors: [
                                        themeController.currentColor.sc1,
                                        themeController.currentColor.sc2
                                      ],
                                    ),
                                    activeThumbColor: Colors.white,
                                    inactiveThumbColor:
                                        stringToColor("#A2A4A9"),
                                    inactiveColor: stringToColor("#161B28"),
                                  );
                                }),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(
                            30.rpx, 21.rpx, 30.rpx, 0),
                        child: Container(
                          decoration: BoxDecoration(
                            color: themeController.currentColor.sc5,
                            borderRadius: BorderRadius.circular(
                                AppConstants().normal_container_radius),
                          ),
                          child: Padding(
                            padding: EdgeInsetsDirectional.fromSTEB(
                                30.rpx, 40.rpx, 30.rpx, 54.rpx),
                            child: Container(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisSize: MainAxisSize.max,
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          "APP消息".tr,
                                          style: TextStyle(
                                              color: themeController
                                                  .currentColor.sc3,
                                              fontSize: AppConstants()
                                                  .title_text_fontSize),
                                        ),
                                      ),
                                      Obx(() {
                                        return GradientSwitch(
                                          value: commonMessageSettingController
                                                      .model.setting ==
                                                  1
                                              ? (messageSettingController
                                                          .model.setting ==
                                                      1
                                                  ? (messageSettingController
                                                              .model
                                                              .appSetting ==
                                                          1
                                                      ? true
                                                      : false)
                                                  : false)
                                              : false,
                                          onChanged: (val) {
                                            if (commonMessageSettingController
                                                    .model.setting ==
                                                0) {
                                              TopSlideNotification.show(context,
                                                  text:
                                                      "请先在设置里的消息通知打开全部消息配置".tr,
                                                  textColor: themeController
                                                      .currentColor.sc9);
                                              return;
                                            }
                                            if (messageSettingController
                                                    .model.setting ==
                                                0) {
                                              TopSlideNotification.show(context,
                                                  text: "请先打开消息提醒设置".tr,
                                                  textColor: themeController
                                                      .currentColor.sc9);
                                              return;
                                            }
                                            String serviceAddress =
                                                ServiceConstant.service_address;
                                            String serviceName =
                                                ServiceConstant.server_service;
                                            String serviceApi =
                                                ServiceConstant.user_setting;
                                            String mac = widget.data['mac'];
                                            String type =
                                                "user_device_message_setting_$mac";
                                            String queryUrl =
                                                "${serviceAddress}${serviceName}${serviceApi}";
                                            var data = {
                                              "type": type,
                                              "setting":
                                                  messageSettingController
                                                      .model.setting,
                                              "appSetting": val == true ? 1 : 0,
                                              "serviceSetting":
                                                  messageSettingController
                                                      .model.serviceSetting,
                                            };
                                            requestWithLog(
                                                logTitle: "更新消息推送状态",
                                                method: MyHttpMethod.put,
                                                queryUrl: queryUrl,
                                                data: data,
                                                onSuccess: (res) {
                                                  _fetchDeviceMessageSetting();
                                                  messageSettingController
                                                      .updateAll();
                                                });
                                          },
                                          activeGradient: LinearGradient(
                                            colors: [
                                              themeController.currentColor.sc1,
                                              themeController.currentColor.sc2
                                            ],
                                          ),
                                          activeThumbColor: Colors.white,
                                          inactiveThumbColor:
                                              stringToColor("#A2A4A9"),
                                          inactiveColor:
                                              stringToColor("#161B28"),
                                        );
                                      }),
                                    ],
                                  ),
                                  Text(
                                    AppConstants().ent_type == 1? "APP消息介绍".tr:"打开“欢睡科技”APP，可以查看该设备的消息内容",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc4,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                  ),
                                  Row(
                                    mainAxisSize: MainAxisSize.max,
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          "服务号消息".tr,
                                          style: TextStyle(
                                              color: themeController
                                                  .currentColor.sc3,
                                              fontSize: AppConstants()
                                                  .title_text_fontSize),
                                        ),
                                      ),
                                      Obx(() {
                                        return GradientSwitch(
                                          value: commonMessageSettingController
                                                      .model.setting ==
                                                  1
                                              ? (messageSettingController
                                                          .model.setting ==
                                                      1
                                                  ? (messageSettingController
                                                              .model
                                                              .serviceSetting ==
                                                          1
                                                      ? true
                                                      : false)
                                                  : false)
                                              : false,
                                          onChanged: (val) {
                                            if (commonMessageSettingController
                                                    .model.setting ==
                                                0) {
                                              TopSlideNotification.show(context,
                                                  text:
                                                      "请先在设置里的消息通知打开全部消息配置".tr,
                                                  textColor: themeController
                                                      .currentColor.sc9);
                                              return;
                                            }
                                            if (messageSettingController
                                                    .model.setting ==
                                                0) {
                                              TopSlideNotification.show(context,
                                                  text: "请先打开消息提醒设置".tr,
                                                  textColor: themeController
                                                      .currentColor.sc9);
                                              return;
                                            }
                                            String serviceAddress =
                                                ServiceConstant.service_address;
                                            String serviceName =
                                                ServiceConstant.server_service;
                                            String serviceApi =
                                                ServiceConstant.user_setting;
                                            String mac = widget.data['mac'];
                                            String type =
                                                "user_device_message_setting_$mac";
                                            String queryUrl =
                                                "${serviceAddress}${serviceName}${serviceApi}";
                                            var data = {
                                              "type": type,
                                              "setting":
                                                  messageSettingController
                                                      .model.setting,
                                              "appSetting":
                                                  messageSettingController
                                                      .model.appSetting,
                                              "serviceSetting":
                                                  val == true ? 1 : 0,
                                            };
                                            requestWithLog(
                                                logTitle: "更新消息推送状态",
                                                method: MyHttpMethod.put,
                                                queryUrl: queryUrl,
                                                data: data,
                                                onSuccess: (res) {
                                                  _fetchDeviceMessageSetting();
                                                  messageSettingController
                                                      .updateAll();
                                                });
                                          },
                                          activeGradient: LinearGradient(
                                            colors: [
                                              themeController.currentColor.sc1,
                                              themeController.currentColor.sc2
                                            ],
                                          ),
                                          activeThumbColor: Colors.white,
                                          inactiveThumbColor:
                                              stringToColor("#A2A4A9"),
                                          inactiveColor:
                                              stringToColor("#161B28"),
                                        );
                                      }),
                                    ],
                                  ),
                                  Text(
                                    AppConstants().ent_type == 1? "服务号消息介绍".tr:"无需打开“欢睡科技”APP，关注欢睡智能睡眠研究所服务号后，微信内即可接收该设备消息推送",
                                    style: TextStyle(
                                        color: themeController.currentColor.sc4,
                                        fontSize: AppConstants()
                                            .normal_text_fontSize),
                                  ),
                                ].divide(SizedBox(
                                  height: 49.rpx,
                                )),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
