import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/models/enums/index.dart';
import '../../../../common/services/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';

class SkinController extends GetxController {
  SkinController();

  Rx<ThemeMode> themeMode = Rx<ThemeMode>(ThemeMode.system);
  Rx<O2Skin> skin = O2Skin.blue.obs;

  _initData() {
    update(["skin"]);
  }
 
  @override
  void onReady() {
    loadThemeMode();
    super.onReady();
  }

  Future<void> loadThemeMode() async {
    themeMode.value  = SharedPreferenceService.to.getThemeMode();
    OLogger.d('当前主题mode ：${themeMode.value.name}');
    skin.value = SharedPreferenceService.to.getThemeSkin();
    OLogger.d('当前系统主题皮肤： ${skin.value.name}');
    _initData();
  }
 

  Future<void> changeWithSystem(bool value) async {
    OLogger.d('切换跟随系统，$value');
    if (value) {
      themeMode.value = ThemeMode.system; // 默认跟随系统
    } else {
      themeMode.value = ThemeMode.light;
    }
    _initData();
    updateUI();
  }
  Future<void> clickLightMode() async {
    if (themeMode.value == ThemeMode.light) {
      return;
    }
    themeMode.value = ThemeMode.light;
    _initData();
    updateUI();
  }
  Future<void> clickDarkMode() async {
    if (themeMode.value == ThemeMode.dark) {
      return;
    }
    themeMode.value = ThemeMode.dark;
    _initData();
    updateUI();
  }

  Future<void> updateUI() async {
    await SharedPreferenceService.to.putString(SharedPreferenceService.appThemeModeKey, themeMode.value.name);
    Get.changeThemeMode(themeMode.value);
    OLogger.d('切换模式');
  }

  /// 点击切换主题皮肤
  clickChangeSkin(O2Skin s) {
    if (skin.value == s) {
      return;
    }
    skin.value = s;
    _initData();
    updateSkin();
  }

  /// 切换主题皮肤
  Future<void> updateSkin() async {
    await SharedPreferenceService.to.putString(SharedPreferenceService.appThemeSkinKey, skin.value.name);
    final theme = Get.isDarkMode ? AppTheme.getDarkThemeBySkin(skin.value) :  AppTheme.getLightThemeBySkin(skin.value);
    Get.changeTheme(theme);
  }

}
