import 'dart:convert';

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

class SearchTagNotifier with ChangeNotifier {
  ///文本标签集合
  List<String> _tagList = [];

  /// 保存历史标签的sp key
  static final String _SP_HOISTROY_KEY = 'hoistroyTag';

  /// 最大存储条数
  static final int _MAX_COUNT = 10;

  /// 初始化历史搜索标签
  Future<List<String>> getHistoryTag() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String jsonStr = prefs.getString(_SP_HOISTROY_KEY);
    if (null != jsonStr && jsonStr.length > 0) {
      _tagList.clear();
      final Map jsonMap = jsonDecode(jsonStr);
      if (jsonMap != null && jsonMap.length > 0) {
        jsonMap.forEach((key, value) => _tagList.insert(0, value));
      }
    }
    return _tagList;
  }

  /// 添加搜索
  void addTag(String tag) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String jsonStr = prefs.getString(_SP_HOISTROY_KEY);
    if (null != jsonStr && jsonStr.length > 0) {
      final Map jsonMap = jsonDecode(jsonStr);
      jsonMap[tag.toString()] = tag.toString();

      _tagList.insert(0, tag); // 第一位
      if (_tagList.length > _MAX_COUNT) {
        jsonMap.remove(_tagList[_tagList.length - 1]);
        _tagList.removeAt(_tagList.length - 1);
      }

      prefs.setString(_SP_HOISTROY_KEY, jsonEncode(jsonMap));
    } else {
      prefs.setString(_SP_HOISTROY_KEY, jsonEncode({'${tag.toString()}': '${tag.toString()}'}));
      _tagList.add(tag);
    }
    notifyListeners();
  }

  /// 请空
  void clear() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // String jsonStr = prefs.getString(_SP_HOISTROY_KEY);
    prefs.setString(_SP_HOISTROY_KEY, '');
    _tagList.clear();
    notifyListeners();
  }
}
