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

import 'package:eitc_erm_app/registration.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:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:left_scroll_actions/cupertinoLeftScroll.dart';
import 'package:left_scroll_actions/global/actionListener.dart';
import 'package:left_scroll_actions/leftScroll.dart';

import 'add_patient.dart';
import 'bean/normal_response.dart';
import 'bean/user_list.dart';

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

class PatientList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => PatientListState();
}

class PatientListState extends State<PatientList> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<UserListEntity?> _future;

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

  Future<UserListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}user/list'), 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);
      UserListEntity mUserListEntity =
          new UserListEntity.fromJson(jsonResponse);
      return mUserListEntity;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @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: Column(children: [
          /*Text(
            '选择就诊人',
            style: const TextStyle(fontSize: 15),
            textAlign: TextAlign.start,
            overflow: TextOverflow.ellipsis,
          ),*/
          FutureBuilder<UserListEntity?>(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                UserListEntity? data = snapshot.data;
                return Expanded(
                    child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: data?.data?.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: CupertinoLeftScroll(
                        key: Key('${index}'),
                        // left scroll widget will auto close while the other widget is opened and has same closeTag.
                        // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                        closeTag: LeftScrollCloseTag('tag'),
                        buttonWidth: 70,
                        child: Container(
                          height: 60,
                          color: Colors.white,
                          alignment: Alignment.centerLeft,
                          child: Text(
                            data!.data![index].patientName as String,
                            style: const TextStyle(fontSize: 18),
                          ),
                        ),
                        buttons: <Widget>[
                          Row(
                            children: <Widget>[
                              SizedBox(width: 20.0),
                              LeftScrollItem(
                                text: ' 解绑 ',
                                color: Colors.red,
                                onTap: () {
                                  showDialog(
                                      context: context,
                                      builder: (context) {
                                        return AlertDialog(
                                            title: Text('提示',
                                                style: TextStyle(
                                                    color: Colors.blueAccent)),
                                            content:
                                                Text('确定解绑该就诊人？'),
                                            actions: <Widget>[
                                              ElevatedButton(
                                                onPressed: () {
                                                  Navigator.of(context).pop();
                                                  remove(patientId: '${data!.data![index].patientId}');
                                                },
                                                child: Text('确定'),
                                              ),
                                              ElevatedButton(
                                                onPressed: () {
                                                  Navigator.of(context).pop();
                                                },
                                                child: Text('取消'),
                                              ),
                                            ]);
                                      });
                                },
                              ),
                            ],
                          ),
                        ],
                        onTap: () async {
                          final result = await Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => AddPatient(userListEntity : data, whichPatient : index,  key: new Key(""),)),
                          );
                          setState(() {
                            _future = fetchData();
                          });
                        },
                      ),
                      subtitle:
                          Text('身份证-${data!.data![index].identificationCard}'),
                      onTap: () async {
                        final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AddPatient(userListEntity : data, whichPatient : index,  key: new Key(""),)),
                        );
                        setState(() {
                          _future = fetchData();
                        });
                      },
                    );
                  },
                ));
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return ColorLoader();
            },
          ),
          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 - 32, 30), // 设置宽度和高度
              ),
            ),
            onPressed: () async {
              await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => AddPatient(userListEntity : new UserListEntity(), whichPatient : -1,  key: new Key(""),)),
              );
              setState(() {
                _future = fetchData();
              });
            },
          ),
        ]),
      ),
    );
  }

  onGoBack() {
    setState(() {
      _future = fetchData();
    });
  }

  Future<void> remove({required String patientId}) async {
    print(patientId);
    var params = {
      'patientId': patientId,
    };
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final response =
        await http.delete(Uri.parse('${Global.BaseUrl}user/remove'),
            headers: {
              'token': '${Global.token}',
            },
            body: params);
    try {
      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(() {
          _future = fetchData();
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } catch (e) {
      Component.toast("异常: $e", 0);
    } finally {}
  }
}
