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

import 'package:eitc_erm_app/registration.dart';
import 'package:eitc_erm_app/select_patient.dart';
import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/widget/line.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;

import 'bean/doctor_list.dart';
import 'bean/favourite_doctor_list.dart';
import 'bean/message_box_s_list_entity.dart';
import 'bean/normal_response.dart';
import 'bean/pda_patrol_time_list.dart';
import 'confirm_registration.dart';
import 'my_doctor.dart';
import 'online_consultation.dart';
import 'online_consultation_detail.dart';

/*void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(DoctorDetail());
}*/
late DoctorListEntity mDoctorListEntity = new DoctorListEntity();
int mWhich = 0;
String selectDateStr = "";
String halfHourLater = "";
FavouriteDoctorListEntity mFavouriteDoctorListEntity = new FavouriteDoctorListEntity();

class DoctorDetail extends StatefulWidget {
  DoctorDetail({required Key key, required doctorListEntity, which})
      : super(key: key) {
    mDoctorListEntity = doctorListEntity;
    mWhich = which;
    print(mDoctorListEntity.data![mWhich].userId.toString() + " =====================");
  }

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

class DoctorDetailState extends State<DoctorDetail> {
  List<Widget> widgetList = [];
  @override
  void initState() {
    super.initState();
    fetchData();

    String? doctorProficient = mDoctorListEntity.data?[mWhich].doctorProficient;
    List<String>? doctorProficientList = doctorProficient?.split(',');
    if (doctorProficientList != null)
      for (var i = 0; i < doctorProficientList!.length; i++) {
        widgetList.add(
          Container(
            margin: const EdgeInsets.all(5.0),
            child: Text(
              ' ${doctorProficientList[i]} ',
              style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 13,
                  color: Colors.white,
                  backgroundColor: Colors.cyan),
              textAlign: TextAlign.center,
            ),
          ),
        );
        widgetList.add(
          SizedBox(
            width: 5,
          ),
        );
      }
  }

