import 'package:flutter/material.dart';
import 'package:fun_selfie_app/utils/api.dart';

class SeachBarDelegate extends SearchDelegate<String> {
  String searchHint = '请输入搜索内容...';
  var suggestList = ['S2023062812', 'S202306243', 'S202307012', 'S202307051'];
  List searchList = [];

  @override
  String get searchFieldLabel => searchHint;
  //重写搜索框右上角方法
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            if (query.isEmpty) return;
            query = "";
            showSuggestions(context);
          })
    ];
  }

  //重写左上角方法
  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(
            icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
        onPressed: () {
          close(context, '');
        });
  }

  //重写键盘点击确认后方法
  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder(
        future: loadList(),
        builder: (context, AsyncSnapshot snapshot) {
          return ListView.builder(
              physics: const AlwaysScrollableScrollPhysics(),
              itemCount: searchList.isEmpty ? 1 : searchList.length,
              itemBuilder: (BuildContext context, int index) {
                if (searchList.isEmpty) return const Text('');
                Map obj = searchList[index];
                return ListTile(
                    title: Text(obj['saleOrderNo']),
                    subtitle: Text(obj['id']),
                    onTap: () {
                      Navigator.pushNamed(
                          context, "/newsDetail/".toString() + obj['id']);
                    });
              });
        });
  }

  //重写输入过程方法,在输入过程不断调用
  @override
  Widget buildSuggestions(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 16, right: 16),
      child: ListView(
        primary: false,
        shrinkWrap: true,
        children: <Widget>[
          const SizedBox(height: 10),
          const Text("推荐活动：", style: TextStyle(fontSize: 20)),
          const SizedBox(height: 10),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: suggestList.map((childNode) {
              return InkWell(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(3),
                  child: Container(
                    padding: const EdgeInsets.all(3),
                    color: Colors.grey,
                    child: Text(
                      childNode,
                      style: const TextStyle(
                          fontSize: 16,
                          color: Colors.white,
                          shadows: [
                            BoxShadow(
                                color: Colors.grey, offset: Offset(0.2, 0.2))
                          ]),
                    ),
                  ),
                ),
                onTap: () {
                  loadList();
                  Future.delayed(const Duration(seconds: 1), () async {
                    searchHint = '';
                    query = childNode;
                    showResults(context);
                  });
                },
              );
            }).toList(),
          )
        ],
      ),
    );
  }

  loadList() async {
    try {
      var params = {
        "pageNo": 1,
        "pageSize": 20,
        "status": 'READY',
        "saleOrderNo": query
      };
      var res = await UtilHelper.updateList(params);
      searchList = res['records'];
    } catch (err) {
      debugPrint(err.toString());
    }
  }
}
