// ignore_for_file: constant_identifier_names

import 'package:get/get.dart';
import 'package:vitalapp/architecture/utils/nums.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/states/waist.dart';

// 主项
const String WHB = "WHB";
// 子项
const String WHR = "WHR";
const String WAISTLINE = "WAISTLINE";
const String HIPLINE = "HIPLINE";

/// 腰臀比
class WaistDeviceController extends GetxController {
  final state = WaistState();

  final medicalController = Get.find<MedicalController>();

  @override
  void onReady() {
    super.onReady();
    _loadCacheData();
  }

  /// 腰围变更
  void onWaistlineChanged(double? value) {
    if (value != null) {
      state.waistline = double.parse(value.toStringAsFixed(2));
    } else {
      state.waistline = null;
    }
    saveExamData();
  }

  /// 臀围变更
  void onHiplineChanged(double? value) {
    if (value != null) {
      state.hipline = double.parse(value.toStringAsFixed(2));
    } else {
      state.hipline = null;
    }
    saveExamData();
  }

  /// 保存测量数据
  void saveExamData() {
    if (state.waistline == null && state.hipline == null) {
      // 都无值不可提交
      medicalController.diagnosisDataValue.remove(WHB);
    } else {
      medicalController.diagnosisDataValue[WHB] = {
        WAISTLINE: NumUtils.displayDouble(state.waistline),
        HIPLINE: NumUtils.displayDouble(state.hipline),
        WHR: NumUtils.displayDouble(state.whr),
      };
    }
    medicalController.saveCachedRecord();
  }

  ///  加载缓存数据
  void _loadCacheData() {
    final jsonMap = medicalController.diagnosisDataValue[WHB];
    if (jsonMap != null) {
      final data = jsonMap as Map<String, dynamic>;
      if (data.containsKey(WAISTLINE)) {
        state.waistline = double.tryParse(data[WAISTLINE]);
      }
      if (data.containsKey(HIPLINE)) {
        state.hipline = double.tryParse(data[HIPLINE]);
      }
    }
  }
}
