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:http/http.dart' as http;

import 'bean/chat_list.dart';
import 'chat/chat_home.dart';

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

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

  Future<ChatList?> fetchData() async {
    String url = '${Global.BaseUrl}chat/getChatList?userId=${Global.userId}';
    final response =
        await http.get(Uri.parse(url), headers: jsonHeaders(withToken: true));
    logd(url);
    logd(Global.token);
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("患者聊天列表=$json");
      ChatList mChatList = ChatList.fromJson(json);
      if (mChatList.code == Global.responseSuccessCode) {
      } else {
        Component.toast(mChatList.msg.toString(), 0);
      }
      return mChatList;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('医生沟通列表',
            style: TextStyle(
              color: Colors.white,
            )),
        centerTitle: true,
        elevation: 0.5,
        backgroundColor: Global.StatusBarColor,
        leading: IconButton(
          tooltip: '返回上一页',
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.of(context).pop();
            //_nextPage(-1);
          },
        ),
      ),
      body: Column(children: [
        Expanded(
          child: FutureBuilder<ChatList?>(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                ChatList? 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(children: [
                        Expanded(
                            child: Text(
                          '${data.data?[index].nickName} ${data.data?[index].remark ?? ""}',
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                              fontSize: 13, color: Colors.black54),
                        )),
                        Text(
                          '${data!.data?[index].createTime}',
                          textAlign: TextAlign.center,
                          style:
                              const TextStyle(fontSize: 13, color: Colors.grey),
                        ),
                      ]),
                      subtitle: const Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('您有什么问题，可以留言，我将第一时间回复。 '),
                          ]),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ChatHome(
                                    doctorId:
                                        data.data![index].userId.toString(),
                                    doctorName: data.data![index].nickName,
                                  )),
                        );
                      },
                    );
                  },
                );
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return const ColorLoader();
            },
          ),
        ),
      ]),
    );
  }
}
