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

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../bean/normal_response2.dart';
import '../image_view.dart';
import '../online_consultation_detail.dart';
import '../utils/Component.dart';
import '../utils/Constants.dart';
import 'chat_disease.dart';
import 'chat_scroll_behavior.dart';
import 'chat_scroll_physics.dart';
import 'socket_core.dart';
import 'package:http/http.dart' as http;

/*void main() {
  runApp(ChatHome());
}*/
String mDoctorId = "";
class ChatHome extends StatefulWidget {
  ChatHome(String doctorId) {
    mDoctorId = doctorId;
  }
  @override
  ChatHomeState createState() => ChatHomeState();
}

class ChatHomeState extends State<ChatHome> {
  bool _isLoading = false;
  List<Map<String, dynamic>> _chatRecords = [
    /*{
      "host": true,
      "name": "你",
      "content": "问诊人：刘娟\n问诊资料：之前做过根管，最近有点疼不知道是哪里的问题"
    },*/
  ];

  final ScrollController _scrollController = ScrollController();
  final TextEditingController _textEditingController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  WebSocketUtility socket = new WebSocketUtility();
  String? userId = Global.userId;
  String? doctorId = Global.doctor.data?[Global.selectDoctor].userId.toString();
  bool sendEnable = true;
  late Future<ChatDisease?> _future;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(scrollListener);
    _focusNode.addListener(textFocusListener);
    if(!mDoctorId.isEmpty) {
      doctorId = mDoctorId;
    }

