import 'dart:io';

import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/utils/logger.dart';
import 'package:eitc_erm_app/widget/loading.dart';
import 'package:flutter/material.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 {
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}user/list'), headers: jsonHeaders(withToken: true));
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("就诊人列表=$json");
      UserListEntity mUserListEntity = UserListEntity.fromJson(json);
      return mUserListEntity;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('就诊人管理',
            style: TextStyle(
              color: Colors.white,
            )),
        centerTitle: true,
        elevation: 0.5,
        backgroundColor: Global.StatusBarColor,
        leading: 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(
                itemCount: data?.data?.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    contentPadding: const EdgeInsets.all(0),
                    title: CupertinoLeftScroll(
                      key: Key('$index'),
                      // left scroll widget will auto close while the other widget is opened and has same closeTag.
                      // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                      closeTag: const LeftScrollCloseTag('tag'),
                      buttonWidth: 70,
                      buttons: <Widget>[
                        Row(
                          children: <Widget>[
                            const SizedBox(width: 20.0),
                            LeftScrollItem(
                              text: ' 解绑 ',
                              color: Colors.red,
                              onTap: () {
                                showDialog(
                                    context: context,
                                    builder: (context) {
                                      return AlertDialog(
                                          title: const Text('提示',
                                              style: TextStyle(
                                                  color: Colors.blueAccent)),
                                          content: const Text('确定解绑该就诊人？'),
                                          actions: <Widget>[
                                            TextButton(
                                              onPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                              child: const Text('取消'),
                                            ),
                                            TextButton(
                                              onPressed: () {
                                                Navigator.of(context).pop();
                                                remove(
                                                    patientId:
                                                        '${data!.data![index].patientId}');
                                              },
                                              child: const Text('确定'),
                                            ),
                                          ]);
                                    });
                              },
                            ),
                          ],
                        ),
                      ],
                      onTap: () async {
                        final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AddPatient(
                                    userListEntity: data,
                                    whichPatient: index,
                                    key: const Key(""),
                                  )),
                        );
                        setState(() {
                          _future = fetchData();
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.only(left: 10),
                        height: 60,
                        color: Colors.white,
                        alignment: Alignment.centerLeft,
                        child: Row(
                          children: [
                            Expanded(
                                child: Text(
                              data!.data![index].patientName as String,
                              style: const TextStyle(fontSize: 18),
                            )),
                            Visibility(
                                visible: data.data?[index].isDefault == 1,
                                child: Container(
                                  margin: const EdgeInsets.only(right: 10),
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 8, vertical: 3),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(30),
                                      color: Colors.lightBlueAccent),
                                  child: const Text(
                                    "默认",
                                    style: TextStyle(
                                        fontSize: 12, color: Colors.white),
                                  ),
                                ))
                          ],
                        ),
                      ),
                    ),
                    subtitle: Container(
                      padding: const EdgeInsets.only(left: 10),
                      child:
                          Text('身份证-${data.data![index].identificationCard}'),
                    ),
                    onTap: () async {
                      final result = await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => AddPatient(
                                  userListEntity: data,
                                  whichPatient: index,
                                  key: const Key(""),
                                )),
                      );
                      setState(() {
                        _future = fetchData();
                      });
                    },
                  );
                },
              ));
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            }
            return const Expanded(child: ColorLoader());
          },
        ),
        Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                style: const ButtonStyle(
                  backgroundColor: WidgetStatePropertyAll(Colors.blue),
                ),
                onPressed: () async {
                  await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => AddPatient(
                              userListEntity: new UserListEntity(),
                              whichPatient: -1,
                              key: const Key(""),
                            )),
                  );
                  setState(() {
                    _future = fetchData();
                  });
                },
                child: const Text("添加就诊人",
                    style: TextStyle(color: Colors.white, fontSize: 15)),
              ),
            )),
        const SizedBox(
          height: 10,
        )
      ]),
    );
  }

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

  Future<void> remove({required String patientId}) async {
    logd("要解绑的就诊人ID=$patientId");
    final response = await http.delete(
      Uri.parse('${Global.BaseUrl}user/remove?patientId=$patientId'),
      headers: {
        'token': Global.token,
      },
    );
    try {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("删除就诊人结果=$json");
      NormalResponse mNormalResponse = NormalResponse.fromJson(json);
      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 {}
  }
}
