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

import 'package:eitc_erm_app/success_registration.dart';
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/doctor_list.dart';
import 'bean/normal_response2.dart';
import 'bean/user_list.dart';

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

// void main() {
//   WidgetsFlutterBinding.ensureInitialized();
//   runApp(ConfirmRegistration());
// }
String mVisitTime = "";
String mVisitTimeEnd = "";
late DoctorListEntity mDoctorListEntity = new DoctorListEntity();
int mWhich = 0;
UserListEntity mUserListEntity = new UserListEntity();
int mWhichPatient = 0;
TextEditingController ctrlRemark = TextEditingController();

class ConfirmRegistration extends StatefulWidget {
  ConfirmRegistration(
      {required String visitTime,
      required String visitTimeEnd,
      required userListEntity,
      required whichPatient,
      required Key key,
      required doctorListEntity,
      which})
      : super(key: key) {
    mVisitTime = visitTime;
    mVisitTimeEnd = visitTimeEnd;
    mUserListEntity = userListEntity;
    mWhichPatient = whichPatient;
    mDoctorListEntity = doctorListEntity;
    mWhich = which;
  }

  @override
  State<StatefulWidget> createState() => ConfirmRegistrationState();
}

class ConfirmRegistrationState extends State<ConfirmRegistration> {
  final GlobalKey<ScaffoldState> _scaffoldKey =
      GlobalKey<ScaffoldState>(); //重要代码 需要绑定key不然切换页面会停止摄像头采集

  @override
  void initState() {
    super.initState();

    initPlatformState(); //检查权限

    //延迟1秒 直播推流
    Future.delayed(Duration(milliseconds: 1000), () {});
  }

  Future<void> initPlatformState() async {
    //相机权限
    if (await requestCameraPermission() == false) {
      return;
    }
    //录音权限
    if (await requestMicrophonePermission() == false) {
      return;
    }
  }

  Future<bool> requestCameraPermission() async {
    var status = await Permission.camera.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.camera.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  Future<bool> requestMicrophonePermission() async {
    var status = await Permission.microphone.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.microphone.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            resizeToAvoidBottomInset: false,
            backgroundColor: Color.fromARGB(0xff, 0xef, 0xef, 0xef),
            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: SingleChildScrollView(
    child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(10),
                          child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(children: [
                                  Padding(
                                    padding: const EdgeInsets.all(3),
                                    child: Image.network(
                                      "${Global.ImageUrl}${mDoctorListEntity.data?[mWhich].avatar}",
                                      width: 60,
                                      fit: BoxFit.cover,
                                      excludeFromSemantics: true,
                                      errorBuilder: (context, error, stackTrace) => Icon(
                                        Icons.person_pin,
                                        size: 60,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ),
                                  Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          mDoctorListEntity
                                              .data![mWhich].nickName
                                              .toString(),
                                          style: TextStyle(fontSize: 20),
                                        ),
                                        SizedBox(height: 8),
                                        Text(
                                          mDoctorListEntity
                                              .data![mWhich].postNames
                                              .toString(),
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                      ]),
                                ]),
                                Text(
                                  mDoctorListEntity.data![mWhich].doctorBlurb ==
                                          null
                                      ? "简介：暂无。"
                                      : "    " + mDoctorListEntity
                                          .data![mWhich].doctorBlurb
                                          .toString(),
                                  style: TextStyle(
                                      fontSize: 15, color: Colors.grey),
                                ),
                              ]),
                        ),
                      ),
                      SizedBox(height: 8),
                      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>[
                                Visibility(
                                  visible: false,
                                  child: 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(
                                          mUserListEntity!
                                              .data![mWhichPatient].patientName
                                              .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(
                                          '${mVisitTime}',
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '挂号科室',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          mDoctorListEntity
                                              .data![mWhich].deptName
                                              .toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      SizedBox(height: 8),
                      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, // 设置最大行数
                                            controller: ctrlRemark,
                                            decoration: InputDecoration(
                                              border: OutlineInputBorder(),
                                              hintText:
                                                  '温馨提示：\n预约后请与就诊当天到就诊室按照工作人员的安排就诊',
                                              hintStyle:
                                                  TextStyle(color: Colors.grey),
                                            ),
                                          ),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '',
                                style:
                                    TextStyle(fontSize: 20, color: Colors.red),
                              ),
                              ElevatedButton(
                                style: ButtonStyle(
                                  backgroundColor:
                                      MaterialStateProperty.all(Colors.blue),
                                ),
                                child: Text(
                                  '确定挂号',
                                  style: const TextStyle(
                                      fontSize: 15, color: Colors.white),
                                ),
                                onPressed: () {
                                  patientAppointment();
                                  /*Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            SuccessRegistration()),
                                  );*/
                                },
                              ),
                            ]),
                      ),
                    ])))));
  }

  Future<String?> patientAppointment() async {
    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };

    String url = 'patient-appointment';
    print(
        '${mUserListEntity.data?[mWhichPatient].identificationCard}  ${mDoctorListEntity.data?[mWhich].userId}  ${mVisitTime}  ${mVisitTimeEnd}');
    var params = {
      'identificationCard':
          mUserListEntity.data?[mWhichPatient].identificationCard,
      'attendingDoctor': mDoctorListEntity.data?[mWhich].userId,
      'appointmentStartTime': mVisitTime,
      'appointmentEndTime': mVisitTimeEnd,
      'remark': ctrlRemark.text,
    };

    var response = await http.post(Uri.parse(Global.BaseUrl + url),
        body: jsonEncode(params), headers: headers);
    print(response.body.toString());
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonString);
      Normal2Response mNormal2Response =
          new Normal2Response.fromJson(jsonResponse);
      if (mNormal2Response.code == Global.responseSuccessCode) {
        Component.toast("预约成功！", 2);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) => SuccessRegistration(
                    patient: mUserListEntity.data?[mWhichPatient].patientName,
                    visitTime: mVisitTime,
                    deptName: mDoctorListEntity.data?[mWhich].deptName,
                    doctorName: mDoctorListEntity.data?[mWhich].nickName,
                    key: new Key(''),
                    remark: ctrlRemark.text,
                  )),
        );
      } else {
        Component.toast(mNormal2Response.msg.toString(), 0);
      }

      return response.toString();
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }
}
