import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zhiying_base_widget/pages/search_page/notifier/search_tag_notifier.dart';
import 'package:zhiying_base_widget/pages/search_result_page/search_result_page.dart';
import 'package:zhiying_base_widget/widgets/search/history_tag/model/search_history_model.dart';
import 'package:zhiying_base_widget/widgets/search/widget/text_tag_widget.dart';
import 'package:zhiying_base_widget/widgets/search/widget/title_widget.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';

///
/// 历史搜索标签
///
class SearchHistoryTagWidget extends StatefulWidget {
  final Map<String, dynamic> data;
  SearchHistoryModel model;

  SearchHistoryTagWidget(this.data, {Key key}) : super(key: key) {
    try {
      model = SearchHistoryModel.fromJson(jsonDecode(data['data']));
    } catch (e) {}
  }

  @override
  _SearchHistoryTagWidgetState createState() => _SearchHistoryTagWidgetState();
}

class _SearchHistoryTagWidgetState extends State<SearchHistoryTagWidget> {
  ///文本标签集合
  List<String> _tagList = [];

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

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

  /// 点击历史标签
  void _historyTagClick(String tag) {
    if (!EmptyUtil.isEmpty(tag)) {
      Navigator.push(context, MaterialPageRoute(builder: (_) => SearchResultPage({'keywords': tag ?? ''})));
    }
  }

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

  /// 添加搜索
  // 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);
  //   }
  //   setState(() {});
  // }

  /// 点击清除所有历史记录
  void _clearTag() async {
    await Provider.of<SearchTagNotifier>(context, listen: false).clear();
    setState(() {

    });
  }

  @override
  void initState() {
    _initHistoryTag();
    super.initState();
  }

  _initHistoryTag() async {
    _tagList = await Provider.of<SearchTagNotifier>(context, listen: false).getHistoryTag();
    setState(() {
    });
  }

  @override
  void didChangeDependencies() {
    _initHistoryTag();
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(left: 12.5, right: 12.5, top: 15),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          /// 标题
          SearchTitleWidget(
              titleText: widget?.model?.history_tilte ?? '历史搜索',
              titleTextColor: widget?.model?.history_bg_color ?? '#333333',
              iconUrl: widget?.model?.clear_history_icon ?? '',
              callback: () => _clearTag()),
          const SizedBox(
            height: 10,
          ),

          /// 历史标签
          _getHistoryWarp(),
        ],
      ),
    );
  }

  /// 历史搜索的标签
  Widget _getHistoryWarp() {
    List<Widget> itemWidgetList = [];
    final int tagListLength = _tagList?.length ?? 0;
    if (tagListLength > 0) {
      for (var i = 0; i < _tagList.length; i++) {
        var str = _tagList[i];
        itemWidgetList.add(GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => _historyTagClick(_tagList[i]),
          child: TextTagWidget(
            "$str",
            padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 10),
            margin: const EdgeInsets.only(right: 5, bottom: 0, top: 0),
            borderColor: HexColor.fromHex('#EDEDED'),
            backgroundColor: Colors.white,
            textStyle: TextStyle(
              color: HexColor.fromHex('#383838'),
              fontSize: 12.5,
            ),
          ),
        ));
      }

      return Wrap(
          spacing: 8.0,
          runSpacing: 8.0,

          ///子标签
          children: itemWidgetList);
    }
    return Container();
  }
}