    socket.initWebSocket(onOpen: () {
      socket.sendMessage(
          "[LOGIN][${DateTime.now().millisecondsSinceEpoch}][${userId}][${doctorId}][2]");
      // socket.initHeartBeat();
    }, onMessage: (data) {
      if (data.toString().contains("SYSTEM")) {
        if (data.toString().contains("已上线")) {
          Component.toast("已连线", 2);
          sendEnable = true;
        } /*else {
          Component.toast("连线失败，请稍后重试！", 0);
          sendEnable = false;
        }*/
      } else {
        if (!data.toString().contains("[" +userId.toString() + "]["+doctorId.toString() + "]")) {
          if (data.toString().contains("[image]")) {
            _chatRecords.insert(0, {
              "host": false,
              "name": Global.doctor.data?[Global.selectDoctor].nickName,
              "content": data.toString().split("[image]")[1].trim(),
              "type": 1
            });
          } else {
            _chatRecords.insert(0, {
              "host": false,
              "name": Global.doctor.data?[Global.selectDoctor].nickName,
              "content": data
                  .toString()
                  .split("-")[1]
                  .trim()
                  .replaceAll("<br/>", "\n"),
              "type": 0
            });
          }
        } else {
          if (data.toString().contains("[image]")) {
            _chatRecords.insert(0, {
              "host": true,
              "name": Global.doctor.data?[Global.selectDoctor].nickName,
              "content": data.toString().split("[image]")[1].trim(),
              "type": 1
            });
          } else if (data.toString().contains("[patient]")) {
            _chatRecords.insert(0, {
              "host": true,
              "name": Global.doctor.data?[Global.selectDoctor].nickName,
              "content": data.toString().split("[patient]")[1].trim(),
              "type": 2
            });
          } else {
            _chatRecords.insert(0, {
              "host": true,
              "name": Global.doctor.data?[Global.selectDoctor].nickName,
              "content": data
                  .toString()
                  .split("-")[1]
                  .trim()
                  .replaceAll("<br/>", "\n"),
              "type": 0
            });
          }
        }
      }

      print(data);

      setState(() {});
    }, onError: (e) {
      print(e);
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (_scrollController.position.maxScrollExtent == 0) {
        // not scroll content, call load more
        if (_isLoading) return;
        _isLoading = true;
        onLoadMore();
      }
    });
  }

  @override
  void dispose() {
    print("结束聊天...");
    socket.sendMessage(
        "[LOGOUT][${DateTime.now().millisecondsSinceEpoch}][${userId}][${doctorId}][2]");
    socket.closeSocket();
    super.dispose();
  }

  @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,
        leading: new IconButton(
          tooltip: '返回上一页',
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      backgroundColor: Global.BackgroundColor,
      body: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(3),
            color: Colors.yellow, // 设置背景颜色为蓝色
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text(
                    Global.patient.data![Global.selectPatient].patientName
                            .toString() +
                        "的病历",
                    style: const TextStyle(fontSize: 16, color: Colors.black),
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => OnlineConsultationDetail("")),
                      );
                    },
                    child: Text(
                      " 点击查看详情 ",
                      style: const TextStyle(
                          backgroundColor: Colors.cyan,
                          fontSize: 14,
                          color: Colors.white),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      onSendMessage(
                          2,
                          "[patient]" +
                              Global
                                  .patient.data![Global.selectPatient].patientId
                                  .toString());
                    },
                    child: Text(
                      " 发送 ",
                      style: const TextStyle(
                          backgroundColor: Colors.redAccent,
                          fontSize: 14,
                          color: Colors.white),
                    ),
                  ),
                ]),
          ),
          Expanded(
            child: ScrollConfiguration(
              behavior: ChatScrollBehavior(),
              child: ListView.builder(
                padding: EdgeInsets.only(bottom: 10),
                itemBuilder: (ctx, index) {
                  return index == _chatRecords.length
                      ? Center(
                          child: SizedBox(
                            height: 0,
                            width: 0,
                            child: CircularProgressIndicator(
                              strokeWidth: 0,
                            ),
                          ),
                        )
                      : chatItemWidget(index);
                },
                controller: _scrollController,
                physics:
                    ChatScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
                reverse: true,
                itemCount: _chatRecords.length + 1,
              ),
            ),
          ),
          editMessageWidget(),
        ],
      ),
      /*floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 处理点击事件
          print('FloatingActionButton was pressed.');
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),*/
    );
  }

  Widget chatItemWidget(int index) {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 10,
        ),
        _chatRecords[index]['host']
            ? Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    width: 10,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Text(
                        "你",
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 12,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Color(0xFF8EBC48),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        alignment: Alignment.centerRight,
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: 220,
                          ),
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                if (_chatRecords[index]['type'] == 0)
                                  Text(_chatRecords[index]['content'],
                                      maxLines: 30,
                                      style: TextStyle(
                                        color: Colors.black,
                                      )),
                                if (_chatRecords[index]['type'] == 1)
                                  GestureDetector(
                                    onTap: () async {
                                      print(_chatRecords[index]['content']
                                          .toString());
                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) =>
                                                ImagePreviewPage(
                                                    _chatRecords[index]
                                                            ['content']
                                                        .toString()
                                                        .replaceAll(
                                                            "[image]", "")),
                                          ));
                                    },
                                    child: CachedNetworkImage(
                                      imageUrl: _chatRecords[index]['content']
                                          .toString()
                                          .replaceAll("[image]", ""),
                                      width: 80,
                                      fit: BoxFit.fitWidth,
                                      /*loadingBuilder: (context, child, loadingProgress) {
                                        if (loadingProgress == null) return child;
                                        return Center(
                                          child: CircularProgressIndicator(
                                            value: loadingProgress.expectedTotalBytes != null
                                                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                                                : null,
                                          ),
                                        );
                                      },*/
                                      placeholder: (context, url) => CircularProgressIndicator(),
                                      errorWidget:
                                          (context, error, stackTrace) {
                                        return const CircularProgressIndicator(); // 显示一个进度指示器作为错误占位
                                      },
                                    ),
                                  ),
                                if (_chatRecords[index]['type'] == 2)
                                  InkWell(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                OnlineConsultationDetail("")),
                                      );
                                    },
                                    child: Text(
                                        Global
                                                .patient
                                                .data![Global.selectPatient]
                                                .patientName
                                                .toString() +
                                            "的病历\n【点击查看详情】",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          color: Colors.blue,
                                        )),
                                  ),
                                /*if (index == _chatRecords.length - 1)
                                  InkWell(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) => OnlineConsultationDetail()),
                                      );
                                    },
                                    child: Text('【点击查看详情】',
                                        style: TextStyle(
                                          color: Colors.blue,
                                        )),
                                  )*/
                              ]),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _chatRecords[index]['host']
                          ? Colors.green
                          : Colors.blue,
                    ),
                    width: 40,
                    height: 40,
                    alignment: Alignment.center,
                    child: Text(
                      "你",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                ],
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    width: 10,
                  ),
                  Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.blue,
                    ),
                    width: 40,
                    height: 40,
                    alignment: Alignment.center,
                    child: Text(
                      _chatRecords[index]['name'] == null ? "医生" : _chatRecords[index]['name'],
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        _chatRecords[index]['name'] == null ? "" : _chatRecords[index]['name'],
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 12,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        alignment: Alignment.centerRight,
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: 220,
                          ),
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                if (_chatRecords[index]['type'] == 0)
                                  Text(_chatRecords[index]['content'],
                                      maxLines: 30,
                                      style: TextStyle(
                                        color: Colors.black,
                                      )),
                                if (_chatRecords[index]['type'] == 1)
                                  GestureDetector(
                                    onTap: () async {
                                      print(_chatRecords[index]['content']
                                          .toString());
                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) =>
                                                ImagePreviewPage(
                                                    _chatRecords[index]
                                                            ['content']
                                                        .toString()
                                                        .replaceAll(
                                                            "[image]", "")),
                                          ));
                                    },
                                    child: CachedNetworkImage(
                                      imageUrl: _chatRecords[index]['content']
                                          .toString()
                                          .replaceAll("[image]", ""),
                                      width: 80,
                                      fit: BoxFit.fitWidth,
                                      /*loadingBuilder: (context, child, loadingProgress) {
                                        if (loadingProgress == null) return child;
                                        return Center(
                                          child: CircularProgressIndicator(
                                            value: loadingProgress.expectedTotalBytes != null
                                                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                                                : null,
                                          ),
                                        );
                                      },*/
                                      placeholder: (context, url) => CircularProgressIndicator(),
                                      errorWidget:
                                          (context, error, stackTrace) {
                                        return const CircularProgressIndicator(); // 显示一个进度指示器作为错误占位
                                      },
                                    ),
                                  ),
                                /*if (index == _chatRecords.length - 1)
                                  InkWell(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) => OnlineConsultationDetail()),
                                      );
                                    },
                                    child: Text('【点击查看详情】',
                                        style: TextStyle(
                                          color: Colors.blue,
                                        )),
                                  )*/
                              ]),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    width: 10,
                  ),
                ],
              ),
      ],
    );
  }

  Widget editMessageWidget() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 6, horizontal: 20),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              enabled: sendEnable,
              focusNode: _focusNode,
              controller: _textEditingController,
              minLines: 1,
              maxLines: 100,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                contentPadding:
                    EdgeInsets.symmetric(vertical: 0, horizontal: 5),
              ),
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Material(
            color: Colors.green,
            borderRadius: BorderRadius.circular(5),
            child: InkWell(
              onTap: () {
                onSendMessage(0, "");
              },
              child: Container(
                  height: 30,
                  width: 50,
                  alignment: Alignment.center,
                  child: Text(
                    "发送",
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  )),
            ),
          ),
          SizedBox(
            width: 5,
          ),
          GestureDetector(
            onTap: () async {
              String uploadImg = await uploadFile();
              if (uploadImg != "") {
                onSendMessage(1, uploadImg.toString());
              }
              uploadImg = "";
            },
            child: Icon(
              Icons.add_circle_outline_outlined,
              color: Colors.black,
              size: 30,
            ),
          ),
        ],
      ),
    );
  }

  Future<String> uploadFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      String fileName = result.files.single.name;
      String? filePath = result.files.single.path;
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(filePath!, filename: fileName),
        "path": "chat",
      });

      try {
        Map<String, String> headers = {
          'token': '${Global.token}',
        };
        Response response = await Dio().post(
            Global.BaseUrl + 'common/minioUploadImage',
            data: formData,
            options: Options(headers: headers));
        print(response.data);
        if (response.statusCode == 200) {
          Normal2Response mNormal2Response =
              new Normal2Response.fromJson(response.data);
          if (mNormal2Response.code == Global.responseSuccessCode) {
            // Component.toast("上传成功！", 2);
            return mNormal2Response.msg.toString();
          } else {
            Component.toast(mNormal2Response.msg.toString(), 0);
            return "";
          }
        } else {
          Component.toast("出错了，请稍后再试！", 0);
          return "";
        }
      } catch (e) {
        print(e);
        return "";
      }
    }

    return "";
  }

  void scrollListener() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent) {
      if (_isLoading) return;
      _isLoading = true;
      onLoadMore();
    }
  }

  void textFocusListener() {
    _scrollController.animateTo(0.0,
        duration: Duration(milliseconds: 200), curve: Curves.easeInOut);
  }

  void onLoadMore() async {
    // 模拟请求接口
    await Future.delayed(Duration(seconds: 1));
    // for (int i = 0; i < 10; i++) {
    //   _chatRecords.addAll([
    //     {
    //       "host": i % 2 == 0 ? false : true,
    //       "name": i % 2 == 0 ? "大夫" : "你",
    //       "content": i % 2 == 0 ? "hello" : "hi"
    //     },
    //   ]);
    // }
    _isLoading = false;
    setState(() {});
  }

  void onSendMessage(int msgType, String info) async {
    String socketMsg = "";
    switch (msgType) {
      case 0:
        // 文字
        if (_textEditingController.text.trim().length == 0) return;
        /*_chatRecords.insert(0, {
          "host": true,
          "name": "你",
          "content": _textEditingController.text.trim(),
          "type": 0,
          "info": info,
        });*/

        socketMsg =
            "[CHAT][${DateTime.now().millisecondsSinceEpoch}][${userId}][][${doctorId}][2] - " +
                _textEditingController.text.trim().replaceAll("\n", "<br/>");
        break;
      case 1:
        // 图片
        /*_chatRecords.insert(0, {
          "host": true,
          "name": "你",
          "content": _textEditingController.text.trim(),
          "type": 1,
          "info": info,
        });*/

        socketMsg =
            "[CHAT][${DateTime.now().millisecondsSinceEpoch}][${userId}][][${doctorId}][2] - [image]" +
                info;
        break;
      case 2:
        // 病历卡
        /*_chatRecords.insert(0, {
          "host": true,
          "name": "你",
          "content": _textEditingController.text.trim(),
          "type": 2,
          "info": info,
        });*/

        socketMsg =
            "[CHAT][${DateTime.now().millisecondsSinceEpoch}][${userId}][][${doctorId}][2] - " +
                info;
        break;
    }

    socket.sendMessage(socketMsg);
    _textEditingController.text = "";
    setState(() {});
  }

  Future<ChatDisease?> fetchData() async {
    print(Global.token);
    final response = await http.get(
        Uri.parse(
            '${Global.BaseUrl}chat/getChatDisease?patientId=${Global.selectPatient}'),
        headers: {
          HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
          'token': '${Global.token}',
        });

    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      ChatDisease mChatDisease = new ChatDisease.fromJson(jsonResponse);

      if (mChatDisease.code == Global.responseSuccessCode) {
        print(mChatDisease.data?.patientId);
      } else {
        Component.toast(mChatDisease.msg.toString(), 0);
        return null;
      }
      return mChatDisease;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }
}
