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/utils/Utils.dart';
import 'package:eitc_erm_app/widget/line.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;

import 'bean/dropdown_list.dart';
import 'bean/message_box_s_list_entity.dart';
import 'bean/normal_response.dart';
import 'bean/normal_response3.dart';
import 'bean/pda_patrol_time_list.dart';
import 'bean/user_list.dart';

/*void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(AddPatient());
}*/
UserListEntity mUserListEntity = new UserListEntity();
int mWhichPatient = 0;
bool isEdit = false;

class AddPatient extends StatefulWidget {
  AddPatient(
      {required Key key, required userListEntity, required whichPatient})
      : super(key: key) {
    mUserListEntity = userListEntity;
    mWhichPatient = whichPatient;
    mWhichPatient == -1 ? isEdit = false : isEdit = true;
    print(isEdit.toString() + '   =================');
  }
  @override
  State<StatefulWidget> createState() => AddPatientState();
}

class AddPatientState extends State<AddPatient> {
  int selectedRadioValue = 0;
  bool switchSelected = true;
  String relationship = "请选择与本人的关系";
  String passport = "请选择证件类型";
  String previous = "请选择既往病史";
  String family = "请选择家族病史";
  TextEditingController nameController = TextEditingController();
  TextEditingController passportController = TextEditingController();
  TextEditingController mobileController = TextEditingController();
  TextEditingController allergyController = TextEditingController();
  TextEditingController homeAddressController = TextEditingController();
  bool mobileCanEdit = true;
  List selectItem0 = [];
  List selectItem1 = [];
  List selectItem2 = [];
  List selectItem3 = [];

