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

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/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

import 'bean/appointment_list.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(RecordRegistration());
}

class RecordRegistration extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => RecordRegistrationState();
}

class RecordRegistrationState extends State<RecordRegistration> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<AppointmentList?> _future;
  String appointmentStatusStr =
      'appointmentStatusArray[0]=1&appointmentStatusArray[1]=3&appointmentStatusArray[2]=4&appointmentStatusArray[3]=5&appointmentStatusArray[4]=6&appointmentStatusArray[5]=8';

  @override
  void initState() {
    super.initState();
    print("Global.selectPatient " + Global.selectPatient.toString());
    if (Global.selectPatient == -1) {
      Component.toast("请先添加或选择患者！", 2);
      Navigator.of(context).pop();
      return;
    }
    _future = fetchData();
  }

  Future<AppointmentList?> fetchData() async {
    print(Global.token);
    final response = await http.get(
        Uri.parse(
            '${Global.BaseUrl}patient-appointment/list?appointmentPersonId=${Global.appointmentPersonId}&${appointmentStatusStr}'),
        headers: {
          HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
          'token': '${Global.token}',
        });
    print(
        '${Global.BaseUrl}patient-appointment/list?appointmentPersonId=${Global.appointmentPersonId}&${appointmentStatusStr}');
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      AppointmentList mAppointmentList =
          new AppointmentList.fromJson(jsonResponse);

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

  @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: Center(
          child: Column(children: <Widget>[
            Container(
              decoration: BoxDecoration(
                color: Global.StatusBarColor,
              ),
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: <Widget>[
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  Text(
                                    Global.patient.data == null
                                        ? ""
                                        : Global
                                            .patient
                                            .data![Global.selectPatient]
                                            .patientName
                                            .toString(),
                                    style: const TextStyle(
                                        fontSize: 20, color: Colors.white),
                                  ),
                                  SizedBox(
                                    width: 20,
                                  ),
                                  Text(
                                    Global.patient.data == null
                                        ? ""
                                        : Global
                                            .patient
                                            .data![Global.selectPatient]
                                            .userRelationship
                                            .toString(),
                                    style: const TextStyle(
                                        backgroundColor: Colors.cyan,
                                        fontSize: 14,
                                        color: Colors.white),
                                  ),
                                ]),
                            Text(
                              Global.patient.data == null
                                  ? ""
                                  : Global.patient.data![Global.selectPatient]
                                      .identificationCard
                                      .toString()
                                      .replaceRange(
                                          6,
                                          Global
                                                  .patient
                                                  .data![Global.selectPatient]
                                                  .identificationCard
                                                  .toString()
                                                  .length -
                                              2,
                                          '******'),
                              style: const TextStyle(
                                  fontSize: 15, color: Colors.black38),
                            ),
                          ]),
                      GestureDetector(
                          child: Column(children: <Widget>[
                            Icon(
                              Icons.cached_outlined,
                              color: Colors.yellowAccent,
                            ),
                            Text(
                              '切换就诊人',
                              style: const TextStyle(
                                  fontSize: 14, color: Colors.yellowAccent),
                            ),
                          ]),
                          onTap: () async {
                            await Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      SelectPatient("fromRecordRegistration")),
                            );
                            setState(() {
                              _future = fetchData();
                            });
                          }),
                    ]),
              ),
            ),
            DefaultTabController(
              initialIndex: 0,
              length: 4,
              child: TabBar(
                tabs: <Widget>[
                  Tab(
                    text: "全部",
                  ),
                  Tab(
                    text: "已预约",
                  ),
                  Tab(
                    text: "治疗完成",
                  ),
                  Tab(
                    text: "已取消",
                  ),
                ],
                enableFeedback: true,
                onTap: (index) {
                  switch (index) {
                    case 0:
                      appointmentStatusStr =
                          'appointmentStatusArray[0]=1&appointmentStatusArray[1]=3&appointmentStatusArray[2]=4&appointmentStatusArray[3]=5&appointmentStatusArray[4]=6&appointmentStatusArray[5]=8';
                      break;
                    case 1:
                      appointmentStatusStr =
                          'appointmentStatusArray[0]=0&appointmentStatusArray[1]=1';
                      break;
                    case 2:
                      appointmentStatusStr =
                          'appointmentStatusArray[0]=0&appointmentStatusArray[1]=5';
                      break;
                    case 3:
                      appointmentStatusStr =
                          'appointmentStatusArray[0]=0&appointmentStatusArray[1]=8';
                      break;
                  }
                  setState(() {
                    _future = fetchData();
                  });
                },
              ),
            ),
            Expanded(
              child: FutureBuilder<AppointmentList?>(
                future: _future,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    AppointmentList? data = snapshot.data;
                    return ListView.builder(
                      itemCount: data?.data?.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: Container(
                            width: double.infinity,
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(children: [
                                            Text(
                                              data!.data![index].department == null ? "" : data!.data![index].department
                                                  .toString(),
                                              style:
                                                  const TextStyle(fontSize: 18),
                                            ),
                                            SizedBox(
                                              width: 5,
                                            ),
                                            Text(
                                              data!.data![index].attendingDoctor
                                                  .toString(),
                                              style: const TextStyle(
                                                  fontSize: 15,
                                                  color: Colors.green),
                                            ),
                                          ]),
                                          GetAppointmentStatus(data!
                                              .data![index].appointmentStatus),
                                        ]),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            '就诊科室',
                                            style: TextStyle(
                                                fontSize: 15,
                                                color: Colors.grey),
                                          ),
                                          Text(
                                            data!.data![index].department == null ? "" : data!.data![index].department
                                                .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(
                                            data!.data![index].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(
                                            data!.data![index]
                                                .appointmentStartTime
                                                .toString(),
                                            style: TextStyle(fontSize: 15),
                                          ),
                                        ]),
                                  ),
                                ]),
                          ),
                          subtitle: Padding(
                            padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
                            child: Container(
                              width: double.infinity,
                              height: 1.0,
                              padding: const EdgeInsets.all(50),
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.black, Colors.white],
                                  begin: Alignment.center,
                                  end: Alignment.centerRight,
                                  tileMode: TileMode.mirror,
                                ),
                              ),
                              child: Image(
                                  image: AssetImage('assets/images/line.png'),
                                  fit: BoxFit.fitWidth),
                            ),
                          ),
                          onTap: () {
                            // Navigator.push(
                            //   context,
                            //   MaterialPageRoute(builder: (context) => NfcDetail()),
                            // );
                          },
                        );
                      },
                    );
                  } else if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  }
                  return ColorLoader();
                },
              ),
            ),
          ]),
        ),
      ),
    );
  }
}

class GetAppointmentStatus extends StatelessWidget {
  int mStatus = 0;
  GetAppointmentStatus(status) {
    mStatus = status;
  }

  @override
  Widget build(BuildContext context) {
    // 1预约，2已确定，3已到店，4治疗中，5治疗完成，6已结账，7已离开，8已失约
    switch (mStatus) {
      case 1:
        return Text(
          '已预约',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 2:
        return Text(
          '已确定',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 3:
        return Text(
          '已到店',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 4:
        return Text(
          '治疗中',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 5:
        return Text(
          '治疗完成',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 6:
        return Text(
          '已结账',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 7:
        return Text(
          '已离开',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
      case 8:
        return Text(
          '已失约',
          style: const TextStyle(fontSize: 15, color: Colors.blue),
        );
        break;
    }
    return Text(
      '未知',
      style: const TextStyle(fontSize: 15, color: Colors.blue),
    );
    ;
  }
}

class _IdCardInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    // 只保留前6位和后2位，中间用星号(*)替换
    String newText =
        newValue.text.replaceRange(6, newValue.text.length - 2, '******');
    return new TextEditingValue(
      text: newText,
      selection: new TextSelection.collapsed(offset: newText.length),
    );
  }
}
