import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:get/get.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/module/profile/profile_page.dart';
import 'package:keyboard/utils/toast_util.dart';
import '../../data/bean/keyboard_info.dart';
import '../../data/consts/error_code.dart';
import '../../plugins/keyboard_android_platform.dart';
import '../../utils/error_handler.dart';
import '../../utils/http_handler.dart';
import '../../widget/flutter_ruler_picker.dart';
import '../store/store_page.dart';

@injectable
class IntimacyScaleController extends BaseController {
  final tag = "IntimacyScaleController";

  final KeyboardRepository keyboardRepository;

  Rxn<KeyboardInfo> get currentKeyboardInfo =>
      keyboardRepository.chooseKeyboardInfo;

  late Rx<RulerPickerController> rulerPickerController;

  List<RulerRange> ranges = const [RulerRange(begin: 0, end: 100, scale: 1)];

  // 当前亲密度
  RxInt currentCustomIntimacy = 0.obs;

  IntimacyScaleController(this.keyboardRepository);

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

    currentCustomIntimacy.value = currentKeyboardInfo.value?.intimacy ?? 0;
    rulerPickerController =
        RulerPickerController(
          value: currentKeyboardInfo.value?.intimacy ?? 0,
        ).obs;
    rulerPickerController.value.addListener(() {
      currentCustomIntimacy.value = rulerPickerController.value.value.toInt();
    });
  }

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

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

  void clickBack() {
    Get.back();
  }

  void onChangeIntimacy(num value) {
    currentCustomIntimacy.value = value.toInt();
  }

  Future<void> clickSaveButton() async {
    if (currentKeyboardInfo.value == null &&
        currentKeyboardInfo.value?.id == null) {
      ToastUtil.show("请选择ta的键盘");
      ProfilePage.start();
      return;
    }

    try {
      await keyboardRepository.updateKeyboardInfo(
        keyboardId: currentKeyboardInfo.value!.id!,
        intimacy: currentCustomIntimacy.value,
      );
      // 通知键盘插件，更新键盘的亲密度值
      var keyboardInfo = currentKeyboardInfo.value!;
      keyboardInfo.intimacy = currentCustomIntimacy.value;
      KeyboardAndroidPlatform.updateKeyboardInfo(keyboardInfo);
      await keyboardRepository.refreshData();

      Get.back();
    } catch (error) {
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.noLoginError) {
          ErrorHandler.toastError(error);
        } else {
          ErrorHandler.toastError(error);
        }
      } else {
        ErrorHandler.toastError(error);
      }
    }
  }
}
