import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/app_parameters.dart';
import 'package:vitalapp/architecture/utils/datetime.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/architecture/values/features.dart';
import 'package:vitalapp/components/cell.dart';
import 'package:vitalapp/components/dialog_date.dart';
import 'package:vitalapp/components/dialog_input.dart';
import 'package:vitalapp/components/dialog_label_select.dart';
import 'package:vitalapp/components/dialog_select.dart';
import 'package:vitalapp/consts/nations.dart';
import 'package:vitalapp/consts/rpc_enum_labels.dart';
import 'package:vitalapp/helper/id_card_helper.dart';
import 'package:vitalapp/managers/interfaces/label.dart';
import 'package:vitalapp/pages/patient_info/widgets/health_infos.dart';
import 'package:vitalapp/store/store.dart';

import 'controller.dart';
import 'widgets/detail_infos.dart';

class PatientInfomationPage extends GetView<PatientInfomationController> {
  final bool isNeedSyncAddressCheck;
  final bool isCanEditId;
  final bool isRequiredName;
  final bool isRequiredCard;
  PatientInfomationPage({
    this.isNeedSyncAddressCheck = false,
    this.isCanEditId = false,
    this.isRequiredName = false,
    this.isRequiredCard = false,
  });

  @override
  Widget build(BuildContext context) {
    return VListFormCellGroup(
      children: [
        VListFormCellGroup(
          formTitle: "基本信息",
          children: _buildBaseInfo(context),
        ),
        DetailInfomations(),
        HealthInfomations(),
      ],
    );
  }

