import 'package:flutter/material.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/styles.dart';

///@Description     基础选择页面
///@author          helinlin
///@create          2021-09-03 15:32
abstract class BaseChoose extends StatefulWidget {
  Map person; //单选回显
  List persons; //多选回显
  bool multi; //是否多选

  BaseChoose({this.person, this.persons, this.multi = false});

  @override
  BaseChooseState createState() => getBaseChoosePersonState();

  BaseChooseState getBaseChoosePersonState();
}

abstract class BaseChooseState extends State<BaseChoose> {
  final List persons = [];
  final List _personsSearch = [];
  bool _isSearch = false;
  final Widget _divider = const Divider(
    color: Colors.grey,
  );
  SearchBar _searchBar;
  String _idKey;
  String _nameKey;

  @override
  void initState() {
    super.initState();
    _idKey = getIdKey();
    _nameKey = getNameKey();
    getData();
  }

  BaseChooseState() {
    _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[_nameKey].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,
      appBar: _searchBar.build(context),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        child: Column(
          children: [
            Expanded(
              child: ListView.separated(
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) {
                    return InkWell(
                      onTap: () {
                        setState(() {
                          var person = _isSearch ? _personsSearch[index] : persons[index];
                          if (widget.multi ?? false) {
                            int index = -1;
                            widget.persons.asMap().forEach((key, value) {
                              if (person[_idKey] == value[_idKey]) {
                                index = key;
                              }
                            });
                            if (index >= 0) {
                              widget.persons.removeAt(index);
                            } else {
                              widget.persons.add(person);
                            }
                          } else {
                            widget.person = person;
                          }
                        });
                      },
                      child: Row(
                        children: [
                          Checkbox(
                              activeColor: Theme.of(context).primaryColor,
                              value: isChoose(index),
                              onChanged: (value) {
                                setState(() {
                                  var person = _isSearch ? _personsSearch[index] : persons[index];
                                  if (widget.multi ?? false) {
                                    int index = -1;
                                    widget.persons.asMap().forEach((key, value) {
                                      if (person[_idKey] == value[_idKey]) {
                                        index = key;
                                      }
                                    });
                                    if (index >= 0) {
                                      widget.persons.removeAt(index);
                                    } else {
                                      widget.persons.add(person);
                                    }
                                  } else {
                                    widget.person = person;
                                  }
                                });
                              }),
                          Expanded(
                              child: ListTile(
                                  title: Text(
                            (_isSearch ? _personsSearch[index][_nameKey] : persons[index][_nameKey]) ?? '',
                            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: widget.person);
                      },
                      child: const Text(
                        '确定',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  bool isChoose(int index) {
    if (widget.multi ?? false) {
      bool isChoose = false;
      widget.persons.forEach((element) {
        if (element[_idKey] == (_isSearch ? _personsSearch[index][_idKey] : persons[index][_idKey])) {
          isChoose = true;
        }
      });
      return isChoose;
    } else {
      return widget.person[_idKey] == (_isSearch ? _personsSearch[index][_idKey] : persons[index][_idKey]);
    }
  }

  ///获取人员数据
  Future<void> getData();

  ///人员id
  String getIdKey();

  ///人员姓名
  String getNameKey();
}
