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

import 'package:eitc_erm_app/select_patient.dart';
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/material.dart';
import 'package:http/http.dart' as http;

import 'bean/doctor_list.dart';

String mFrom = "";
// void main() {
//   WidgetsFlutterBinding.ensureInitialized();
//   runApp(SelectPatient());
// }

class SelectDoctor extends StatefulWidget {
  SelectDoctor(String from) {
    mFrom = from;
  }
  @override
  State<StatefulWidget> createState() => SelectDoctorState();
}

class SelectDoctorState extends State<SelectDoctor> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<DoctorListEntity?> _future;
  late BuildContext cxt;

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

  Future<DoctorListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}doctor/list'), 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);
      DoctorListEntity mDoctorListEntity =
          new DoctorListEntity.fromJson(jsonResponse);
      if (mDoctorListEntity.code == Global.responseSuccessCode) {
        return mDoctorListEntity;
      } else {
        Component.toast(mDoctorListEntity.msg.toString(), 0);
      }
      return null;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    cxt = context;
    return MaterialApp(
      home: Scaffold(
        appBar: new AppBar(
          title: new Text('选择医生',
              style: TextStyle(
                color: Colors.white,
              )),
          centerTitle: true,
          elevation: 0.5,
          backgroundColor: Global.StatusBarColor,
          leading: new IconButton(
            tooltip: '返回上一页',
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.of(context).pop();
              //_nextPage(-1);
            },
          ),
        ),
        body: Column(children: [
          /*Text(
            '选择就诊人',
            style: const TextStyle(fontSize: 15),
            textAlign: TextAlign.start,
            overflow: TextOverflow.ellipsis,
          ),*/
          FutureBuilder<DoctorListEntity?>(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                DoctorListEntity? data = snapshot.data;
                return Expanded(
                    // wrap in Expanded
                    child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: data?.data?.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Padding(
                        padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
                        child: Row(children: [
                          Text(
                            data!.data![index].nickName as String,
                            style: const TextStyle(fontSize: 18),
                          ),
                          data!.data![index].nickName?.length == 2
                              ? SizedBox(width: 28.0)
                              : SizedBox(width: 10.0),
                         /* if (data!.data![index].doctorBlurb != null)
                            ElevatedButton(
                              child: Text(" ${data!.data![index].doctorBlurb} ",
                                  style: TextStyle(
                                      color: Colors.indigo, fontSize: 16)),
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.resolveWith<Color>(
                                        (states) {
                                  return Colors
                                      .lightBlueAccent; // Regular color
                                }),
                                // fixedSize: MaterialStateProperty.all<Size>(
                                //   Size(70, 15),
                                // ),
                                padding:
                                    MaterialStateProperty.all(EdgeInsets.zero),
                                minimumSize:
                                    MaterialStateProperty.all(Size.zero),
                              ),
                              onPressed: () {},
                            ),*/
                        ]),
                      ),
                      subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                                '${data!.data![index].deptName} - ${data!.data![index].postNames}\n'),
                            Divider(
                              height: 2, // 分割线的高度
                              color: Colors.black12, // 分割线的颜色
                              thickness: 1, // 可选，分割线的厚度
                            ),
                          ]),
                      onTap: () {
                        Global.doctor = data;
                        Global.selectDoctor = index;
                        /*if (mFrom == "fromDoctorDetail") {
                          Navigator.of(cxt).pop();
                        } else if (mFrom == "fromRecordRegistration") {
                          Navigator.pop(cxt, "success");
                        } else */{
                          // if(Global.selectPatient == -1)
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => SelectPatient("fromSelectDoctor")),
                            );
                          /*else
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ChatHome()),
                            );*/
                        }
                      },
                    );
                  },
                ));
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return ColorLoader();
            },
          ),
        ]),
      ),
    );
  }
}
