import 'dart:async';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:ef/ef.dart';
import 'package:vbvs_app/controller/main_bottom/main_page_controller.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/pages/common/selectDialog.dart';

class GlobalModel {
  List deviceList = [];//用户绑定设备数量
  Map deviceMain = {};

  Map useBedController = {}; //之前控制的设备

  List deviceType = [];

  List homeImgList = []; //轮播图

  bool hideBottomNavigationBar = false;

  get deviceMainIsShare {
    if (deviceMain != null && deviceMain["type"] == 2) {
      return true;
    } else {
      return false;
    }
  }

  // get JunheDevices {
  //   List arr = [];

  //   deviceList.forEach((d) {
  //     d?["personnelInfo"]?.forEach((item) {
  //       if (item["mac"] == d["bindMacA"] &&
  //           arr.indexWhere((a) => a["mac"] == item["mac"]) == -1) {
  //         arr.add(item);
  //       }
  //     });
  //     if (d["bindMacB"] != null && d["bindMacB"] != "") {
  //       d["personnelInfo"].forEach((item) {
  //         if (item["mac"] == d["bindMacB"] &&
  //             arr.indexWhere((a) => a["mac"] == item["mac"]) == -1) {
  //           arr.add(item);
  //         }
  //       });
  //     }
  //   });

  //   return arr;
  // }

  get JunheDevices {
    List arr = [];
    try {
      if (deviceList != null) {
        deviceList.forEach((d) {
          if (d?["personnelInfo"] != null) {
            d["personnelInfo"].forEach((item) {
              if (item["mac"] == d["bindMacA"] &&
                  arr.indexWhere((a) => a["mac"] == item["mac"]) == -1) {
                arr.add(item);
              }
            });
          }
          if (d["bindMacB"] != null && d["bindMacB"] != "") {
            if (d["personnelInfo"] != null) {
              d["personnelInfo"].forEach((item) {
                if (item["mac"] == d["bindMacB"] &&
                    arr.indexWhere((a) => a["mac"] == item["mac"]) == -1) {
                  arr.add(item);
                }
              });
            }
          }
        });
      }
    } catch (e) {
      print(e);
    }
    return arr;
  }

  get mainDevicePeople {
    if (deviceMain == null || deviceMain["mac"] == null) {
      return [{}, {}];
    }
    List arr = [{}, {}];
    if (deviceMain["personnelInfo"] != null) {
      if (deviceMain["bindMacA"] != null) {
        deviceMain["personnelInfo"]?.forEach((d) {
          if (d["mac"] == deviceMain["bindMacA"]) {
            arr[0] = d;
          }
        });
      }
      if (deviceMain["bindMacB"] != null) {
        deviceMain["personnelInfo"]?.forEach((d) {
          if (d["mac"] == deviceMain["bindMacB"]) {
            arr[1] = d;
          }
        });
      }
    }
    return arr;
  }

  GlobalModel();
}

class GlobalController extends GetControllerEx<GlobalModel> {
  GlobalController() {
    attr = GetModel(GlobalModel()).obs;
  }

  get userInfoController => Get.find<UserInfoController>();

  Timer? getDeviceListTimer;

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

  resetParmAll() {
    resetParm();
    Get.find<MainPageController>().resetParm();
  }

  resetParm() {
    getDeviceListTimer?.cancel();
    getDeviceListTimer = null;
    model.deviceList = [];
    model.deviceMain = {};
    model.useBedController = {};
    model.deviceType = [];
    model.homeImgList = [];
    model.hideBottomNavigationBar = false;
  }

  deviceUpdateTimerCreated() {
    if (getDeviceListTimer == null) {
      getDeviceListTimer = Timer.periodic(const Duration(seconds: 10), (t) {
        if (userInfoController.model.token != null) {}
      });
    }
  }

  getDeviceGroupName(device) {
    return "${device['roomName']}/${device["deviceType"]?["name"]}/${device["name"]}";
  }

  getDeviceGroupName2(device) {
    return "${device["deviceType"]?["name"]}/${device["name"]}";
  }

  getUpperCaseMac(mac) {
    if (mac == null || mac == "") {
      return "";
    }
    return "$mac".toUpperCase();
  }


  getDeviceList({int time = 1}) async {
    await EasyDartModule.dio.get("/api/device/info/list").then((d) {
      Map d_ = {};
      d.data?["data"]?.forEach((item) {
        if (d_[item["roomName"]] == null) {
          d_[item["roomName"]] = [];
        }
        d_[item["roomName"]].add(item);
      });
      List res_ = [];
      d_.keys.forEach((key) {
        res_.addAll(d_[key]);
      });
      model.deviceList = res_;
      if (model.deviceMain != null && model.deviceMain["mac"] != null) {
        bool isClose = false;
        model.deviceList.forEach((item) {
          if (item["mac"] == model.deviceMain["mac"]) {
            model.deviceMain = item;
            isClose = true;
            updateAll();
          }
        });
        if (!isClose) {
          model.deviceMain = {};
          updateAll();
          showCustomConfirmAndCancelDialog(Get.context!, "设备已经被解绑，是否回到主界面？")
              .then((e) {
            if (e == "confirm") {
              Get.find<MainPageController>().model.currentIndex = 0;
              Get.offAllNamed("/mianPageBottomChange");
            }
          });
        }
      } else {
        updateAll();
      }
    }).catchError((e) {
      print("$e");
      if (time > 0) {
        getDeviceList(time: time - 1);
      }
    });
  }
}
