import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_lib_business_components/index.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/managers/interfaces/language.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/age_text.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_measure/view/measure/measure_images_bar.dart';

///检查详情对话框界面
class InspectionDetailsDiaLog extends FStatelessWidget {
  ///检查记录编号
  final String recordCode;

  ///检查列表
  final GetRecordsPageDTO checkInfo;

  ///病人信息
  final PatientInfo patientInfo;
  final List<PatientInfoExt> patientInfoExts;
  final ScrollController _scrollController = ScrollController();
  final OrganizationPatientTypeEnum patientType;
  final languageConfigManager = Get.find<ILanguageConfigManager>();
  InspectionDetailsDiaLog({
    Key? key,
    required this.recordCode,
    required this.checkInfo,
    required this.patientInfo,
    required this.patientInfoExts,
    this.patientType = OrganizationPatientTypeEnum.Person,
  }) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      title: FText(
        i18nBook.remedical.examinationDetails.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      insetPadding: EdgeInsets.symmetric(vertical: 100),
      children: [
        FContainer(
          width: 800,
          child: _inspectionDetail(),
        ),
      ],
    );
  }

  FWidget _inspectionDetail() {
    return FContainer(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: FColumn(
        children: [
          FContainer(
            height: 45,
            padding: EdgeInsets.only(left: 25, right: 5),
            child: _buildInspectionPersonInfoTemplate(),
          ),
          FContainer(
            height: 45,
            padding: EdgeInsets.only(left: 25, right: 5),
            child: _buildInspectionTemplate(),
          ),
          FSizedBox(
            height: 10,
          ),
          if (ServerConfigManager.isScreenshot) ...[
            FContainer(
              height: 30,
              padding: EdgeInsets.only(left: 25, right: 5),
              margin: EdgeInsets.only(bottom: 20),
              child: _buildExaminingPhysician(),
            ),
            FSizedBox(
              height: 10,
            ),
            FContainer(
              height: 30,
              padding: EdgeInsets.only(left: 25, right: 5),
              margin: EdgeInsets.only(bottom: 20),
              child: _buildMedicalHistory(),
            ),
          ],
          FDivider(
            color: Colors.grey[400],
          ),
          FContainer(
            height: 30,
            padding: EdgeInsets.only(left: 25, right: 5),
            child: _buildInspectionDeviceInfo(),
          ),
          FContainer(
            padding: EdgeInsets.only(left: 25, right: 5),
            child: _builInspectionItemTemplate(),
          ),
          FContainer(
            height: 30,
            padding: EdgeInsets.only(left: 25, right: 5),
            margin: EdgeInsets.only(bottom: 20),
            child: _buildInspectionDoctorAndCreatorInfo(),
          ),
          FSizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }

  FWidget _buildInspectionTemplate() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FTitleField(
          i18nBook.remedical.time.t,
          FText('${DateFormat("yyyy-MM-dd HH:mm:ss").format(
            DateTime.fromMillisecondsSinceEpoch(
                DateTime.tryParse(checkInfo.createTime.toString())
                    ?.millisecondsSinceEpoch as int),
          )}'),
          sizeAfter: 80,
          maxLargeFieldWidth: 230,
          minLargeFieldWidth: 230,
        ),
        FTitleField(
          i18nBook.organization.department.t,
          FText('${checkInfo.deptName ?? i18nBook.homePage.notYet.t}'),
        ),
      ],
    );
  }

  FWidget _buildInspectionPersonInfoTemplate() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FTitleField(
          patientType == OrganizationPatientTypeEnum.Person
              ? i18nBook.common.fullName.t
              : i18nBook.remedical.petName.t,
          FText(
            '${patientInfo.name}',
            overflow: TextOverflow.ellipsis,
          ),
          sizeAfter: 80,
          maxLargeFieldWidth: 230,
          minLargeFieldWidth: 230,
        ),
        FTitleField(
          i18nBook.remedical.age.t,
          // 年龄变更
          AgeText(
            ageUnits: patientInfo.ageUnits,
            ageDay: patientInfo.ageDay,
            ageMonth: patientInfo.ageMonth,
            ageWeek: patientInfo.ageWeek,
            ageYear: patientInfo.ageYear,
          ),
          sizeAfter: 80,
        ),
        FTitleField(
          i18nBook.remedical.gender.t,
          FText(
            patientInfo.sex != null && patientInfo.sex != ''
                ? languageConfigManager.getExamLanguageValue(
                    patientInfo.sex ?? i18nBook.remedical.notFill.t)
                : i18nBook.remedical.notFill.t,
          ),
          sizeAfter: 0,
        ),
      ],
    );
  }

  FWidget _builInspectionItemTemplate() {
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 100 : 180,
          child: FText(
            i18nBook.remedical.checkItem.t,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ),
        FExpanded(
          child: FListView.builder(
            shrinkWrap: true,
            itemCount: patientInfoExts.length,
            itemBuilder: (BuildContext context, int index) {
              return FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  FContainer(
                    // height: 30,
                    child: FRow(
                      children: [
                        FText(
                          '${languageConfigManager.getExamLanguageValue(patientInfoExts[index].patientScanType ?? '')}',
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  FSizedBox(
                    height: 10,
                  ),
                  FAlwaysScrollListView(
                    scrollController: _scrollController,
                    child: QuickFWidget(ScrollConfiguration(
                      behavior: ScrollConfiguration.of(context)
                          .copyWith(scrollbars: false),
                      child: FListView.builder(
                        shrinkWrap: true,
                        controller: _scrollController,
                        itemCount: patientInfoExts[index].content?.length,
                        itemBuilder: (BuildContext context, int index1) {
                          String displayValue = patientInfoExts[index]
                                      .content?[index1]
                                      .key ==
                                  'GestationalAgeOrigin'
                              ? languageConfigManager.getExamLanguageValue(
                                  patientInfoExts[index]
                                          .content?[index1]
                                          .value ??
                                      '')
                              : patientInfoExts[index].content?[index1].value ??
                                  i18nBook.remedical.notFill.t;
                          if (isValidDateTime(displayValue)) {
                            // 使用与日期字符串相匹配的格式
                            DateFormat format =
                                DateFormat('MM/dd/yyyy h:mm:ss a');
                            // 解析字符串为DateTime对象
                            DateTime dateTime =
                                format.parse(displayValue, true).toLocal();
                            DateFormat newFormat =
                                DateFormat('MM/dd/yyyy h:mm:ss a');
                            displayValue = newFormat.format(dateTime);
                          }
                          return FContainer(
                            // height: 30,
                            child: FContainer(
                              margin: EdgeInsets.only(bottom: 5),
                              child: FRow(
                                children: [
                                  FContainer(
                                    width: 150,
                                    child: FText(
                                      '${languageConfigManager.getExamLanguageValue(patientInfoExts[index].content?[index1].key ?? '')}',
                                      style: TextStyle(
                                        fontSize: 15,
                                      ),
                                    ),
                                  ),
                                  FText(displayValue)
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    )),
                  ),
                  FSizedBox(
                    height: 10,
                  ),
                  FSizedBox(
                    height: 0.5,
                    child: FContainer(
                      color: Color.fromRGBO(151, 151, 151, 1),
                    ),
                  ),
                  FSizedBox(
                    height: 10,
                  ),
                ],
              );
            },
          ),
        ),
      ],
    );
  }

  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 _buildInspectionDoctorAndCreatorInfo() {
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 100 : 180,
          child: FText(
            i18nBook.remedical.checkDoctor.t,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ),
        FExpanded(
          child: FContainer(
            child: FText(
              '${checkInfo.creatorName != null ? checkInfo.creatorName : i18nBook.homePage.notYet.t}',
              style: TextStyle(
                fontSize: 15,
              ),
            ),
          ),
        )
      ],
    );
  }

  FWidget _buildInspectionDeviceInfo() {
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 100 : 180,
          child: FText(
            i18nBook.remedical.deliveryDevice.t,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ),
        FExpanded(
          child: FContainer(
            child: FText(
              '${checkInfo.displayName ?? i18nBook.remedical.notFill.t}',
              style: TextStyle(
                fontSize: 15,
              ),
            ),
          ),
        )
      ],
    );
  }

  FWidget _buildExaminingPhysician() {
    return FTitleField(
      i18nBook.remedical.checkDoctor.t,
      FText(patientInfo.examiningPhysician ?? i18nBook.remedical.notFill.t),
      sizeAfter: 80,
      maxLargeFieldWidth: 230,
      minLargeFieldWidth: 230,
    );
  }

  FWidget _buildMedicalHistory() {
    return FTitleField(
      i18nBook.common.medicalHistory.t,
      FText(patientInfo.medicalHistory ?? i18nBook.remedical.notFill.t),
      sizeAfter: 80,
      maxLargeFieldWidth: 460,
      minLargeFieldWidth: 460,
    );
  }
}
