import 'dart:io';

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

import 'bean/clinic_list.dart';
import 'bean/synchronize_data.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: jsonHeaders());
    logd(url);
    if (response.statusCode == 200) {
      ClinicList mClinicList =
          ClinicList.fromJson(decodeBodyToJson(response.bodyBytes));
      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: jsonHeaders());
    logd(url);
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("同步数据结果=$json");
      SynchronizeData mSynchronizeData = SynchronizeData.fromJson(json);
      if (mSynchronizeData.code == Global.responseSuccessCode) {
        Global.token = mSynchronizeData.data!.token.toString();
        await Utils.saveData("token", Global.token);
        Navigator.pushReplacementNamed(context, '/home');
      } else {
        Component.toast(mSynchronizeData.msg.toString(), 0);
      }
      return mSynchronizeData;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return 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: const 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!;
                        Global.RootUrl = data.data![index].clinicIp!;
                        Global.Port = data.data![index].serverPost!;
                        Global.ChatPort = data.data![index].webSocketPost!;

                        //诊所ID
                        String clinicId = await Utils.readData("clinicId");
                        Utils.saveData("clinicId", data.data![index].id!);
                        String token = await Utils.readData("token");
                        if (mFrom == "fromHome") {
                          synchronizeData(context);
                        } else if (token.isNotEmpty) {
                          Global.token = token;
                          Global.userId = await Utils.readData("userId");
                          //ID与保存的ID不同就同步数据
                          if (clinicId != data.data![index].id!) {
                            Global.userIdentificationCard =
                                await Utils.readData("userIdentificationCard");
                            Global.loginPhoneNo =
                                await Utils.readData("loginPhoneNo");
                            //保存的身份证和手机号为空跳转到登录
                            if (Global.userIdentificationCard.isEmpty ||
                                Global.loginPhoneNo.isEmpty) {
                              Navigator.pushReplacementNamed(context, '/login');
                              return;
                            }
                            synchronizeData(context);
                            return;
                          }
                          logd("2222 " + Global.userId);
                          Navigator.pushReplacementNamed(context, '/home');
                        }
                        //医生没有同步数据的逻辑,所以不保存token每次都登录
                        /*else if ((await Utils.readData("doctorToken"))
                            .isNotEmpty) {
                          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 const ColorLoader();
            },
          ),
        ),
      ]),
    );
  }
}
