import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:sk_base_mobile/constants/dict_enum.dart';
import 'package:sk_base_mobile/models/dict_item.model.dart';
import 'package:sk_base_mobile/models/dict_type.model.dart';
import 'package:sk_base_mobile/apis/index.dart';
import 'package:sk_base_mobile/util/logger_util.dart';

const needCachedKey = [
  DictTypeEnum.InventoryRoom,
  DictTypeEnum.InventoryLine,
  DictTypeEnum.InventoryLineLevel
];

class DictService extends GetxService {
  Future<DictService> init() async {
    await getDictTypes();
    return this;
  }

  RxList<DictTypeModel> dictTypes = RxList([]);
  Future<void> getDictTypes() async {
    try {
      final response = await Api.getDictTypeAll({
        'storeCodes': needCachedKey,
        'withItems': true,
      });
      dictTypes.value = (response.data as List)
          .map((item) => DictTypeModel.fromJson(item))
          .toList();
    } catch (e) {
      LoggerUtil().error('getDictTypes error: $e');
    }
  }

  List<DictItemModel> getDictItemsByCode(String code) {
    return dictTypes.firstWhereOrNull((item) => item.code == code)?.dictItems ??
        [];
  }
}
