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

import 'package:eitc_erm_app/select_department.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/cupertino.dart';
import 'package:flutter/material.dart';

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

import 'bean/user_list.dart';
import 'confirm_registration.dart';
import 'doctor_detail.dart';

import 'package:flutter_localizations/flutter_localizations.dart';

// void main() => runApp(Registration());
UserListEntity mUserListEntity = new UserListEntity();
int mWhichPatient = 0;

class Registration extends StatefulWidget {
  Registration(
      {required Key key, required userListEntity, required whichPatient})
      : super(key: key) {
    mUserListEntity = userListEntity;
    mWhichPatient = whichPatient;
  }
  @override
  State<StatefulWidget> createState() => RegistrationState();
}

class RegistrationState extends State<Registration> {
  DateTime now = DateTime.now();
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<DoctorListEntity?>? _future = null;
  String searchDeptName = "";
  int selectItem = -1;
  String selectDateStr = "";
  String halfHourLater = "";

  @override
  void initState() {
    super.initState();
    _future = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate, //多加这行代码
      ],
      supportedLocales: [
        const Locale('en', 'US'), // 美国英语
        const Locale('zh', 'CN'), // 中文简体
        //其它Locales
      ],
      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: [
          Row(children: [
            GestureDetector(
                onTap: () {
                  _showDatePicker(0);
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50.0,
                  width: 50,
                  color: Global.StatusBarColor,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        Icons.calendar_month_outlined,
                        size: 15,
                        color: Colors.white,
                      ),
                      Text(
                        '全部',
                        style: TextStyle(fontSize: 12, color: Colors.white),
                      ),
                    ],
                  ),
                )),
            Expanded(
              child: Container(
                height: 50.0,
                width: 350,
                color: Global.StatusBarColor,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          selectItem = 0;
                          _showDatePicker(0);
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 0
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          "今天\n " + LocalDateUtils.getMMDD(now, "-") + " ",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 0)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(1);
                          selectItem = 1;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 1
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 1))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 1)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 1)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(2);
                          selectItem = 2;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 2
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 2))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 2)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 2)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(3);
                          selectItem = 3;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 3
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 3))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 3)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 3)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(4);
                          selectItem = 4;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 4
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 4))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 4)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 4)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(5);
                          selectItem = 5;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 5
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 5))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 5)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 5)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showDatePicker(6);
                          selectItem = 6;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.all(3),
                        padding: EdgeInsets.only(right: 5.0, left: 5.0),
                        decoration: selectItem == 6
                            ? BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                color: Colors.white)
                            : null,
                        child: Text(
                          LocalDateUtils.getWeekday(
                                  now.add(Duration(days: 6))) +
                              "\n " +
                              LocalDateUtils.getMMDD(
                                  now.add(Duration(days: 6)), "-") +
                              " ",
                          style: TextStyle(
                            fontSize: 10,
                            color: (selectItem == 6)
                                ? Global.StatusBarColor
                                : Colors.white,
                          ),
                        ),
                      ),
                    ),
                    // 更多的子Widget根据需要添加
                  ],
                ),
              ),
            ),
          ]),
          Padding(
              padding: EdgeInsets.fromLTRB(5, 10, 5, 5),
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                ),
                child: Text(
                  "点击查找科室",
                  style: const TextStyle(fontSize: 18, color: Colors.white),
                ),
                onPressed: () async {
                  final result = await Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => SelectDepartment()),
                  );
                  setState(() {
                    searchDeptName = result;
                    _future = fetchData();
                  });
                },
              )),
          Expanded(
            child: FutureBuilder<dynamic>(
              future: _future,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  DoctorListEntity 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: 60,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                        title: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '${data.data?[index].nickName} ${data.data?[index].deptName}',
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.black54),
                              ),
                              ElevatedButton(
                                style: ButtonStyle(
                                  padding: MaterialStateProperty.all(
                                      EdgeInsets.fromLTRB(15, 3, 15, 3)),
                                  minimumSize:
                                      MaterialStateProperty.all(Size.zero),
                                  backgroundColor:
                                      MaterialStateProperty.all(Colors.blue),
                                ),
                                child: Text(
                                  "查看详情",
                                  style: const TextStyle(
                                      fontSize: 12, color: Colors.white),
                                ),
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => DoctorDetail(
                                            doctorListEntity: data,
                                            key: new Key(''),
                                            which: index)),
                                  );
                                },
                              ),
                              ElevatedButton(
                                child: Text("挂号",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 12)),
                                style: ButtonStyle(
                                  padding: MaterialStateProperty.all(
                                      EdgeInsets.fromLTRB(15, 3, 15, 3)),
                                  minimumSize:
                                      MaterialStateProperty.all(Size.zero),
                                  backgroundColor:
                                      MaterialStateProperty.resolveWith<Color>(
                                          (states) {
                                    return Colors.yellow; // Regular color
                                  }),
                                ),
                                onPressed: () {
                                  print(selectDateStr);
                                  if(selectDateStr.isEmpty) {
                                    Component.toast("请选择预约时间", 0);
                                    return;
                                  }

                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              ConfirmRegistration(
                                                visitTime : selectDateStr,
                                                  visitTimeEnd : halfHourLater,
                                                  userListEntity:
                                                      mUserListEntity,
                                                  whichPatient: mWhichPatient,
                                                  doctorListEntity: data,
                                                  key: new Key(''),
                                                  which: index)));
                                },
                              ),
                            ]),
                        subtitle: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('从事口腔专业20余年。擅长口腔正畸、种植牙高精尖技术。 '),
                            ]),
                        onTap: () {
                          // Navigator.push(
                          //   context,
                          //   MaterialPageRoute(builder: (context) => NfcDetail()),
                          // );
                        },
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                return ColorLoader();
              },
            ),
          ),
        ]),
      ),
    );
  }

  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:  () {
                                  _future = fetchData();
                                  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;
                            },
                          ),
                        ),
                      ]),
                ),),
              ]),
        );
      },
    );
  }

  Future<DoctorListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final timeout = const Duration(seconds: 30);
    final response = await http.get(
        Uri.parse('${Global.BaseUrl}doctor/list?deptName=${searchDeptName}&selectDateStr=${selectDateStr}'),
        headers: {
          HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
          'token': '${Global.token}',
        }).timeout(timeout);
    print('${Global.BaseUrl}doctor/list?deptName=${searchDeptName}&selectDateStr=${selectDateStr}');
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      DoctorListEntity mDoctorListEntity =
          new DoctorListEntity.fromJson(jsonResponse);
      return mDoctorListEntity;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }
}