  @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: Container(
          padding: const EdgeInsets.all(10),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(mainAxisSize: MainAxisSize.max, children: [
              Expanded(
                flex: 1,
                child: Padding(
                  padding: const EdgeInsets.all(10),
                  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,
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 4,
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '${mDoctorListEntity.data?[mWhich].nickName}',
                                    style: const TextStyle(fontSize: 18),
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Text(
                                    '${mDoctorListEntity.data?[mWhich].postNames == null ? "" : mDoctorListEntity.data?[mWhich].postNames}',
                                    style: const TextStyle(
                                        fontSize: 15, color: Colors.brown),
                                  ),
                                ]),
                            SizedBox(width: 75),
                            if (mDoctorListEntity.data?[mWhich].isCollection ==
                                0)
                              GestureDetector(
                                  child: Icon(
                                    Icons.favorite_border,
                                    color: Colors.grey,
                                  ),
                                  onTap: () {
                                    collectDoctor();
                                  }),
                            if (mDoctorListEntity.data?[mWhich].isCollection ==
                                1)
                              GestureDetector(
                                  child: Icon(
                                    Icons.favorite,
                                    color: Colors.red,
                                  ),
                                  onTap: () {
                                    cancelCollectDoctor();
                                  }),
                          ]),
                      Container(
                        padding: const EdgeInsets.fromLTRB(25, 5, 0, 0),
                        alignment: Alignment.centerLeft,
                        width: double.infinity,
                        child: Text(
                          '服务人数：${mDoctorListEntity.data?[mWhich].receivePatientNum}人',
                          style:
                              const TextStyle(fontSize: 15, color: Colors.grey),
                        ),
                      ),
                    ]),
              ),
            ]),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Text(
                mDoctorListEntity.data?[mWhich].doctorBlurb ?? "暂无",
                style: const TextStyle(fontSize: 14, color: Colors.grey),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Row(children: [
                Text(
                  '擅长：',
                  style: const TextStyle(fontSize: 15),
                ),
                SizedBox(
                  width: 5,
                ),
                Row(children: widgetList),
              ]),
            ),
            Line(),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Text(
                '服务项目',
                style: const TextStyle(fontSize: 18, color: Colors.black),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        Icons.collections_bookmark,
                        color: Colors.blue,
                        size: 35,
                      ),
                      SizedBox(width: 10),
                      Text('图文咨询',
                          style: TextStyle(
                              color: Colors.deepPurple, fontSize: 20)),
                    ],
                  ),
                  ElevatedButton(
                    child: Text("问诊",
                        style: TextStyle(color: Colors.white, fontSize: 15)),
                    style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.resolveWith<Color>((states) {
                        return Colors.orange; // Regular color
                      }),
                    ),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => OnlineConsultation()),
                      );
                    },
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        Icons.reddit_outlined,
                        color: Colors.blue,
                        size: 35,
                      ),
                      SizedBox(width: 10),
                      Text('挂号预约',
                          style: TextStyle(
                              color: Colors.deepPurple, fontSize: 20)),
                    ],
                  ),
                  ElevatedButton(
                    child: Text("挂号",
                        style: TextStyle(color: Colors.white, fontSize: 15)),
                    style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.resolveWith<Color>((states) {
                        return Colors.blue; // Regular color
                      }),
                    ),
                    onPressed: () async {
                      // if(Global.selectPatient != -1) {
                      if (Global.selectPatient != -1) {
                        if (selectDateStr.isEmpty) {
                          Component.toast("请选择预约时间", 0);
                          _showDatePicker(0);
                          return;
                        }
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => ConfirmRegistration(
                                    visitTime: selectDateStr,
                                    visitTimeEnd: halfHourLater,
                                    userListEntity: Global.patient,
                                    whichPatient: Global.selectPatient,
                                    doctorListEntity: mDoctorListEntity,
                                    key: new Key(''),
                                    which: mWhich)));
                      } else {
                        Component.toast("请先选择就诊人", 1);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  SelectPatient("fromDoctorDetail")),
                        );
                      }
                    },
                  ),
                ],
              ),
            ),
          ]),
        ),
      ),
    );
  }

  Future<void> collectDoctor() async {
    var params = {
      "avatar": mDoctorListEntity.data?[mWhich].avatar,
      "briefIntroduction": mDoctorListEntity.data?[mWhich].doctorBlurb,
      "doctorId": mDoctorListEntity.data?[mWhich].userId,
      "doctorName": mDoctorListEntity.data?[mWhich].nickName,
      "label": "",
      "postName": mDoctorListEntity.data?[mWhich].postNames
    };

    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };
    var response = await http.post(
        Uri.parse(Global.BaseUrl +
            'collection-doctor/collect-doctor?doctorId=' +
            mDoctorListEntity.data![mWhich].userId.toString()),
        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);
      NormalResponse mNormalResponse =
          new NormalResponse.fromJson(jsonResponse);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast("收藏成功！", 2);
        setState(() {
          mDoctorListEntity.data?[mWhich].isCollection = 1;
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  Future<FavouriteDoctorListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };

    final response = await http.get(
        Uri.parse(Global.BaseUrl + 'collection-doctor/list'),
        headers: headers);
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      mFavouriteDoctorListEntity =
      new FavouriteDoctorListEntity.fromJson(jsonResponse);
      if (mFavouriteDoctorListEntity.code == Global.responseSuccessCode) {
        return mFavouriteDoctorListEntity;
      } else {
        Component.toast(mFavouriteDoctorListEntity.msg.toString(), 0);
      }
      return null;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  Future<void> cancelCollectDoctor() async {
    var params = {
      "avatar": mDoctorListEntity.data?[mWhich].avatar,
      "briefIntroduction": mDoctorListEntity.data?[mWhich].doctorBlurb,
      "doctorId": mDoctorListEntity.data?[mWhich].userId,
      "doctorName": mDoctorListEntity.data?[mWhich].nickName,
      "label": "",
      "postName": mDoctorListEntity.data?[mWhich].postNames
    };

    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };
    var response = await http.post(
        Uri.parse(Global.BaseUrl +
            'collection-doctor/cancel-collect-doctor?doctorId=' +
            mDoctorListEntity.data![mWhich].userId.toString()),
        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);
      NormalResponse mNormalResponse =
          new NormalResponse.fromJson(jsonResponse);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast("取消成功！", 2);
        setState(() {
          mDoctorListEntity.data?[mWhich].isCollection = 0;
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  void _showDatePicker(int addDay) async {
    DateTime dateTime = DateTime(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day + addDay,
        DateTime.now().minute > 30
            ? DateTime.now().hour + 1
            : DateTime.now().hour,
        DateTime.now().minute > 30 ? 0 : 30);
    // 默认时间
    selectDateStr = dateTime.toString().replaceAll(":00.000", "");
    halfHourLater = dateTime
        .add(const Duration(minutes: 30))
        .toString()
        .replaceAll(":00.000", "");
    // 显示对话框
    await showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return MaterialApp(
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate, //多加这行代码
          ],
          supportedLocales: [
            const Locale('en', 'US'), // 美国英语
            const Locale('zh', 'CN'), // 中文简体
            //其它Locales
          ],
          home: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SizedBox(height: 500),
                Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(10),
                            topRight: Radius.circular(10)),
                        color: Colors.white),
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.fromLTRB(30, 10, 30, 0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Material(
                                  color: Colors.grey,
                                  borderRadius: BorderRadius.circular(5),
                                  child: InkWell(
                                    onTap: () {
                                      selectDateStr = "";
                                      Navigator.of(context).pop();
                                    },
                                    child: Container(
                                        height: 30,
                                        width: 50,
                                        alignment: Alignment.center,
                                        child: Text(
                                          "取消",
                                          style: TextStyle(
                                            color: Colors.white,
                                          ),
                                        )),
                                  ),
                                ),
                                Material(
                                  color: Colors.green,
                                  borderRadius: BorderRadius.circular(5),
                                  child: InkWell(
                                    onTap: () {
                                      Navigator.of(context).pop();
                                    },
                                    child: Container(
                                        height: 30,
                                        width: 50,
                                        alignment: Alignment.center,
                                        child: Text(
                                          "确定",
                                          style: TextStyle(
                                            color: Colors.white,
                                          ),
                                        )),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Expanded(
                            child: CupertinoDatePicker(
                              mode: CupertinoDatePickerMode.dateAndTime,
                              // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
                              initialDateTime: DateTime(
                                  DateTime.now().year,
                                  DateTime.now().month,
                                  DateTime.now().day + addDay,
                                  DateTime.now().minute > 30
                                      ? DateTime.now().hour + 1
                                      : DateTime.now().hour,
                                  DateTime.now().minute > 30 ? 0 : 30),
                              // 初始化日期
                              minimumDate: DateTime(2024, 07, 09),
                              // 最小可选日期
                              maximumDate: DateTime(2025, 07, 22),
                              // 最大可选日期
                              minimumYear: 2024,
                              // 最小年份
                              maximumYear: 2025,
                              // 最大年份
                              minuteInterval: 30,
                              // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
                              use24hFormat: true,
                              // 是否使用24小时制
                              dateOrder: DatePickerDateOrder.dmy,
                              // 日期选择器排序方式 默认年/月/日
                              backgroundColor: Colors.white,
                              // 选中日期变化回调
                              onDateTimeChanged: (dateTime) {
                                print(dateTime);
                                selectDateStr = dateTime.toString().replaceAll(":00.000", "");
                                halfHourLater = dateTime.add(const Duration(minutes: 30)).toString().replaceAll(":00.000", "");
                                // _chooseDateTime = dateTime;
                              },
                            ),
                          ),
                        ]),
                  ),
                ),
              ]),
        );
      },
    );
  }
}
