import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/age_text.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_jsonrpc/rpc.dart';
import '../../controller.dart';
import 'package:fis_common/index.dart';

class RecordDetailPage extends FisView<ConsultationRecordViewController>
    implements FPage {
  @override
  String get pageName => "RecordDetailPage";

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      backgroundColor: Colors.white,
      appBar: FAppBar(
        title: FText(
          i18nBook.notification.detail.t,
          style: TextStyle(
              fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
        ),
        elevation: 0,
        centerTitle: true,
        leading: FIconButton(
          name: "back",
          businessParent: this,
          icon: FIcon(Icons.arrow_back_ios_new, size: 20, color: Colors.white),
          onPressed: () {
            Get.back();
          },
        ),
        actions: [
          if (controller.isCanDelete)
            FIconButton(
              name: "delete",
              businessParent: this,
              icon: FIcon(Icons.delete, size: 20, color: Colors.white),
              onPressed: () async {
                bool isDeleted = await controller.deleteRecord(
                    controller.mobileDetailPageRecordCode, this);
                if (isDeleted) {
                  Get.back();
                }
                // print(isDeleted);
              },
            ),
        ],
      ),
      body: _Body(),
    );
  }
}

class _Body extends FisView<ConsultationRecordViewController> {
  final Map parameters = Get.parameters;

