import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/widget/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'bean/department.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(SelectDepartment());
}

class SelectDepartment extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SelectDepartmentState();
}

class SelectDepartmentState extends State<SelectDepartment> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<Department?> _future;
  TextEditingController mController = TextEditingController();
  String searchDeptName = "";

  @override
  void initState() {
    super.initState();
    _future = fetchData();
  }

  Future<Department?> fetchData() async {
    print(Global.token);
    final response = await http.get(
        Uri.parse('${Global.BaseUrl}sys-dept/list?deptName=' + searchDeptName),
        headers: {
          HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
          'token': '${Global.token}',
        });
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      Department mDepartment = new Department.fromJson(jsonResponse);
      return mDepartment;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return /*WillPopScope(
      // 使用 onWillPop 回调来决定是否允许退出
        onWillPop: () async {
          return false;
        },
        child: */Scaffold(
            appBar: new AppBar(title: new Text(' '), centerTitle: true),
            body: Container(
                  padding: EdgeInsets.all(20),
                  child: SingleChildScrollView(
                      child: Column(
                          crossAxisAlignment:
                              CrossAxisAlignment.center, //纵向对齐方式
                          children: <Widget>[
                        Padding(
                          padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
                          child: SearchBar(
                              hintText: "请输入科室",
                              leading: Icon(Icons.earbuds),
                              controller: mController,
                              trailing: [
                                Icon(Icons.mic),
                                GestureDetector(
                                    child: Icon(Icons.search_rounded),
                                    onTap: () {
                                      setState(() {
                                        searchDeptName = mController.text;
                                        _future = fetchData();
                                      });
                                    }),
                              ]),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
                          child: Row(children: [
                            Expanded(
                              child: FutureBuilder<Department?>(
                                future: _future,
                                builder: (context, snapshot) {
                                  if (snapshot.hasData) {
                                    Department? data = snapshot.data;
                                    return ListView.builder(
                                      shrinkWrap: true,
                                      itemCount: data?.data?.length,
                                      itemBuilder: (context, index) {
                                        return ListTile(
                                          title: Text(
                                              '${data!.data?[index].deptName}'),
                                          onTap: () {
                                            Navigator.pop(context, data!.data?[index].deptName);
                                            // Navigator.push(
                                            //   context,
                                            //   MaterialPageRoute(builder: (context) => NfcDetail()),
                                            // );
                                          },
                                        );
                                      },
                                    );
                                  } else if (snapshot.hasError) {
                                    return Text('Error: ${snapshot.error}');
                                  }
                                  return ColorLoader();
                                },
                              ),
                            ),
                          ]),
                        )
                      ])),
                ));
  }
}