  List<Widget> _buildBaseInfo(BuildContext context) {
    final state = controller.state;

    return [
      Obx(
        () => VListFormCell(
          label: "姓名",
          content: controller.state.name,
          isRequired: isRequiredName,
          onTap: () async {
            final result = await VDialogInput(
              title: "姓名",
              initialValue: controller.state.name,
              placeholder: "请填写姓名",
            ).show();
            if (result != null) {
              controller.state.name = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "证件号",
          content: controller.state.cardNo,
          isRequired: isRequiredCard,
          onTap: () async {
            if (isCanEditId) {
              print("点击修改证件号");
              final result = await VDialogInput(
                title: "证件号",
                initialValue: controller.state.cardNo,
                placeholder: "请填写证件号",
                onConfirmVerification: (v) {
                  bool isValid = IdCardHelper.validateIDCard(v);
                  if (!isValid) {
                    PromptBox.showToast("请填写正确的证件号",
                        toastPosition: EasyLoadingToastPosition.top);
                  }
                  return isValid;
                },
                showCancel: true,
              ).show();
              if (result != null && result is String) {
                final passed =
                    await controller.onCardNoChanged(result.toUpperCase());
                if (passed) {
                  await controller
                      .checkOfflinePatientExists(result.toUpperCase());
                }
              }
            }
          },
          endIcon: _buildEndIcon(isEdit: isCanEditId),
        ),
      ),
      if (Store.user.hasFeature(FeatureKeys.CrowdClassification)) ...[
        Obx(
          () => VListFormCell(
            label: "人群分类",
            content: controller.state.labels.join("、"),
            onTap: () async {
              var allLabels = await Get.find<ILabelManager>().getAllLabels();
              final result = await Get.dialog(
                VDialogLabelSelect(
                  selectedLabels: controller.state.labels,
                  allLabels: allLabels,
                ),
              );
              var selectedLabels = result as List<String>;
              controller.state.labels = selectedLabels;
            },
            endIcon: _buildEndIcon(),
          ),
        ),
      ],
      Obx(
        () => VListFormCell(
          label: "联系电话",
          content: controller.state.phoneNo,
          onTap: () async {
            final result = await VDialogInput(
              title: "联系电话",
              initialValue: controller.state.phoneNo,
              placeholder: "请填写联系电话",
              showCancel: true,
              onConfirmVerification: (v) {
                var isValid = (v.length == 11 && IdCardHelper.isNumeric(v));
                if (!isValid) {
                  PromptBox.showToast("请填写正确的联系电话",
                      toastPosition: EasyLoadingToastPosition.top);
                }
                return isValid;
              },
            ).show();
            if (result != null) {
              controller.state.phoneNo = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "联系人姓名",
          content: controller.state.emergencyName,
          onTap: () async {
            final result = await VDialogInput(
              title: "联系人姓名",
              initialValue: controller.state.emergencyName,
              placeholder: "请填写联系人姓名",
            ).show();
            if (result != null) {
              controller.state.emergencyName = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "联系人电话",
          content: controller.state.emergencyPhone,
          onTap: () async {
            final result = await VDialogInput(
              title: "联系人电话",
              initialValue: controller.state.emergencyPhone,
              placeholder: "请填写联系人电话",
              showCancel: true,
              onConfirmVerification: (v) {
                var isValid = (v.length == 11 && IdCardHelper.isNumeric(v));
                if (!isValid) {
                  PromptBox.showToast("请填写正确的联系人电话",
                      toastPosition: EasyLoadingToastPosition.top);
                }
                return isValid;
              },
            ).show();
            if (result != null) {
              controller.state.emergencyPhone = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "性别",
          content: RpcEnumLabels.gender[state.gender],
          onTap: () async {
            final result = await VDialogSelect<GenderEnum, GenderEnum>(
              title: "选择性别",
              source: const [
                GenderEnum.Male,
                GenderEnum.Female,
                GenderEnum.Unknown,
                GenderEnum.Unspecified
              ],
              valueGetter: (data) => data,
              labelGetter: (data) => RpcEnumLabels.gender[data] ?? "",
              initialValue: state.gender,
            ).show();
            if (result != null) {
              controller.state.gender = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "民族",
          content: state.nation,
          onTap: () async {
            final result = await VDialogSelect<String, String>(
              title: "选择民族",
              source: Nations.china,
              valueGetter: (data) => data,
              labelGetter: (data) => data,
              initialValue: state.nation.contains("族")
                  ? state.nation
                  : "${state.nation}族",
            ).show();
            if (result != null) {
              controller.state.nation = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "出生日期",
          content: controller.state.birthday != null
              ? DataTimeUtils.formatDateString(controller.state.birthday!)
              : "",
          onTap: () async {
            bool _isLocalStation = AppParameters.data.isLocalStation;
            DateTime? result;
            if (kIsWeb || _isLocalStation) {
              result = await showDatePicker(
                context: context,
                initialDate: controller.state.birthday ?? DateTime.now(),
                firstDate: DateTime(1900),
                lastDate: DateTime.now(),
              );
            } else {
              result = await VDialogDate(
                title: "设置出生日期",
                initialValue: controller.state.birthday,
                maxValue: DateTime.now(),
              ).show();
            }
            if (result != null) {
              controller.state.birthday = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "年龄",
          content: controller.state.age,
          endIcon: _buildEndIcon(isEdit: false),
          onTap: () {},
        ),
      ),
      if (isNeedSyncAddressCheck)
        Obx(
          () => VListFormCell(
            label: "同步户籍地址到现住地址",
            labelWidth: 250,
            contentWidget: Container(
              child: Switch(
                onChanged: (value) {
                  controller.onSyncAddressCheckChanged(value);
                },
                value: controller.state.isSyncAddresses,
              ),
            ),
          ),
        ),
      Obx(
        () => VListFormCell(
          label: "户籍地址",
          content: controller.state.permanentResidenceAddress,
          onTap: () async {
            final result = await VDialogInput(
              title: "户籍地址",
              initialValue: controller.state.permanentResidenceAddress,
              placeholder: "请填写户籍地址",
            ).show();
            if (result != null) {
              controller.state.permanentResidenceAddress = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "现住地址",
          content: controller.state.address,
          onTap: () async {
            final result = await VDialogInput(
              title: "现住地址",
              initialValue: controller.state.address,
              placeholder: "请填写现住地址",
            ).show();
            if (result != null) {
              controller.state.address = result;
            }
          },
          endIcon: _buildEndIcon(),
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "建档单位",
          content: controller.state.createdOrgName,
          endIcon: _buildEndIcon(isEdit: false),
          onTap: () {},
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "建档人",
          content: controller.state.createdDoctorName,
          endIcon: _buildEndIcon(isEdit: false),
          onTap: () {},
        ),
      ),
      Obx(
        () => VListFormCell(
          label: "建档时间",
          content: controller.state.createTime,
          endIcon: _buildEndIcon(isEdit: false),
          onTap: () {},
        ),
      ),
    ];
  }

  Widget _buildEndIcon({bool isEdit = true}) {
    return Container(
      margin: EdgeInsets.only(left: isEdit ? 15 : 35),
      child: isEdit ? Icon(Icons.edit_outlined) : SizedBox(),
    );
  }
}