  void getDropdownList() {
    for(int i = 0; i < 4; i++) {
      dropdownList(i);
    }
  }
  Future<DropdownList?> dropdownList(int i) async {
    String url = '${Global.BaseUrl}system/dropdownList?dictType=erm_personal_relationship';
    print(url);
    switch(i) {
      case 1:
        url = '${Global.BaseUrl}system/type/erm_document_type';
        break;
      case 2:
        url = '${Global.BaseUrl}system/dropdownList?dictType=erm_past_history';
        break;
      case 3:
        url = '${Global.BaseUrl}system/dropdownList?dictType=erm_family_history';
        break;
    }
    final response = await http.get(
        Uri.parse(url),
        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);
      DropdownList mDropdownList = new DropdownList.fromJson(jsonResponse);

      if (mDropdownList.code == Global.responseSuccessCode) {
        switch(i) {
          case 0:
            mDropdownList.data?.forEach((item) {
              selectItem0.add(item.dictValue);
            });
            break;
          case 1:
            mDropdownList.data?.forEach((item) {
              selectItem1.add(item.dictValue);
            });
            break;
          case 2:
            mDropdownList.data?.forEach((item) {
              selectItem2.add(item.dictValue);
            });
            break;
          case 3:
            mDropdownList.data?.forEach((item) {
              selectItem3.add(item.dictValue);
            });
            break;
        }

        setState(() {

        });
      } else {
        Component.toast(mDropdownList.msg.toString(), 0);
        return null;
      }
      return mDropdownList;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  @override
  void initState() {
    super.initState();
    getDropdownList();
    if(isEdit) {
      relationship = mUserListEntity.data![mWhichPatient].userRelationship.toString();
      nameController.text = mUserListEntity.data![mWhichPatient].patientName.toString();
      int? passportInt = mUserListEntity.data![mWhichPatient].documentType;
      switch(passportInt) {
        case 0:
          passport = "身份证";
          break;
        case 1:
          passport = "护照";
          break;
        case 2:
          passport = "港澳通行证";
          break;
      }
      if(relationship == "本人") {
        mobileCanEdit = false;
      } else {
        mobileCanEdit = true;
      }
      passportController.text = mUserListEntity.data![mWhichPatient].identificationCard.toString();
      previous = mUserListEntity.data![mWhichPatient].pastHistory.toString();
      print("------------------------ " + mUserListEntity.data![mWhichPatient].pastHistory.toString());
      family = mUserListEntity.data![mWhichPatient].familyHistory.toString();
      if(!mUserListEntity.data![mWhichPatient].allergyHistory.toString().isEmpty) {
        selectedRadioValue = 1;
        allergyController.text = mUserListEntity.data![mWhichPatient].allergyHistory.toString();
      }
      mobileController.text = mUserListEntity.data![mWhichPatient].patientPhone.toString();
      homeAddressController.text = mUserListEntity.data![mWhichPatient].homeAddress.toString();
      if(mUserListEntity.data![mWhichPatient].isDefault == 1) {
        switchSelected = true;
      } else {
        switchSelected = false;
      }

    }
  }

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _errorText = '';

  Future<void> _validateInputs() async {
    final FormState? form = _formKey.currentState;
    /*if (form!.validate()) {
      _errorText = '';
    } else {
      _errorText = '输入不能为空';
    }
    form.save();*/
    setState(() {
      if(relationship == "请选择与本人的关系") {
        _errorText = "请选择与本人的关系";
        return;
      } else if(passport == "请选择证件类型") {
        _errorText = "请选择证件类型";
        return null;
      } else if(previous == "请选择既往病史") {
        _errorText = "请选择既往病史";
        return;
      } else if(family == "请选择家族病史") {
        _errorText = "请选择家族病史";
        return;
      } else if(nameController.text == '') {
        _errorText = "请填写姓名";
        return;
      } else if(passportController.text == '') {
        _errorText = "请填写证件号码";
        return;
      } else if(mobileController.text == '') {
        _errorText = "请填写手机号码";
        return;
      } else if(selectedRadioValue == 1 && allergyController.text == '') {
        _errorText = "请填写过敏史";
        return;
      } else if(!Utils.validateIDCard(passportController.text)) {
        _errorText = "请输入正确的身份证号码";
        return;
      } else if(!Utils.isChinaPhoneLegal(mobileController.text)) {
        _errorText = "请输入正确的手机号码";
        return;
      } else {
        _errorText = "";
      }
    });
if(!_errorText.isEmpty) {
  return;
}
    print("${previous} ${family} ${allergyController.text} ");

    int passportType = 0;
    if(passport == "身份证") {
      passportType = 0;
    } else if(passport == "护照") {
      passportType = 1;
    } else if(passport == "港澳通行证") {
      passportType = 2;
    }

    int isDefault = 1;
    if(switchSelected) {
      isDefault = 1;
    } else {
      isDefault = 0;
    }

    String patientId = isEdit ? mUserListEntity.data![mWhichPatient].patientId.toString() : "";
    var params = {
      'patientId': patientId,
      'userRelationship': relationship,
      'documentType': passportType,
      'pastHistory': previous,
      'familyHistory': family,
      'patientName': nameController.text,
      'identificationCard': passportController.text,
      'patientPhone': mobileController.text,
      'allergyHistory': allergyController.text,
      'homeAddress': homeAddressController.text,
      'isDefault': isDefault,
    };

    print(params);

    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };
    var response = await http.post(Uri.parse(Global.BaseUrl + 'user'),
        body: jsonEncode(params), headers: headers);
    if(isEdit) {
      response = await http.put(Uri.parse(Global.BaseUrl + 'user'),
          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);
      NormalResponse3 mNormalResponse =
      new NormalResponse3.fromJson(jsonResponse);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast(isEdit ? "保存成功！" : "添加成功！", 2);
        Navigator.pop(context, "success");
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: new AppBar(
          title: new Text(isEdit ? '编辑就诊人' : '添加就诊人',
              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: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Column(children: [
              Padding(
                  padding: const EdgeInsets.all(10),
                  child: Text(
                    "请认真填写就诊人信息",
                    style: TextStyle(
                      color: Colors.orange,
                    ),
                  )),
              if (_errorText != null)
                Text(
                  "  " + _errorText + "  ",
                  style: TextStyle(color: Colors.white, backgroundColor: Colors.red),
                ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: GestureDetector(
                  onTap: () {
                    selectItem(selectItem0, 0);
                  },
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "关系",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text(
                                relationship,
                                style: TextStyle(
                                  color: Colors.black,
                                ),
                              ),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.grey,
                              ),
                            ])
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              // new Line(),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Container(
                  alignment: Alignment.center,
                  height: 45,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "姓名  ",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Expanded(
                          child: TextFormField(
                            maxLines: 1,
                            onSaved: (value) {},
                            textAlign: TextAlign.right,
                            controller: nameController,
                            inputFormatters: [
                              FilteringTextInputFormatter.singleLineFormatter,
                              LengthLimitingTextInputFormatter(4)
                            ],
                            decoration: const InputDecoration(
                              hintText: ('请填写姓名'),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 13,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: GestureDetector(
                  onTap: () {
                    // selectItem(['身份证', '护照', '港澳通行证'], 1);
                    selectItem(selectItem1, 1);
                  },
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "证件类型",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text(
                                passport,
                                style: TextStyle(
                                  color: Colors.black,
                                ),
                              ),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.grey,
                              ),
                            ])
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "证件号码",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Expanded(
                          child: TextFormField(
                            controller: passportController,
                            maxLines: 1,
                            onSaved: (value) {},
                            textAlign: TextAlign.right,
                            inputFormatters: [
                              FilteringTextInputFormatter.singleLineFormatter,
                              LengthLimitingTextInputFormatter(18)
                            ],
                            decoration: const InputDecoration(
                              hintText: ('请输入证件号码'),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 13,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: GestureDetector(
                  onTap: () {
                    selectItem(selectItem2, 2);
                  },
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "既往病史",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text(
                                previous,
                                style: TextStyle(
                                  color: Colors.black,
                                ),
                              ),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.grey,
                              ),
                            ])
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: GestureDetector(
                  onTap: () {
                    selectItem(selectItem3, 3);
                  },
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "家族病史",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text(
                                family,
                                style: TextStyle(
                                  color: Colors.black,
                                ),
                              ),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.grey,
                              ),
                            ])
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "过敏史",
                        style: TextStyle(
                          color: Colors.grey,
                        ),
                      ),
                      Row(
                        children: <Widget>[
                          Text("无"),
                          Radio(
                            value: 0,
                            onChanged: (value) {
                              setState(() {
                                allergyController.text = "";
                                this.selectedRadioValue = value!;
                              });
                            },
                            groupValue: selectedRadioValue,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Text("有"),
                          Radio(
                            value: 1,
                            onChanged: (value) {
                              setState(() {
                                this.selectedRadioValue = value!;
                              });
                            },
                            groupValue: selectedRadioValue,
                          ),
                        ],
                      ),
                    ]),
              ),
              Visibility(
                visible: this.selectedRadioValue == 1,
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Expanded(
                          child: TextFormField(
                            controller: allergyController,
                            maxLines: 1,
                            onSaved: (value) {},
                            textAlign: TextAlign.right,
                            inputFormatters: [
                              FilteringTextInputFormatter.singleLineFormatter,
                              LengthLimitingTextInputFormatter(18)
                            ],
                            decoration: const InputDecoration(
                              hintText: ('请填写过敏史'),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 13,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "手机号",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Expanded(
                          child: TextFormField(
                            enabled: mobileCanEdit,
                            controller: mobileController,
                            maxLines: 1,
                            onSaved: (value) {},
                            textAlign: TextAlign.right,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              LengthLimitingTextInputFormatter(11)
                            ],
                            decoration: const InputDecoration(
                              hintText: ('请输入手机号码'),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 13,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "就诊人地址",
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Expanded(
                          child: TextFormField(
                            controller: homeAddressController,
                            maxLines: 1,
                            onSaved: (value) {},
                            textAlign: TextAlign.right,
                            // inputFormatters: [
                            //   FilteringTextInputFormatter.digitsOnly,
                            //   LengthLimitingTextInputFormatter(11)
                            // ],
                            decoration: const InputDecoration(
                              hintText: ('选填'),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 13,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ]),
                ),
              ),
              Divider(
                color: Colors.grey,
                thickness: 1,
                indent: 10,
                endIndent: 10,
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "设为默认就诊人",
                        style: TextStyle(
                          color: Colors.grey,
                        ),
                      ),
                      CupertinoSwitch(
                        value: switchSelected,
                        onChanged: (value) {
                          setState(() {
                            switchSelected = value;
                          });
                        },
                      ),
                    ]),
              ),
              Center(
                child: 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: () {
                    _validateInputs();
                  },
                ),
              ),
            ]),
          ),
        ),
      ),
    );
  }

  selectItem(List list, int item) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          height: list.length * 50,
          child: Column(
            children: List.generate(
              list.length,
              (index) => GestureDetector(
                onTap: () {
                  setState(() {
                    switch (item) {
                      case 0:
                        relationship = list[index];
                        if(relationship == "本人") {
                          mobileCanEdit = false;
                          mobileController.text = Global.loginPhoneNo;
                        } else {
                          mobileCanEdit = true;
                          mobileController.text = "";
                        }
                        break;
                      case 1:
                        passport = list[index];
                        break;
                      case 2:
                        previous = list[index];
                        break;
                      case 3:
                        family = list[index];
                        break;
                    }
                  });
                  Navigator.pop(context);
                },
                child: Padding(
                  padding: const EdgeInsets.all(10),
                  child: Text(
                    '${list[index]}',
                    style: TextStyle(fontSize: 18),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
