import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jcs_airport/services/api.dart';
import '../../../consts/colors.dart';
import '../../../utils/GetConfig.dart';
import './hotSug.dart';

class HazardousChemicalsSearchPage extends StatefulWidget {
  const HazardousChemicalsSearchPage();

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

class _HazardousChemicalsSearchPage extends State<HazardousChemicalsSearchPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  List<String> hotWords = [];
  List<_SearchKey> searchKeyCount = [];
  List<String> orderKeyword = [];

  final bool _isNotSearching = true;

  String theme = 'blue';

  BuildContext me;

  // 当前页码
  int pageIndex = 1;

  // 是否有下一页
  bool hasNext = false;

  // 分页所需控件
  bool isAnimating = false;

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

  @override
  Widget build(BuildContext context) {
    me = context;
    return Scaffold(
        backgroundColor: const Color.fromRGBO(240, 243, 245, 1),
        appBar: AppBar(
            elevation: 0.2,
            brightness: Brightness.light,
            backgroundColor: const Color(0xFFFFFFFF),
            leading: Container(
              child: GestureDetector(
                  onTap: () {
                    _focusNode.unfocus();
                    Navigator.pop(context);
                  },
                  child: Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32)),
            ),
            title: Container(
              height: 38,
              padding: const EdgeInsets.symmetric(horizontal: 18),
              decoration: BoxDecoration(color: Colors.grey.shade100, borderRadius: const BorderRadius.all(Radius.circular(45))),
              child: Center(
                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: const InputDecoration(
                      hintText: '请输入搜索内容', border: InputBorder.none, contentPadding: EdgeInsets.only(bottom: 10)),
                  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: Color(0xFF999999), fontSize: 14.0, fontWeight: FontWeight.w500)))))
            ]),
        body: ListView(children: <Widget>[
          Offstage(
              offstage: !_isNotSearching,
              child: Container(
                  color: Colors.white,
                  child: HotSugWidget(title: '搜索历史', hotWords: hotWords, deleteBtnClick: deleteSearchHistory, theme: theme)))
        ]),
        resizeToAvoidBottomPadding: false);
  }

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

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

  dynamic search(String 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);
      }
      Get.back(result: keyword);
      // 页面跳转，查询并显示结果
      //_searchData(keyword);
    }
  }

  dynamic searchByHistory(String text) {
    // 页面跳转，查询并显示结果
    search(text);
  }

  dynamic deleteSearchHistory() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove('hotWordsHistory');
    initData();
  }

/*dynamic _searchData(keyword) {
    setState(() {
      pageIndex = 1;
    });
    _loadMore(keyword);
  }*/

/* Future<void> _loadMore(keyword) async {
    Map<String, dynamic> query = {'pageNum': pageIndex, 'pageSize': 20};
    query['name'] = keyword;
    setState(() {
      isAnimating = true;
    });
    var data = await API.getHazardousChemicals(query);
    setState(() {
      isAnimating = false;
      List hazardousList = [];
      if (data != null && data['records'].length > 0) {
        for (dynamic p in data['records']) {
          hazardousList.add(p);
        }
      }
      widget.callback(hazardousList);
      if (data['current'] == data['pages']) {
        hasNext = false;
      }
      Navigator.pop(me);
    });
  }*/
}

class _SearchKey {
  String keyword;
  int count;

  _SearchKey();

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