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

import 'package:eitc_erm_app/select_department.dart';
import 'package:eitc_erm_app/select_doctor.dart';
import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/utils/DateUtils.dart';
import 'package:eitc_erm_app/utils/Utils.dart';
import 'package:eitc_erm_app/widget/line.dart';
import 'package:eitc_erm_app/widget/loading.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'bean/chat_list.dart';
import 'bean/clinic_list.dart';
import 'bean/pda_patrol_time_list.dart';
import 'package:http/http.dart' as http;

import 'bean/synchronize_data.dart';
import 'bottom_navigation.dart';
import 'chat/chat_home.dart';
import 'confirm_registration.dart';
import 'doctor_talk_list.dart';
import 'login.dart';

/*void main() => runApp(DoctorTalkList());*/

class SelectClinic extends StatelessWidget {
  DateTime now = DateTime.now();
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<ClinicList?> _future = fetchData();
  String mFrom = "";
  SelectClinic(String from) {
    mFrom = from;
  }

  Future<ClinicList?> fetchData() async {
    String url = '${Global.BaseUrl}api/clinicList';
    final response = await http.get(Uri.parse(url), headers: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
    });
    print(url);
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      ClinicList mClinicList = new ClinicList.fromJson(jsonResponse);
      if (mClinicList.code == Global.responseSuccessCode) {
      } else {
        Component.toast(mClinicList.msg.toString(), 0);
      }
      return mClinicList;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  Future<SynchronizeData?> synchronizeData(BuildContext context) async {
    String url = '${Global.BaseUrl}api/synchronizeData?id=${Global.userId}&identificationCard=${Global.userIdentificationCard}&phoneNumber=${Global.loginPhoneNo}';
    final response = await http.get(Uri.parse(url), headers: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
    });
    print(url);
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      SynchronizeData mSynchronizeData = new SynchronizeData.fromJson(jsonResponse);
      if (mSynchronizeData.code == Global.responseSuccessCode) {
        Global.token = mSynchronizeData.data!.token.toString();
        Navigator.pushReplacementNamed(context, '/home');
      } else {
        Component.toast(mSynchronizeData.msg.toString(), 0);
      }
      return mSynchronizeData;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: new AppBar(
          title: new Text('请选择您需要挂号的医院/诊所',
              style: TextStyle(
                color: Colors.white,
              )),
          centerTitle: true,
          elevation: 0.5,
          backgroundColor: Global.StatusBarColor,
        ),
        body: Column(children: [
          Expanded(
            child: FutureBuilder<ClinicList?>(
              future: _future,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  ClinicList? data = snapshot.data;
                  return ListView.builder(
                    shrinkWrap: true,
                    itemCount: data?.data?.length,
                    itemBuilder: (context, index) {
                      return Center(
                          child: ListTile(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(5),
                                topRight: Radius.circular(5),
                                bottomRight: Radius.circular(5),
                                bottomLeft: Radius.circular(5))),
                        tileColor: Colors.white,
                        iconColor: Colors.white,
                        title: Text(
                          '${data!.data?[index].clinicName}',
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                              fontSize: 18, color: Colors.black),
                        ),
                        subtitle: Line(),
                        onTap: () async {
                          Global.clinic = data!.data![index].clinicName!;
                          if(mFrom == "fromHome") {
                            synchronizeData(context);
                          } else if (!(await Utils.readData("token")).isEmpty) {
                            Global.token = await Utils.readData("token");
                            Global.userId = await Utils.readData("userId");
                            print("2222 " + Global.userId);
                            Navigator.pushReplacementNamed(context, '/home');
                          } /*else if (!(await Utils.readData("doctorToken"))
                              .isEmpty) {
                            Global.token = await Utils.readData("doctorToken");
                            Navigator.pushReplacementNamed(context, '/doctor');
                          }*/ else
                            Navigator.pushReplacementNamed(context, '/login');
                        },
                      ));
                    },
                  );
                } else if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                return ColorLoader();
              },
            ),
          ),
        ]),
      ),
      routes: {
        '/login': (context) => Login(),
        '/home': (context) => BottomNavigationWidget(),
        '/doctor': (context) => DoctorTalkList(),
      },
    );
  }
}
