/* 当前评阅任务ID */
import 'dart:convert';

import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/common/model/enum/KeyboardType.dart';
import 'package:marking_app/common/model/marking/do_marking_keyboard_model.dart';
import 'package:marking_app/utils/fast_data.dart';
import 'package:marking_app/utils/index.dart';

// 阅卷键盘习惯偏好
final markingKeyboardProvider = StateNotifierProvider<DoMarkingKeyboardHandle, DoMarkingKeyboardModel>(
    (ref) => DoMarkingKeyboardHandle(DoMarkingKeyboardModel()));

// 阅卷键盘习惯偏好
class DoMarkingKeyboardHandle extends StateNotifier<DoMarkingKeyboardModel> {
  DoMarkingKeyboardHandle(DoMarkingKeyboardModel moedl) : super(moedl);

  // 初始化键盘
  void initMarkingKeyboard() async {
    DoMarkingKeyboardModel? localModel = await FastData.getInstance().getPreferences();
    if (localModel != null) {
      SortKeyboard? sort = localModel.sort;
      // FULL_AND_AERO_TOP_INVERTED_ORDER 废弃 如果缓存中设置了这个需要自定义到默认设置项
      if (sort != null && sort == SortKeyboard.FULL_AND_AERO_TOP_INVERTED_ORDER)
        localModel.sort = SortKeyboard.INVERTED_ORDER;
      toggleKeyboard(localModel, synchro: false);
    }
  }

  // 辅助键盘打关闭切换
  Future<bool?> changeOpenAuxiliary(bool? val) async {
    try {
      if (state.keyboard != KeyboardType.RIGHT_SELECTION) {
        return null;
      }
      state.openAuxiliary = val ?? !state.openAuxiliary;
      toggleKeyboard(DoMarkingKeyboardModel.fromJson(state.toJson()));
      return state.openAuxiliary;
    } catch (e) {
      return null;
    }
  }

  // 切换键盘
  Future<bool> toggleKeyboard(DoMarkingKeyboardModel item, {bool synchro = true}) async {
    if (!synchro) {
      state = item;
      return true;
    }
    bool flag = false;
    if (synchro) {
      flag = await FastData.getInstance().setPreferences(item);
    }
    if (flag) state = item;
    return flag;
  }

  // 关闭引导页
  void closeTheBootPage() {
    state.guidePageDisplay = false;
  }

  // 清空
  void clean() {
    toggleKeyboard(DoMarkingKeyboardModel());
    FastData.getInstance().cleanPreferences();
  }
}

// 阅卷小题切换监听
final markingSubtopicSwitchingProvider =
    StateNotifierProvider<MarkingSubtopicSwitchingHandle, int>((ref) => MarkingSubtopicSwitchingHandle(-1));

// 阅卷小题切换监听
class MarkingSubtopicSwitchingHandle extends StateNotifier<int> {
  MarkingSubtopicSwitchingHandle(int moedl) : super(moedl);

  void setVal(int index) {
    state = index;
  }

  // 清空
  void clean() {
    state = -1;
  }
}
