import 'package:base/consts/color.dart';
import 'package:base/widgets/search/hotSug.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../view/hidedanger_manage/danger_search_result.dart';

class HiddenDangerSearchPage extends StatefulWidget {
  bool isHandle;
  HiddenDangerSearchPage(this.isHandle);

  @override
  State<StatefulWidget> createState() => _HiddenDangerSearchPage();
}

class _HiddenDangerSearchPage extends State<HiddenDangerSearchPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  List<String> hotWords = [];
  List<_SearchKey> searchKeyCount = [];
  List<String> orderKeyword = [];
  bool _isNotSearching = true;
  String theme = 'blue';

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(240, 243, 245, 1),
      appBar: AppBar(
        elevation: 0.2,
        brightness: Brightness.light,
        title: Container(
            height: 30,
            padding: const EdgeInsets.only(bottom: 5),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: const BorderRadius.all(Radius.circular(25.0)),
            ),
            child: Row(
              children: <Widget>[
                Padding(
                    padding: const EdgeInsets.only(right: 4.0, left: 10.0, top: 5),
                    child: Icon(
                      Icons.search,
                      size: 20,
                      color: Theme.of(context).primaryColor,
                    )),
                Container(
                  width: MediaQuery.of(context).size.width - 160,
                  child: TextField(
                    textInputAction: TextInputAction.search,
                    controller: _controller,
                    autofocus: true,
                    focusNode: _focusNode,
                    style: const TextStyle(fontSize: 14.0, color: Color(0xFF999999)),
                    onSubmitted: (value) {
                      search(_controller.text);
                    },
                    decoration: InputDecoration(
                        suffixIcon: GestureDetector(
                          onTap: () {
                            _controller.text = '';
                            setState(() {
                              _isNotSearching = true;
                            });
                          },
                        ),
                        border: InputBorder.none,
                        hintText: '请输入搜索内容',
                        contentPadding: const EdgeInsets.only(top: -8)),
                    onChanged: (val) {},
                  ),
                )
              ],
            )),
        actions: <Widget>[
          Align(
              child: Padding(
            padding: const EdgeInsets.only(right: 10),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  search(_controller.text);
                });
              },
              child: const Text(
                '搜索',
                style: TextStyle(color: Colors.white, fontSize: 14.0, fontWeight: FontWeight.w500),
              ),
            ),
          ))
        ],
      ),
      body: ListView(
        children: <Widget>[
          Offstage(
              offstage: !_isNotSearching,
              child: Container(
                color: Colors.white,
                child: HotSugWidget(
                    title: '搜索历史',
                    hotWords: hotWords,
                    searchData: searchByHistory,
                    deleteBtnClick: deleteSearchHistory,
                    theme: theme),
              )),
        ],
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  @override
  void initState() {
    super.initState();
    initData();
    initConfig();
  }

  Future<void> initData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      List<String> data = prefs.getStringList('hotWordsHistory');
      if (data != null && data.isNotEmpty) {
        hotWords = data;
      } else {
        hotWords = [];
      }
    });
  }

  Future<void> search(keyword) async {
    if (keyword != null && keyword.isNotEmpty) {
      // 添加搜索历史
      if (hotWords.contains(keyword)) {
      } else {
        setState(() {
          hotWords.add(keyword);
        });
        final prefs = await SharedPreferences.getInstance();
        prefs.setStringList('hotWordsHistory', hotWords);
      }
      // 页面跳转，查询并显示结果
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return HiddenSearchSearchResultPage(keyword, widget.isHandle);
      }));
    }
  }

  void searchByHistory(String text) {
    // 页面跳转，查询并显示结果
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return HiddenSearchSearchResultPage(text, widget.isHandle);
    }));
  }

  Future<void> deleteSearchHistory() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove('hotWordsHistory');
    initData();
  }
}

class _SearchKey {
  String keyword;
  int count;
  _SearchKey();
  _SearchKey.fromJson(jsonRes) {
    keyword = jsonRes['keyword'];
    count = jsonRes['count'];
  }

  @override
  String toString() {
    return '{"keyword":"$keyword","count": $count}';
  }
}
