import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/inspection_record_card.dart';
import 'package:get/get.dart';

import 'exam_record_util.dart';

/// 检查记录
class ExamRecord extends FisView<ConsultationController>
    implements FInteractiveContainer {
  ///是否仅显示一条记录
  final bool isSingle;

  @override
  final String pageName;

  ExamRecord({this.isSingle = false, this.pageName = 'ExamRecord', Key? key})
      : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(isSingle, this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

class _DesktopLayout extends FisView<ConsultationController>
    implements FWidget {
  ///父级节点
  final FInteractiveContainer businessParent;
  final reportManager = Get.find<IReportManager>();
  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FObx(
      () {
        return FContainer(
          color: Colors.white,
          child: FColumn(
            children: [
              controller.state.checkLists.length == 0
                  ? FContainer(
                      margin: EdgeInsets.only(top: 80),
                      child: FColumn(
                        children: [
                          FCenter(
                            child: FImage.asset(
                              "assets/images/no_data.png",
                              width: 300,
                              height: 300,
                              fit: BoxFit.cover,
                            ),
                          ),
                          FText(i18nBook.common.noneDataTip.t),
                        ],
                      ),
                    )
                  : FExpanded(
                      child: FAlwaysScrollListView(
                        scrollController: controller.checkRecordController,
                        child: QuickFWidget(ScrollConfiguration(
                          behavior: ScrollConfiguration.of(context)
                              .copyWith(scrollbars: false),
                          child: FListView.builder(
                            shrinkWrap: true,
                            itemCount: controller.state.checkLists.length,
                            controller: controller.checkRecordController,
                            itemBuilder: (context, index) {
                              return FObx(() {
                                var checkItem =
                                    controller.state.checkLists[index];
                                return BuildCheckRecordCard(
                                  canCreateReport: checkItem.canCreateReport,
                                  time: reportManager.getTime(
                                    checkItem.createTime.toString(),
                                  ),
                                  distributionEquipment:
                                      checkItem.displayName ??
                                          i18nBook.homePage.notYet.t,
                                  department: checkItem.deptName ??
                                      i18nBook.homePage.notYet.t,
                                  examiningDoctor: checkItem.creatorName != null
                                      ? checkItem.creatorName
                                      : i18nBook.homePage.notYet.t,
                                  reportsNum:
                                      int.parse(checkItem.reportNum ?? ""),
                                  recordCode: checkItem.recordCode ??
                                      i18nBook.homePage.notYet.t,
                                  recordStatus: checkItem.recordStatus,
                                  remedicalList: checkItem.remedicalList,
                                  diagnosisInfos: checkItem.diagnosisInfos,
                                  index: index,
                                  isReferral: checkItem.isReferral,
                                  referralStatus: checkItem.referralStatus,
                                  deviceCode: checkItem.deviceCode,
                                  canStartImgCollecting:
                                      checkItem.canCollcetImg,
                                );
                              });
                            },
                          ),
                        )),
                      ),
                    )
            ],
          ),
        );
      },
    );
  }
}

class _MobileLayout extends StatefulWidget implements FWidget {
  final bool isSingle;

  ///父级节点
  final FInteractiveContainer businessParent;
  _MobileLayout(this.isSingle, this.businessParent);
  @override
  State<StatefulWidget> createState() {
    return _MobileLayoutState();
  }
}

class _MobileLayoutState extends State<_MobileLayout> {
  late ConsultationController controller;
  late GetRecordsPageDTO _examRecord;
  late int _totalCount = 0;
  late PreferredSizeWidget _appBar;
  int _currentCount = 1;
  bool _isSingle = false;

  @override
  void initState() {
    controller = Get.find<ConsultationController>();
    _isSingle = widget.isSingle;
    if (_isSingle) {
      final recordCode = controller.state
              .imageScanned[controller.state.imageScannedIndex].recordCode ??
          '';
      _examRecord = controller.state.checkLists
          .firstWhere((element) => element.recordCode == recordCode);
      controller.state.examRecord = _examRecord;
    } else {
      _examRecord = controller.state.examRecord;

      _totalCount = controller.state.recordCount;
    }
    _appBar = _buildAppBar();
    controller.onstatusChange.addListener((sender, e) => onStatusChanged(e));
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    var patientInfo =
        controller.state.patientInfos[controller.state.selectPatientCardIndex];
    ScrollController scrollController = new ScrollController();
    var name = patientInfo.name;
    if (name == null || name == '') {
      name = i18nBook.remedical.notFill.t;
    }
    var age = patientInfo.age;
    if (age == null || age == '') {
      age = i18nBook.remedical.notFill.t;
    }
    var sex = patientInfo.sex;
    if (sex == null || sex == '') {
      sex = i18nBook.remedical.notFill.t;
    } else {
      sex = controller.getValues(sex);
    }

    return FObx(() {
      return FScaffold(
        appBar: _appBar,
        backgroundColor: Colors.grey.shade200,
        body: 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(
              _examRecord,
              controller,
              scrollController,
              name ?? '',
              patientInfo,
              sex ?? i18nBook.remedical.notFill.t,
              context),
        ),
        bottomNavigationBar: _isSingle ? null : _buildExamRecordOperationArea(),
      );
    });
  }

  FWidget _buildExamRecordOperationArea() {
    return FRow(
      children: [
        FExpanded(
          flex: 1,
          child: FObx(
            () => FBottomCanCelButton(
              height: 56,
              businessParent: widget.businessParent,
              name: "ExamRecord",
              title: i18nBook.remedical.previousPage.t,
              onPressed: controller.state.examRecordIndex == 0
                  ? null
                  : () async {
                      await controller.inspectionRecordsController
                          .lastExamPage();
                      setState(
                        () {
                          controller = Get.find<ConsultationController>();
                          _examRecord = controller.state.examRecord;
                          _currentCount--;
                        },
                      );
                    },
            ),
          ),
        ),
        FExpanded(
          flex: 1,
          child: FObx(
            () => FBottomSubmitButton(
              businessParent: widget.businessParent,
              name: "ExamRecord",
              title: i18nBook.remedical.nextPage.t,
              height: 56,
              onPressed: controller.state.examRecordIndex + 1 == _totalCount
                  ? null
                  : () async {
                      await controller.inspectionRecordsController
                          .nextExamPage();
                      setState(
                        () {
                          controller = Get.find<ConsultationController>();
                          _examRecord = controller.state.examRecord;
                          _totalCount = controller.state.recordCount;
                          _currentCount++;
                        },
                      );
                    },
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    controller.state.description = '';
    controller.state.conclusion = '';
    controller.onstatusChange.removeListener((sender, e) => onStatusChanged(e));
    controller.state.selectedImages.clear();
    controller.state.selectedRemedicalImages.clear();
    super.dispose();
  }

  PreferredSizeWidget _buildAppBar() {
    final examRecord = controller.state.examRecord;
    return ExamRecordsMobileAppbar(
      title: FText(
        i18nBook.remedical.checkRecord.t,
        style: TextStyle(
          fontSize: 16,
          color: Colors.white,
        ),
      ),
      status: examRecord.recordStatus,
      isReferral: examRecord.isReferral,
      referralStatus: examRecord.referralStatus,
      controller: controller,
      // isSingle: _isSingle,
    );
  }

  void onStatusChanged(String e) {
    _appBar = _buildAppBar();
    if (mounted) {
      setState(() {});
    }
  }
}
