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/widget/loading.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

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

import 'chat/chat_home.dart';
import 'confirm_registration.dart';

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

class PatientTalkList extends StatelessWidget {
  DateTime now = DateTime.now();
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late 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: {
          HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
          'token': '${Global.token}',
        });
    print(url);
    print(Global.token);
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      ChatList mChatList = new ChatList.fromJson(jsonResponse);
      if (mChatList.code == Global.responseSuccessCode) {
      } else {
        Component.toast(mChatList.msg.toString(), 0);
      }
      return mChatList;
    } 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,
          leading: new 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: 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: Container(
                          height: 55,
                          child: Image.network(
                            "${Global.ImageUrl}${data!.data?[index].avatar}",
                            width: 55,
                            fit: BoxFit.cover,
                            excludeFromSemantics: true,
                            errorBuilder: (context, error, stackTrace) => Icon(
                              Icons.person_pin,
                              size: 55,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                        title: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '${data!.data?[index].nickName} ${data!.data?[index].remark}',
                                textAlign: TextAlign.center,
                                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: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('您有什么问题，可以留言，我将第一时间回复。 '),
                            ]),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => ChatHome(data!.data![index].userId.toString())),
                          );
                        },
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                return ColorLoader();
              },
            ),
          ),
        ]),
      ),
    );
  }
}
