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

import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import 'bean/appointment_list.dart';
import 'package:http/http.dart' as http;

import 'bean/disease.dart';
import 'chat/chat_home.dart';
import 'image_view.dart';
import 'online_consultation.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(OnlineConsultationDetail(""));
}

String mPatientId = "";

class OnlineConsultationDetail extends StatefulWidget {
  OnlineConsultationDetail(String patientId) {
    mPatientId = patientId;
  }
  @override
  State<StatefulWidget> createState() => OnlineConsultationDetailState();
}

class OnlineConsultationDetailState extends State<OnlineConsultationDetail> {
  Disease mDisease = new Disease();
  late BuildContext cxt;

  @override
  void initState() {
    super.initState();
    getChatDisease();
    print(Global.user.data?.id);
  }

  Future<Disease?> getChatDisease() async {
    Uri url = Uri.parse(
        '${Global.BaseUrl}chat/getChatDisease?patientId=${Global.appointmentPersonId}');
    if(!mPatientId.isEmpty) {
      url = Uri.parse(
          '${Global.BaseUrl}chat/getChatDisease?patientId=${mPatientId}');
    }
    print("======== " + url.toString());
    final response = await http.get(url,
        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);
      mDisease = new Disease.fromJson(jsonResponse);

      if (mDisease.code == Global.responseSuccessCode) {
        if (mDisease.data?.name == null) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => OnlineConsultation()),
          );
        }
        setState(() {});
      } else {
        Component.toast(mDisease.msg.toString(), 0);
        return null;
      }
      return mDisease;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    this.cxt = context;
    return MaterialApp(
        home: Scaffold(
            resizeToAvoidBottomInset: false,
            backgroundColor: Global.BackgroundColor,
            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: Container(
                padding: EdgeInsets.all(10),
                child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '问诊资料',
                                style: TextStyle(
                                    fontSize: 20, color: Colors.black),
                              ),
                            ]),
                      ),
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.all(10),
                          child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                /*Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '挂号费',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          '¥12.5',
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),*/
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '就诊人',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          mDisease.data == null ? "" : mDisease.data!.name.toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '性别',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          mDisease.data == null ? "" : mDisease.data!.sex == 0 ? "男" : "女",
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '年龄',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          mDisease.data == null ? "" : mDisease.data!.age.toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '医生姓名',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          mDisease.data == null ? "" : mDisease.data!.docker.toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      SizedBox(height: 8),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '病情资料',
                                style: TextStyle(
                                    fontSize: 20, color: Colors.black),
                              ),
                            ]),
                      ),
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.all(10),
                          child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Expanded(
                                          child: TextField(
                                            maxLines: 5,
                                            enabled: false,
                                            decoration: InputDecoration(
                                              border: OutlineInputBorder(),
                                              hintText: mDisease.data == null ? "" : mDisease.data!.resource
                                                  .toString(),
                                            ),
                                          ),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(5),
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '患处、病历、检查单等照片',
                                style: TextStyle(fontSize: 10),
                              ),
                              SizedBox(height: 3),
                              GridView.builder(
                                padding: const EdgeInsets.all(10),
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                gridDelegate:
                                    const SliverGridDelegateWithFixedCrossAxisCount(
                                  //注意此行
                                  crossAxisCount: 3, //每行 widget 数量
                                  crossAxisSpacing: 10, //widget 水平之间的距离
                                  mainAxisSpacing: 10, //widget 垂直之间的距离
                                ),
                                itemCount:
                                mDisease.data == null ? 0 :mDisease.data?.url?.split(",").length,
                                // itemCount: 2,
                                itemBuilder: _customWidget,
                              )
                            ]),
                      ),
                      /*ElevatedButton(
                        child: Text("下一步",
                            style: TextStyle(
                                color: Colors.white, fontSize: 15)),
                        style: ButtonStyle(
                          backgroundColor:
                          MaterialStateProperty.resolveWith<Color>(
                                  (states) {
                                return Colors.blue; // Regular color
                              }),
                          fixedSize: MaterialStateProperty.all<Size>(
                            Size(MediaQuery.of(context).size.width - 30,
                                30), // 设置宽度和高度
                          ),
                        ),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => ChatHome()),
                          );
                        },
                      ),*/
                    ]))));
  }

  Widget _customWidget(BuildContext context, int index) {
    String? imgUrl = mDisease.data?.url!.split(",")[index];
    return GestureDetector(
      onTap: () {},
      child: Container(
        child: Center(
          child: GestureDetector(
            onTap: () async {
              Navigator.push(
                cxt,
                MaterialPageRoute(
                    builder: (context) => ImagePreviewPage(imgUrl!),
              ));
            },
            child: Image.network(
              // 图片地址
              imgUrl!,
              width: 100,
              fit: BoxFit.cover,
              excludeFromSemantics: true,
              errorBuilder: (context, error, stackTrace) => Icon(
                Icons.image,
                size: 100,
                color: Colors.grey,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
