import 'package:flutter/material.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:get/get.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';

///选择维保执行人员
class ChooseMaintenancePerson extends StatefulWidget {
  final Map person;

  const ChooseMaintenancePerson({this.person});

  @override
  _ChooseMaintenancePersonState createState() => _ChooseMaintenancePersonState(person: person ?? {});
}

class _ChooseMaintenancePersonState extends State<ChooseMaintenancePerson> {
  final List _persons = [];
  final List _personsSearch = [];
  bool _isSearch = false;
  Map person = {};
  SearchBar _searchBar;
  Widget divider = const Divider(
    color: Colors.blue,
  );
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

  _ChooseMaintenancePersonState({this.person}) {
    _searchBar = SearchBar(
        hintText: '请输入关键字',
        inBar: false,
        buildDefaultAppBar: (BuildContext context) {
          return AppBar(title: const Text('请选择'), actions: [_searchBar.getSearchAction(context)]);
        },
        setState: setState,
        onChanged: (value) {
          setState(() {
            _isSearch = true;
            _personsSearch.clear();
            _persons.forEach((element) {
              if (element['name'].contains(value)) {
                _personsSearch.add(element);
              }
            });
          });
        },
        onSubmitted: (String value) {},
        onCleared: () {
          setState(() {
            _isSearch = false;
            _personsSearch.clear();
          });
        },
        onClosed: () {
          setState(() {
            if (_isSearch == true && _personsSearch.isEmpty) {
              _isSearch = false;
            }
          });
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      key: _scaffoldKey,
      appBar: _searchBar.build(context),
      body: Column(
        children: [
          Expanded(
            child: ListView.separated(
                shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    onTap: () {
                      setState(() {
                        person = _isSearch ? _personsSearch[index] : _persons[index];
                      });
                    },
                    child: Row(
                      children: [
                        Checkbox(
                            value: person['sequenceNbr'] ==
                                (_isSearch ? _personsSearch[index]['sequenceNbr'] : _persons[index]['sequenceNbr']),
                            onChanged: (value) {
                              setState(() {
                                person = _isSearch ? _personsSearch[index] : _persons[index];
                              });
                            }),
                        Expanded(
                            child: ListTile(
                                title: Text(
                          _isSearch ? _personsSearch[index]['name'] : _persons[index]['name'],
                          style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                        ))),
                      ],
                    ),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return divider;
                },
                itemCount: _isSearch ? _personsSearch.length : _persons.length),
          ),
          Container(
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(
                  child: FlatButton(
                    color:Theme.of(context).primaryColor,
                    height: 40,
                    onPressed: () {
                      Get.back(result: person);
                    },
                    child: const Text(
                      '确定',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Future<void> initData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var userInfo = await API.maintenanceUser();
      Get.back();
      if (userInfo != null) {
        setState(() {
          _persons.addAll(userInfo);
        });
      }
    });
  }
}
