import 'package:fis_common/index.dart';
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/values/font_sizes.dart';
import 'package:fis_ui/values/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/managers/interfaces/live_consultation.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:flyinsono/views/desktop/index.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/filter_drawer.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/real_time_consultation_export.dart';
import 'package:get/get.dart';

import 'emergency_preparedness.dart';

/// 实时诊断的大列表页面
class FRealTimeConsultationListPage
    extends FisView<RealTimeConsultationController> implements FPage {
  final GlobalKey _globalKey = GlobalKey();

  // final evaluateController = Get.find<RealTimeConsultationController>();
  final tabelScrollController = ScrollController();

  FRealTimeConsultationListPage({Key? key}) : super(key: key);

  @override
  String get pageName => 'FRealTimeConsultationListPage';
  ScaffoldState get _scaffoldState => _globalKey.currentState as ScaffoldState;
  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      key: _globalKey,
      body: _buildOrgTableContent(context),
      endDrawer: FFilterDrawer(
        closeDrawer: () {
          controller.listController.onFilterDateComparison();
          _scaffoldState.closeEndDrawer();
        },
      ),
    );
  }

  /// 年龄文案
  String _ageLabel(String? age) {
    if (age == null || age.isEmpty) {
      return i18nBook.remedical.notFill.t;
    }
    return age;
  }

  /// 头部筛选部分
  FWidget _buildfilterHeader() {
    return FContainer(
      padding: EdgeInsets.only(
        left: FSpacings.XXL,
        bottom: FSpacings.MINI_BUTTON,
      ),
      child: FColumn(
        children: [
          FRow(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _buildSearchInputRow(),
              FRow(
                children: [
                  if (Store.user.hasFeature(FeatureKeys.ApplyConsultation))
                    FIconButton(
                      icon: FIcon(Icons.refresh),
                      color: Colors.blue,
                      onPressed: () async {
                        controller.state.pageIndex = 1;
                        controller.listController
                            .findConsultationsByPageAsync();
                      },
                      businessParent: this,
                      name: 'refersh',
                    ),
                ],
              ),
              FSizedBox(
                width: 10,
              ),
              FIconButton(
                businessParent: this,
                name: i18nBook.common.filter.t,
                onPressed: () {
                  _scaffoldState.openEndDrawer();
                },
                icon: FIcon(
                  Icons.filter_alt_rounded,
                  color: FTheme.ins.colorScheme.primary,
                ),
              ),
              FSizedBox(
                width: 15,
              ),
              if ((FPlatform.isWindows || FPlatform.isMacOS) &&
                  Store.user.canBatchExportData)
                _buildTextOutlinedButton(
                  i18nBook.remedical.export.t,
                  () {
                    router.dialog(() => FRealTimeConsultationExport());
                  },
                ),
              FExpanded(child: const FSizedBox()),
              FButtonGroup(
                spacing: 10,
                children: [
                  _buildTextButton(
                    i18nBook.realTimeConsultation.createApplication.t,
                    controller.createAppointmentConsultation,
                    fixedSize: MaterialStateProperty.all(Size(88, 34)),
                  ),
                  if (Store.user.hasFeature(FeatureKeys.EmergencyConsultation))
                    _buildTextButton(
                      i18nBook.realTimeConsultation.makeCall.t,
                      _emergencyConsultationRequest,
                      fixedSize: MaterialStateProperty.all(Size(88, 34)),
                    ),
                ],
              ),
              FSizedBox(
                width: 15,
              ),
            ],
          ),
          _buildTabs(),
        ],
      ),
    );
  }

  ///表格内容
  FWidget _buildOrgTableContent(BuildContext context) {
    final columns = _buildOrgTableHeader();
    return FContainer(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: FFlex(
        direction: Axis.vertical,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildfilterHeader(),
          FExpanded(
            child: QuickFWidget(
              ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FObx(
                  () => FTable<ConsultationsRecordCard>(
                    autoHeight: false,
                    noDataHintText: i18nBook.common.noData.t,
                    columns: columns,
                    source: controller.state.consultationsRecordCardList,
                    loading: false,
                    onRowSelected: (value, index, idxs) {},
                    onRowTap: (index) {
                      controller.listController.onTableRowClick(index);
                    },
                    onAllRowsSelected: (value, idxs) => {},
                    scrollController: tabelScrollController,
                  ),
                ),
              ),
            ),
          ),
          FObx(
            () => FTablePagination(
              currListLength: controller.state.totalCount,
              currPageIndex: controller.state.pageIndex,
              pageSize: 20,
              onChangePage: (pageIndex, listLength) {
                controller.state.pageIndex = pageIndex;
                controller.listController.findConsultationsByPageAsync();
                _tableScrollToTop();
              },
              totalItemNumText: i18nBook.common.ofTerm.translate(
                ['${controller.state.totalCount}'],
              ),
              previousFivePageText: i18nBook.common.previousFivePageText.t,
              nextFivePageText: i18nBook.common.nextFivePageText.t,
            ),
          ),
          FSizedBox(
            height: FSpacings.XXL,
          )
        ],
      ),
    );
  }

  void _tableScrollToTop() {
    tabelScrollController.animateTo(0,
        duration: Duration(milliseconds: 500), curve: Curves.ease);
  }

  /// 获取预约会诊时间
  String _getConsultationTime(ConsultationsRecordCard info) {
    //如果会诊申请没有通过，会诊状态是待审核或者已拒绝或者已撤回，则只显示日期，不显示具体时间
    if (info.consultationTime == null) return '--';
    if (_isConsultationAccepted(info.state)) {
      if (info.consultationTimeEnd == null) return '';
      return CalendarUtils.formatDateRangeWithYear(
          info.consultationTime!.toLocal(),
          info.consultationTimeEnd!.toLocal());
    } else {
      return '--';
    }
  }

  /// 会诊是否被接受
  bool _isConsultationAccepted(TransactionStatusEnum? e) {
    //会诊状态
    List<TransactionStatusEnum> consultationStatus = [
      TransactionStatusEnum.Applied,
      TransactionStatusEnum.Rejected,
      TransactionStatusEnum.Withdrawn,
    ];
    return !consultationStatus.any((element) => element == e);
  }

  ///组织表格Header
  List<FTableColumn<ConsultationsRecordCard>> _buildOrgTableHeader() {
    return <FTableColumn<ConsultationsRecordCard>>[
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.remedical.patientDisplayName.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.patientName.isNullOrEmpty
                ? i18nBook.remedical.notFill.t
                : rowData.patientName!,
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.common.mobileNumber.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.phone.isNullOrEmpty
                ? i18nBook.remedical.notFill.t
                : rowData.phone!,
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.remedical.age.t,
        render: (rowData, index) => FCenter(
          child: FText(
            _ageLabel(rowData.age),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.remedical.gender.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.sex.isNullOrEmpty
                ? i18nBook.remedical.notFill.t
                : rowData.sex!,
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
        maxWidth: 150,
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.realTimeConsultation.dateConsultation.t,
        render: (rowData, index) => FCenter(
          child: FText(
            _getConsultationTime(rowData),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.realTimeConsultation.competentExperts.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.expertUserName.toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      // 俄语定制主题，去掉申请机构列
      if (!i18nBook.isCurrentRussian)
        FTableColumn<ConsultationsRecordCard>(
          headerText: i18nBook.realTimeConsultation.applicantMechanism.t,
          render: (rowData, index) => FCenter(
            child: FText(
              rowData.applyOrganizationName.toString(),
              style: const TextStyle(
                fontSize: 16,
              ),
            ),
          ),
          minWidth: 250,
        ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.common.status.t,
        render: (rowData, index) => FCenter(
          child: FText(
            _stateLabel(rowData.state!),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordCard>(
        headerText: i18nBook.realTimeConsultation.consultationEvaluation.t,
        render: (rowData, index) => FContainer(
          padding: EdgeInsets.symmetric(
            vertical: 8,
          ),
          child: _buildConsultationEvaluateButton(rowData),
        ),
      ),
    ];
  }

  /// 搜索框
  FWidget _buildSearchInputRow() {
    return FContainer(
      width: 300,
      padding: EdgeInsets.all(15),
      child: FRow(
        children: [
          FBorderInput(
            hintSize: FSpacings.XL,
            contentSize: FSpacings.XL,
            maxLength: 20,
            hintText: i18nBook.remedical.searchKeyword.t,
            borderColor: Color.fromRGBO(234, 234, 234, 1),
            focusNode: controller.keyWordSearchFocusNode,
            suffixIcon: FMaterial(
              color: Colors.transparent,
              child: FIconButton(
                businessParent: this,
                name: "search",
                onPressed: () {
                  controller.state.pageIndex = 1;
                  controller.listController.findConsultationsByPageAsync();
                },
                icon: FIcon(
                  Icons.search,
                ),
              ),
            ),
            height: 36,
            onChanged: (value) {
              controller.state.keyWord = value;
            },
          ),
        ],
      ),
    );
  }

  /// 普通按钮
  FWidget _buildTextButton(String textString, Function onPressed,
      {MaterialStateProperty<Size?>? fixedSize}) {
    return FElevatedButton(
      name: textString,
      businessParent: this,
      onPressed: () => onPressed.call(),
      child: FText(
        textString,
        style: TextStyle(color: Colors.white),
      ),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(
          EdgeInsets.symmetric(vertical: 15),
        ),
        fixedSize: fixedSize,
      ),
    );
  }

  /// 边框按钮
  FWidget _buildTextOutlinedButton(String textString, Function onPressed) {
    return FOutlinedButton(
      name: textString,
      businessParent: this,
      onPressed: () => onPressed.call(),
      child: FText(
        textString,
        style: TextStyle(color: Colors.black),
      ),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(
          EdgeInsets.symmetric(
            vertical: 15,
          ),
        ),
        minimumSize: MaterialStateProperty.all(Size(88, 0)),
      ),
    );
  }

  /// 会诊评价
  String _consultationEvaluateLabel(
      EvaluateGradeEnum consultationEvaluateEnum) {
    switch (consultationEvaluateEnum) {
      case EvaluateGradeEnum.UnSet:
        return i18nBook.realTimeConsultation.unrated.t;
      case EvaluateGradeEnum.Dissatisfaction:
        return i18nBook.realTimeConsultation.unsatisfactory.t;
      case EvaluateGradeEnum.General:
        return i18nBook.realTimeConsultation.general.t;
      case EvaluateGradeEnum.Satisfaction:
        return i18nBook.realTimeConsultation.satisfactory.t;
      default:
        return '';
    }
  }

  // 构建会诊评价按钮，可弹出评价弹窗
  FWidget _buildConsultationEvaluateButton(ConsultationsRecordCard rowData) {
    Function()? onTap;
    if (rowData.consultationEvaluate == null ||
        rowData.consultationEvaluate == EvaluateGradeEnum.UnSet) {
      onTap = null;
    } else {
      onTap = () => controller.openEvaluateDialog(rowData.consultationCode);
    }
    return FContainer(
      child: FInkWell(
        onTap: onTap,
        child: FCenter(
          child: FText(
            _consultationEvaluateLabel(
              rowData.consultationEvaluate ?? EvaluateGradeEnum.UnSet,
            ),
            style: TextStyle(
              color: rowData.consultationEvaluate == null ? Colors.grey : null,
              fontSize: FFontSizes.H6,
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _emergencyConsultationRequest() async {
    var manager = Get.find<ILiveConsultationManager>();
    var datas = await manager.queryEmergencyData();
    var devices = datas.deviceInfoList ?? [];
    var users = datas.expertList ?? [];
    var emergencySetting = await manager.getEmergencySettingAsync();
    await router.dialog(
      () => EmergencyPreparedness(
        onPressed: ((selectedUser, selectedDevice, patientInfo) async {
          var device = devices.firstWhereOrNull(
              (element) => element.shortCode == selectedDevice);
          var deviceCode = device?.deviceCode ?? '';
          bool resut = await controller.listController
              .startEmergencyConsultation(
                  selectedUser, selectedDevice, deviceCode, patientInfo);
          if (resut) {
            router.back();
          }
        }),
        users: users,
        devices: devices,
        setting: emergencySetting,
      ),
    );
  }

  /// 会诊状态文案
  String _stateLabel(TransactionStatusEnum statusEnum) {
    switch (statusEnum) {
      case TransactionStatusEnum.Applied:
        return i18nBook.user.underVerification.t;
      case TransactionStatusEnum.End:
        return i18nBook.realTimeConsultation.closed.t;
      case TransactionStatusEnum.InProgress:
        return i18nBook.realTimeConsultation.haveInHand.t;
      case TransactionStatusEnum.PendingReport:
        return i18nBook.realTimeConsultation.toBeReported.t;
      case TransactionStatusEnum.Rejected:
        return i18nBook.realTimeConsultation.rejected.t;
      case TransactionStatusEnum.ToStart:
        return i18nBook.realTimeConsultation.toBeStarted.t;
      case TransactionStatusEnum.Withdrawn:
        return i18nBook.realTimeConsultation.withdrawn.t;
      case TransactionStatusEnum.Expired:
        return i18nBook.realTimeConsultation.expired.t;
      default:
        return '';
    }
  }

  FWidget _buildTabs() {
    const horizontalSpacing = 10.0;

    return FRow(
      children: [
        const FSizedBox(
          width: horizontalSpacing,
        ),
        _tabRadio(
          title: i18nBook.common.all.t,
          value: QueryConsultationStatusEnum.All,
        ),
        const FSizedBox(
          width: horizontalSpacing,
        ),
        _tabRadio(
          title: i18nBook.user.underVerification.t,
          value: QueryConsultationStatusEnum.Applied,
        ),
        const FSizedBox(
          width: horizontalSpacing,
        ),
        _tabRadio(
          title: i18nBook.realTimeConsultation.toBeStarted.t,
          value: QueryConsultationStatusEnum.ToStart,
        ),
        const FSizedBox(
          width: horizontalSpacing,
        ),
        _tabRadio(
          title: i18nBook.realTimeConsultation.haveInHand.t,
          value: QueryConsultationStatusEnum.InProgress,
        ),
        const FSizedBox(
          width: horizontalSpacing,
        ),
        _tabRadio(
          title: i18nBook.realTimeConsultation.toBeReported.t,
          value: QueryConsultationStatusEnum.PendingReport,
        ),
      ],
    );
  }

  FWidget _tabRadio({
    required String title,
    required QueryConsultationStatusEnum value,
  }) {
    return FInkWell(
      onTap: () {
        controller.state.consultationStatus = value;
        controller.listController.findConsultationsByPageAsync();
      },
      child: FContainer(
        margin: EdgeInsets.only(right: 15),
        child: FRow(
          children: [
            FObx(
              () => FRadio(
                value: value,
                groupValue: controller.state.consultationStatus,
                onChanged: (v) {
                  controller.state.consultationStatus = value;
                  controller.listController.findConsultationsByPageAsync();
                },
              ),
            ),
            FObx(
              () => FText(
                title,
                style: TextStyle(
                  color: controller.state.consultationStatus == value
                      ? FTheme.ins.colorScheme.primary
                      : FTheme.ins.colorScheme.text,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
