import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/functional/popup_menu_button.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:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

///检查病例手机端APPbar
class ExamRecordsMobileAppbar extends StatelessWidget
    implements PreferredSizeWidget, FPage {
  ExamRecordsMobileAppbar({
    this.title,
    this.controller,
    // this.isSingle = false,
    this.status = RecordStatusEnum.NotScanned,
    this.isReferral = false,
    this.referralStatus = ReferralStatusEnum.Wait,
    this.pageName = 'ExamRecordsMobileAppbar',
    Key? key,
  }) : super(key: key);
  //标题
  final FWidget? title;
  //诊断控制器
  final ConsultationController? controller;
  //是否单个检查病例
  // final bool isSingle;

  ///检查状态
  final RecordStatusEnum status;

  /// 是否是转诊病人
  final bool? isReferral;

  /// 转诊状态
  final ReferralStatusEnum? referralStatus;

  @override
  final String pageName;

  @override
  FWidget build(BuildContext context) {
    /// 转诊病人可以写报告的状态判断
    bool isReferralCanWriteReport = !isReferral! ||
        (isReferral! && referralStatus == ReferralStatusEnum.Accepted);
    bool isCanWriteReport =
        (controller?.state.examRecord.canCreateReport ?? false) ||
            ([RecordStatusEnum.Uploaded, RecordStatusEnum.NotReport]
                .contains(status));
    return FAppBar(
      backgroundColor: FTheme.ins.colorScheme.primary,
      elevation: 0,
      automaticallyImplyLeading: false,
      foregroundColor: Colors.white,
      titleSpacing: title == null ? 24 : 21,
      title: title,
      // actions: isSingle
      //     ? null
      //     : [
      //         FPopupMenuButton<String>(
      //           itemBuilder: ((context) => <PopupMenuItem<String>>[
      //                 this.selectView(
      //                   FIcons.scan_image,
      //                   i18nBook.remedical.scanImage.t,
      //                   'A',
      //                 ),
      //                 this.selectView(
      //                   FIcons.view_report,
      //                   i18nBook.remedical.viewReport.t,
      //                   'B',
      //                 ),
      //                 if (isCanWriteReport && isReferralCanWriteReport)
      //                   this.selectView(
      //                     FIcons.edit,
      //                     i18nBook.remedical.writeReport.t,
      //                     'C',
      //                   ),
      //               ]),
      //           onSelected: (String action) async {
      //             switch (action) {
      //               case 'A':
      //                 controller!.openCloudImage();
      //                 break;
      //               case 'B':
      //                 controller!.viewReport();
      //                 break;
      //               case 'C':
      //                 await controller!.writeReport();
      //                 break;
      //             }
      //           },
      //         ),
      //       ],
      centerTitle: true,
      leading: FIconButton(
        name: "back",
        icon: FIcon(
          Icons.arrow_back_ios_new,
          size: 20,
          color: Colors.white,
        ),
        onPressed: () {
          Get.back();
        },
        businessParent: this,
      ),
    );
  }

// 返回每个隐藏的菜单项
  selectView(IconData icon, String text, String id) {
    return new PopupMenuItem<String>(
      value: id,
      child: new FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <FWidget>[
          new FIcon(icon, color: FTheme.ins.colorScheme.primary),
          new FText(text),
        ],
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

/// 单行文本框
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),
        FContainer(
          width: expand ? width - 30 : width / 2 + 5,
          alignment: Alignment.centerLeft,
          child: FText(
            value,
            maxLines: 1,
          ),
        ),
      ],
    ),
  );
}

/// 单行文本框
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: 5),
        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: 30, top: 10),
    child: FRow(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        FExpanded(
          flex: 1,
          child: FContainer(
            height: 40,
            alignment: Alignment.centerLeft,
            child: FText(
              key,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        const FSizedBox(width: 20),
        FExpanded(
          flex: 3,
          child: FContainer(
            alignment: Alignment.centerLeft,
            child: widget,
          ),
        ),
      ],
    ),
  );
}

/// 检查列表
FWidget buildExamRecords(
    GetRecordsPageDTO examRecord,
    ConsultationController controller,
    ScrollController scrollController,
    String name,
    PatientInfo patientInfo,
    String sex,
    BuildContext context) {
  return FFlex(
    direction: Axis.vertical,
    children: [
      FExpanded(
        flex: 2,
        child: 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,
            ),
          ),
        ),
      ),
      FExpanded(
        flex: 7,
        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,
                ),
              ),
              const FSizedBox(height: 10),
              buildKeyWidget(
                i18nBook.remedical.checkItem.t,
                FSizedBox(),
              ),
              const FSizedBox(height: 10),
              FExpanded(
                child: FContainer(
                  width: double.infinity,
                  margin: EdgeInsets.only(left: 40),
                  child: FListView.builder(
                    itemCount: controller.state.checkInfoLists.length,
                    itemBuilder: (_, i) => FContainer(
                      child: _buildCheckInfos(
                          scrollController, i, controller, context),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      _buildCheckDoctorArea(examRecord)
    ],
  );
}

FWidget _buildCheckInfos(ScrollController scrollController, int i,
    ConsultationController controller, BuildContext context) {
  return FObx(() {
    final checkInfos = controller.state.checkInfoLists;
    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,
                ],
              );
            } else if (index == checkInfos[i].content!.length - 1 &&
                checkInfos.length > 1) {
              return FColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  row,
                  const FSizedBox(height: 5),
                  FPadding(
                    padding: EdgeInsets.only(right: 40),
                    child: FDivider(
                      height: 1,
                      thickness: 1,
                      color: Colors.grey.shade400,
                    ),
                  )
                ],
              );
            } else {
              return row;
            }
          },
        ),
      )),
    );
  });
}

FWidget _buildCheckDoctorArea(GetRecordsPageDTO 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.topCenter,
          child: FText(_generatorDoc(examRecord)),
        ),
      ),
    ),
  );
}

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

List<FWidget> _buildRecordInfoTemplate(
  String name,
  PatientInfo patientInfo,
  String sex,
  GetRecordsPageDTO examRecord,
) {
  return [
    buildKeyValue(
      i18nBook.common.fullName.t,
      name,
    ),
    // 年龄变更
    buildAgeKeyValue(
      i18nBook.remedical.age.t,
      AgeText(
        ageUnits: patientInfo.ageUnits,
        ageDay: patientInfo.ageDay,
        ageMonth: patientInfo.ageMonth,
        ageWeek: patientInfo.ageWeek,
        ageYear: patientInfo.ageYear,
      ),
    ),
    buildKeyValue(
      i18nBook.organization.department.t,
      examRecord.deptName ?? i18nBook.remedical.notFill.t,
    ),
    buildKeyValue(
      i18nBook.remedical.gender.t,
      sex,
    ),
    buildKeyValue(
      i18nBook.remedical.time.t,
      examRecord.createTime == null
          ? i18nBook.remedical.notFill.t
          : DateFormat("yyyy-MM-dd").format(
              DateTime.fromMillisecondsSinceEpoch(
                DateTime.tryParse(
                  examRecord.createTime.toString(),
                )?.millisecondsSinceEpoch as int,
              ),
            ),
      expand: true,
    )
  ];
}

FWidget _buildContainer(String value) {
  return FContainer(
    height: 30,
    alignment: Alignment.centerLeft,
    child: FText(
      value,
      maxLines: 1,
    ),
  );
}