  @override
  FWidget build(BuildContext context) {
    ScrollController scrollController = ScrollController();
    return FContainer(
      width: double.infinity,
      decoration: new BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            8.0,
          ),
        ), //圆角弧度
        border: new Border.all(
          width: 1,
          color: Colors.white,
        ),
      ),
      margin: EdgeInsets.symmetric(
        horizontal: 10,
        vertical: 20,
      ),
      child: buildExamRecords(
        scrollController,
        controller.currSelectPatientInfo.name ?? '',
        controller.getValues(controller.currSelectPatientInfo.sex ?? ''),
        context,
      ),
    );
  }

  /// 检查列表
  FWidget buildExamRecords(ScrollController scrollController, String name,
      String sex, BuildContext context) {
    if (sex.isEmpty) {
      sex = i18nBook.remedical.notFill.t;
    }
    final List<PatientInfoExt> checkInfos =
        controller.checkInfo!.patientInfoExtList ?? [];
    final examRecord = controller.checkInfo!;
    final patientInfo = controller.currSelectPatientInfo;
    var checkItem = buildKeyWidget(
      i18nBook.remedical.checkItem.t,
      FSizedBox(),
    );
    return FFlex(
      direction: Axis.vertical,
      children: [
        FContainer(
          padding: EdgeInsets.only(left: 10),
          width: double.infinity,
          alignment: Alignment.center,
          decoration: new BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.0),
              topRight: Radius.circular(8.0),
            ), //圆角弧度
            border: new Border.all(
              width: 1,
              color: Colors.white,
            ),
            color: Colors.white,
          ),
          child: FWrap(
            runAlignment: WrapAlignment.center,
            runSpacing: 10,
            spacing: 15,
            crossAlignment: WrapCrossAlignment.center,
            children: _buildRecordInfoTemplate(
              name,
              patientInfo,
              sex,
              examRecord,
            ),
          ),
        ),
        _horizontalDivider(),
        FExpanded(
          child: FContainer(
            alignment: Alignment.centerLeft,
            width: double.infinity,
            margin: EdgeInsets.only(top: 2, bottom: 2),
            decoration: new BoxDecoration(
              border: new Border.all(
                width: 1,
                color: Colors.white,
              ),
              color: Colors.white,
            ),
            child: FColumn(
              children: [
                buildKeyWidget(
                  i18nBook.remedical.deliveryDevice.t,
                  _buildContainer(
                    examRecord.displayName ?? i18nBook.homePage.notYet.t,
                  ),
                ),
                _buildCheckDoctorArea(examRecord),
                _horizontalDivider(),
                if (checkInfos.isEmpty) ...[
                  buildKeyWidget(
                    i18nBook.remedical.checkItem.t,
                    _buildContainer(
                      i18nBook.remedical.notFill.t,
                    ),
                  ),
                ] else ...[
                  checkItem,
                ],
                FExpanded(
                  child: FContainer(
                    width: double.infinity,
                    margin: EdgeInsets.only(left: 40),
                    child: FListView.builder(
                      itemCount: checkInfos.length,
                      itemBuilder: (_, i) => FContainer(
                        child: _buildCheckInfos(
                            scrollController, checkInfos, i, context),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  FWidget _buildCheckInfos(ScrollController scrollController,
      List<PatientInfoExt> checkInfos, int i, BuildContext context) {
    return FAlwaysScrollListView(
      scrollController: scrollController,
      child: QuickFWidget(ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: FListView.builder(
          shrinkWrap: true,
          controller: scrollController,
          itemCount: checkInfos[i].content!.length,
          itemBuilder: (BuildContext context, int index) {
            final row = FRow(
              children: [
                FExpanded(
                  child: _buildContainer(
                    controller.getValues(
                      checkInfos[i].content![index].key ??
                          i18nBook.remedical.notFill.t,
                    ),
                  ),
                ),
                const FSizedBox(width: 10),
                FExpanded(
                  child: _buildContainer(
                    checkInfos[i].content == null
                        ? i18nBook.remedical.notFill.t
                        : checkInfos[i].content![index].value ??
                            i18nBook.remedical.notFill.t,
                  ),
                ),
              ],
            );
            if (index == 0) {
              return FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  FText(
                    controller.getValues(
                      checkInfos[i].patientScanType!,
                    ),
                    style: TextStyle(
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                  const FSizedBox(height: 5),
                  row,
                  _horizontalDivider(),
                ],
              );
            } else if (index == checkInfos[i].content!.length - 1 &&
                checkInfos.length > 1) {
              return FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  row,
                  const FSizedBox(height: 5),
                ],
              );
            } else {
              return FColumn(
                children: [
                  row,
                  _horizontalDivider(),
                ],
              );
            }
          },
        ),
      )),
    );
  }

  FWidget _horizontalDivider() {
    return FPadding(
      padding: EdgeInsets.symmetric(horizontal: 0, vertical: 5),
      child: FDivider(
        height: 1,
        thickness: 1,
        color: Colors.grey.shade400,
      ),
    );
  }

  FWidget _buildCheckDoctorArea(QueryRecordResult examRecord) {
    return FContainer(
      height: 50,
      width: double.infinity,
      decoration: new BoxDecoration(
        border: new Border.all(
          width: 1,
          color: Colors.white,
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(8.0),
          bottomRight: Radius.circular(8.0),
        ),
        color: Colors.white,
      ),
      child: FContainer(
        alignment: Alignment.topCenter,
        child: buildKeyWidget(
          i18nBook.remedical.checkDoctor.t,
          FContainer(
            height: 30,
            alignment: Alignment.centerLeft,
            child: FText(_generatorDoc(examRecord)),
          ),
        ),
      ),
    );
  }

  String _generatorDoc(QueryRecordResult? examRecord) {
    return '${examRecord?.creatorName != null ? examRecord?.creatorName : i18nBook.homePage.notYet.t}';
  }

  List<FWidget> _buildRecordInfoTemplate(
    String name,
    PatientInfo patientInfo,
    String sex,
    QueryRecordResult examRecord,
  ) {
    String patientId = parameters['devicePatientID'] ?? '';
    var createTime = examRecord.createTime?.toLocal();
    var defaultTime = DateTime.utc(0001, 01, 01, 00, 00, 00, 00);
    if (examRecord.examTime != null && examRecord.examTime != defaultTime) {
      createTime = examRecord.examTime!.toLocal();
    }
    return [
      buildKeyValue(
        i18nBook.common.fullName.t,
        name,
        expand: true,
      ),

      buildKeyValue(
        i18nBook.organization.department.t,
        examRecord.deptName ?? i18nBook.remedical.notFill.t,
        expand: true,
      ),
      // 年龄变更
      buildAgeKeyValue(
        i18nBook.remedical.age.t,
        AgeText(
          ageUnits: patientInfo.ageUnits,
          ageDay: patientInfo.ageDay,
          ageMonth: patientInfo.ageMonth,
          ageWeek: patientInfo.ageWeek,
          ageYear: patientInfo.ageYear,
        ),
      ),
      buildKeyValue(
        i18nBook.remedical.gender.t,
        sex,
      ),
      buildKeyValue(
        i18nBook.remedical.time.t,
        createTime == null
            ? i18nBook.remedical.notFill.t
            : DateFormat("yyyy-MM-dd HH:mm:ss").format(
                DateTime.fromMillisecondsSinceEpoch(
                  DateTime.tryParse(
                    createTime.toString(),
                  )?.millisecondsSinceEpoch as int,
                ),
              ),
        expand: true,
      ),
      buildKeyValue(
        "ID",
        patientId.isNullOrEmpty ? i18nBook.remedical.notFill.t : patientId,
        expand: true,
      )
    ];
  }

  FWidget _buildContainer(String value) {
    String displayValue = value;
    if (isValidDateTime(value)) {
      // 使用与日期字符串相匹配的格式
      DateFormat format = DateFormat('MM/dd/yyyy h:mm:ss a');
      // 解析字符串为DateTime对象
      DateTime dateTime = format.parse(value, true).toLocal();
      DateFormat newFormat = DateFormat('MM/dd/yyyy h:mm:ss a');
      displayValue = newFormat.format(dateTime);
    }
    return FContainer(
      height: 40,
      alignment: Alignment.centerLeft,
      child: FText(
        displayValue,
        maxLines: 3,
      ),
    );
  }

  bool isValidDateTime(String input) {
    String pattern =
        r'^(\d{1,2})\/(\d{1,2})\/(\d{4})\s(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])\s(AM|PM)$';
    RegExp regExp = RegExp(pattern);
    return regExp.hasMatch(input);
  }

  /// 单行文本框
  FWidget buildKeyValue(String key, String value, {bool expand = false}) {
    final width = MediaQuery.of(Get.context!).size.width / 2 - 30;
    return FContainer(
      width: expand ? width * 2 : width,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            width: width / 2 - 15,
            alignment: Alignment.centerLeft,
            child: FText(
              key,
              maxLines: 1,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const FSizedBox(width: 10),
          if (expand) ...[
            FExpanded(
              child: FText(
                value,
                maxLines: 3,
              ),
            ),
          ] else ...[
            FContainer(
              width: width / 2 + 5,
              alignment: Alignment.centerLeft,
              child: FText(
                value,
                maxLines: 3,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 单行文本框
  FWidget buildAgeKeyValue(String key, FWidget value, {bool expand = false}) {
    final width = MediaQuery.of(Get.context!).size.width / 2 - 30;
    return FContainer(
      width: expand ? width * 2 : width,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            width: width / 2 - 15,
            alignment: Alignment.centerLeft,
            child: FText(
              key,
              maxLines: 1,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const FSizedBox(width: 10),
          FContainer(
            width: expand ? width - 30 : width / 2 + 5,
            alignment: Alignment.centerLeft,
            child: value,
          ),
        ],
      ),
    );
  }

  /// 单行组件
  FWidget buildKeyWidget(String key, FWidget widget) {
    return FContainer(
      margin: EdgeInsets.only(left: 20, top: 10),
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FExpanded(
            flex: 5,
            child: FContainer(
              height: 40,
              alignment: Alignment.centerLeft,
              child: FText(
                key,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const FSizedBox(width: 20),
          FExpanded(
            flex: 7,
            child: FContainer(
              alignment: Alignment.centerLeft,
              child: widget,
            ),
          ),
        ],
      ),
    );
  }
}
