import 'package:fis_i18n/i18n.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/spacings.dart';
import 'package:fis_ui/widgets/scroll/refreshIndicator.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.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/consultation/widgets/consultation_card.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/emergency_preparedness.dart';
import 'package:get/get.dart';

import 'index.dart';

class MobileConsultationPage extends FisView<MobileConsultationController>
    implements FPage {
  const MobileConsultationPage({Key? key}) : super(key: key);

  @override
  String get pageName => 'MobileConsultationPage';
  final double _searchInputHeight = 35;

  @override
  FWidget build(BuildContext context) {
    return FSafeArea(
      child: FScaffold(
        appBar: AppBar(
          toolbarHeight: 50,
          title: _buildPageTitle(),
          leading: FSizedBox(),
          backgroundColor: Colors.white,
          elevation: 0,
          leadingWidth: 0,
        ),
        body: _buildPageBody(context),
      ),
    );
  }

  ///搜索框
  FWidget _buildSearchInput() {
    return FContainer(
      height: 50,
      child: FBorderInput(
        width: double.infinity,
        height: _searchInputHeight,
        focusNode: controller.searchFocusNode,
        controller: controller.serachInput,
        fillColor: Colors.white,
        hintSize: FSpacings.L,
        contentSize: FSpacings.L,
        maxLength: 50,
        borderColor: FTheme.ins.colorScheme.line,
        suffixIcon: FIconButton(
          name: "search",
          onPressed: () => controller.getConsultations(),
          icon: FIcon(
            Icons.search,
            size: FFontSizes.H6,
          ),
          businessParent: this,
        ),
        hintText: i18nBook.remedical.searchPatient.t,
        onChanged: (value) {
          controller.state.keyWord = value;
        },
        margin: EdgeInsets.symmetric(horizontal: 15),
      ),
    );
  }

  FWidget _buildPageBody(BuildContext context) {
    return FColumn(
      children: [
        _buildSearchInput(),
        FExpanded(
          child: _buildConsultationCards(context),
        ),
      ],
    );
  }

  FWidget _buildPageTitle() {
    return FContainer(
      height: 50,
      width: double.infinity,
      child: FStack(
        children: [
          FAlign(
            alignment: Alignment.center,
            child: FText(
              i18nBook.realTimeConsultation.consultationList.t,
              style: TextStyle(
                fontSize: FFontSizes.H6,
                color: Colors.black,
              ),
            ),
          ),
          if (Store.user.hasFeature(FeatureKeys.EmergencyConsultation))
            FPositioned(
              right: 5,
              child: FIconButton(
                color: FTheme.ins.colorScheme.primary,
                icon: FIcon(FIcons.emergency),
                onPressed: startEmergencyConsultation,
                businessParent: this,
                name: 'more_horiz',
              ),
            ),
        ],
      ),
    );
  }

  ///会诊列表
  FWidget _buildConsultationCards(BuildContext context) {
    return FRefreshIndicator(
      onRefresh: () async {
        controller.refreshConsultation();
      },
      child: FObx(() {
        return controller.state.consultationsRecordCardList.length <= 0
            ? FCenter(child: FText(i18nBook.common.noData.t))
            : FAlwaysScrollListView(
                scrollController: controller.patientCardScrollController,
                child: QuickFWidget(ScrollConfiguration(
                  behavior: ScrollConfiguration.of(context)
                      .copyWith(scrollbars: false),
                  child: FListView.builder(
                    shrinkWrap: true,
                    itemCount:
                        controller.state.consultationsRecordCardList.length,
                    controller: controller.patientCardScrollController,
                    itemBuilder: (context, index) {
                      var list = controller.state.consultationsRecordCardList;
                      return ConsultationCard(list[index], index);
                    },
                  ),
                )),
              );
      }),
    );
  }

  Future<void> startEmergencyConsultation() 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 Get.to(
      () => EmergencyPreparedness(
        onPressed: ((selectedUser, selectedDevice, patientInfo) {
          var device = devices.firstWhereOrNull(
              (element) => element.shortCode == selectedDevice);
          var deviceCode = device?.deviceCode ?? '';
          controller.startEmergencyConsultation(
              selectedUser, selectedDevice, deviceCode, patientInfo);
        }),
        users: users,
        devices: devices,
        setting: emergencySetting,
      ),
    );
  }
}
