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/logger.dart';
import 'package:eitc_erm_app/widget/loading.dart';
import 'package:eitc_erm_app/widget/user_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

import 'bean/doctor_chat_list.dart';
import 'chat/chat_home_doctor.dart';

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

class DoctorTalkList extends StatelessWidget {
  DateTime now = DateTime.now();
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late final Future<DoctorChatList?> _future = fetchData();

  int lastExitTime = 0;

  Future<DoctorChatList?> fetchData() async {
    String url =
        '${Global.BaseUrl}chat/getChatPatientList?dockerId=${Global.user.data?.id}';
    final response = await http.get(Uri.parse(url), headers: jsonHeaders(withToken: true));
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("医生聊天列表=$json");
      DoctorChatList mDoctorChatList = new DoctorChatList.fromJson(json);
      if (mDoctorChatList.code == Global.responseSuccessCode) {
      } else {
        Component.toast(mDoctorChatList.msg.toString(), 0);
      }
      return mDoctorChatList;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: !Platform.isAndroid,
        onPopInvokedWithResult: _onPopInvoke,
        child: Scaffold(
          appBar: AppBar(
            title: const Text('患者沟通列表',
                style: TextStyle(
                  color: Colors.white,
                )),
            centerTitle: true,
            elevation: 0.5,
            backgroundColor: Global.StatusBarColor,
          ),
          body: Column(children: [
            Expanded(
              child: FutureBuilder<DoctorChatList?>(
                future: _future,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    DoctorChatList? data = snapshot.data;
                    return ListView.builder(
                      shrinkWrap: true,
                      itemCount: data?.data?.length,
                      itemBuilder: (context, index) {
                        return 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,
                          leading: UserHeader(
                            url:
                                "${Global.ImageUrl}${data!.data?[index].avatar}",
                          ),
                          title: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '与 ${data!.data?[index].phoneNumber} 的聊天记录',
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                      fontSize: 15, color: Colors.black),
                                ),
                                /*Text(
                                '${data!.data?[index].updateDate}',
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.grey),
                              ),*/
                              ]),
                          subtitle: Text(
                            '${data!.data?[index].updateDate}',
                            style: const TextStyle(
                                fontSize: 13, color: Colors.grey),
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ChatHomeDoctor(
                                      data.data![index].id.toString(),
                                      data.data![index].phoneNumber
                                          .toString())),
                            );
                          },
                        );
                      },
                    );
                  } else if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  }
                  return const ColorLoader();
                },
              ),
            ),
          ]),
        ));
  }

  void _onPopInvoke(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }
    int now = DateTime.now().millisecondsSinceEpoch;
    if (lastExitTime == 0 || now - lastExitTime > 2000) {
      Component.toast("再次点击退出应用", 2);
      lastExitTime = now;
      return;
    }
    SystemNavigator.pop(animated: true);
  }
}
