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

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

import 'add_patient.dart';
import 'bean/user_list.dart';
import 'chat/chat_home.dart';
import 'online_consultation.dart';

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

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

class SelectPatientState extends State<SelectPatient> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<UserListEntity?> _future;
  late BuildContext cxt;

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

  Future<UserListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final response = await http
        .get(Uri.parse('${Global.BaseUrl}user/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);
      UserListEntity mUserListEntity =
          new UserListEntity.fromJson(jsonResponse);
      if (mUserListEntity.code == Global.responseSuccessCode) {
      } else {
        Component.toast("服务器错误提示：" + mUserListEntity.msg.toString(), 0);
        return null;
      }
      return mUserListEntity;
    } 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<UserListEntity?>(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                UserListEntity? data = snapshot.data;
                return Expanded(
                    // wrap in Expanded
                    child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: data?.data?.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                          Row(
                          children: [
                            Text(
                              data!.data == null ? "" : data!.data![index].patientName as String,
                              style: const TextStyle(fontSize: 18),
                            ),
                            SizedBox(width: 15),
                            // if (index == 0)
                              ElevatedButton(
                                child: Text(" ${data!.data == null ? "" : data!.data![index].userRelationship } ",
                                    style: TextStyle(
                                        color: Colors.indigo, fontSize: 13)),
                                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: () {},
                              ),]),
                            if (data!.data == null ? false : data!.data![index].isDefault == 1)
                              Text(
                                '默认就诊人',
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.grey),
                              ),
                          ]),
                      subtitle: Text('身份证-${data!.data == null ? "" : data!.data![index].identificationCard}'),
                      onTap: () {
                        Global.appointmentPersonId = data!.data![index].patientId!;
                        Global.patient = data;
                        Global.selectPatient = index;
                        if(mFrom == "fromDoctorDetail") {
                          Navigator.of(cxt).pop();
                        } else if(mFrom == "fromRecordRegistration") {
                          Navigator.pop(cxt, "success");
                        } else if(mFrom == "fromSelectDoctor") {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => OnlineConsultation()),
                          );
                        } else {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => Registration(userListEntity : data, whichPatient : index, key : new Key(""))),
                          );
                        }
                      },
                    );
                  },
                ));
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return CircularProgressIndicator();
            },
          ),
          ElevatedButton(
            child: Text("添加就诊人",
                style: TextStyle(color: Colors.white, fontSize: 15)),
            style: ButtonStyle(
              backgroundColor:
                  MaterialStateProperty.resolveWith<Color>((states) {
                return Colors.blue; // Regular color
              }),
              fixedSize: MaterialStateProperty.all<Size>(
                Size(MediaQuery.of(context).size.width - 32, 30), // 设置宽度和高度
              ),
            ),
            onPressed: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => AddPatient(userListEntity : new UserListEntity(), whichPatient : -1,  key: new Key(""),)),
              );
              setState(() {
                _future = fetchData();
              });
            },
          ),
        ]),
      ),
    );
  }

}
