import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/scaffold/drawer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/consultation_list_controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_theme/theme.dart';
import 'real_time_consulation_time_filter.dart';

/// 右侧筛选抽屉
class FFilterDrawer extends StatefulWidget implements FPage {
  const FFilterDrawer({
    super.key,
    this.closeDrawer,
  });

  final VoidCallback? closeDrawer;

  @override
  String get pageName => 'FFilterDrawer';
  @override
  State<FFilterDrawer> createState() => _FFilterDrawerState();
}

class _FFilterDrawerState extends State<FFilterDrawer> {
  late final controller = Get.find<RealTimeConsultationController>();
  late final realTimeConsultationListController =
      Get.put(RealTimeConsultationListController(controller));
  ScrollController _scrollController = ScrollController();

  final GlobalKey _startKey = GlobalKey();
  final GlobalKey _endKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    realTimeConsultationListController.findParentOrganizationsAsync();
    realTimeConsultationListController.findGrassRootsOrganizationsAsync();
  }

  @override
  Widget build(BuildContext context) {
    return FDrawer(
      width: 500,
      child: FAlwaysScrollListView(
        scrollController: _scrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView(
            shrinkWrap: true,
            controller: _scrollController,
            children: [
              FColumn(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildFilterMain(),
                  _buildBottomButtons(),
                ],
              ),
            ],
          ),
        )),
      ),
    );
  }

  FWidget _buildBottomButtons() {
    return FContainer(
      margin: EdgeInsets.only(top: 15),
      child: FColumn(
        children: [
          FRow(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FElevatedButton(
                name: 'search',
                businessParent: this.widget,
                onPressed: () {
                  _onSearch();
                },
                child: FText(
                  i18nBook.common.search.t,
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(
                    EdgeInsets.symmetric(
                      vertical: 15,
                      horizontal: 30,
                    ),
                  ),
                  fixedSize: MaterialStateProperty.all(Size(210, 40)),
                ),
              ),
              FSizedBox(
                width: 30,
              ),
              FElevatedButton(
                name: 'reset',
                businessParent: this.widget,
                onPressed: () {
                  controller.onReset();
                  _onSearch();
                },
                child: FText(
                  i18nBook.measure.resetTone4Btn.t,
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(
                    EdgeInsets.symmetric(
                      vertical: 15,
                      horizontal: 30,
                    ),
                  ),
                  fixedSize: MaterialStateProperty.all(Size(210, 40)),
                ),
              ),
            ],
          ),
          FSizedBox(
            height: 50,
          ),
        ],
      ),
    );
  }

  FWidget _buildFilterMain() {
    return FColumn(
      children: [
        _buildCloseDrawer(),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.startTime.t,
          filterWidget: _buildTimeInput(
            context: context,
            currentKey: _startKey,
            hintText: i18nBook.realTimeConsultation.selectStartTime.t,
            textEditingController: TextEditingController(
                text: realTimeConsultationListController.state.startDate),
            inputType: 1,
          ),
          isExpanded: true,
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.endTime.t,
          filterWidget: _buildTimeInput(
            context: context,
            currentKey: _endKey,
            hintText: i18nBook.remedical.selectEndTime.t,
            textEditingController: TextEditingController(
                text: realTimeConsultationListController.state.endDate),
            inputType: 2,
          ),
          isExpanded: true,
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.consultationEvaluation.t,
          filterWidget: _buildConsultationEvaluation(),
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.consultationStatus.t,
          filterWidget: _buildConsultationStatus(),
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.applicationClassification.t,
          filterWidget: _buildClassification(),
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.consultationInstitution.t,
          filterWidget: FObx(
            () {
              final state = realTimeConsultationListController.state;
              return _buildSelectData(
                state.consultationInstitutionList,
                state.currentConsultationInstitution,
                (value) => realTimeConsultationListController
                    .filterConsultationInstitution(value),
              );
            },
          ),
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.competentExperts.t,
          filterWidget: FObx(
            () {
              final state = realTimeConsultationListController.state;
              return _buildSelectData(
                state.competentExpertList,
                state.currentCompetentExpert,
                (value) => realTimeConsultationListController
                    .state.currentCompetentExpert = value,
              );
            },
          ),
        ),

        /// 申请机构 0320 屏蔽申请机构
        // _buildFilterItem(
        //   title: i18nBook.realTimeConsultation.applicantMechanism.t,
        //   filterWidget: FObx(
        //     () {
        //       final state = realTimeConsultationListController.state;
        //       return _buildSelectData(
        //         state.applicantInstitutionList,
        //         state.currentApplicantInstitution,
        //         (value) => state.currentApplicantInstitution = value,
        //       );
        //     },
        //   ),
        // ),
        // _buildFilterItem(
        //   title: i18nBook.remedical.gender.t,
        //   filterWidget: _buildSexSelect(),
        // ),
        // _buildFilterItem(
        //   title: i18nBook.remedical.age.t,
        //   filterWidget: _buildAgeInput(),
        // ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.nameOfDisease.t,
          filterWidget: _buildCommonInput(
            value:
                realTimeConsultationListController.state.currentPatientDiseases,
            onChanged: (value) {
              realTimeConsultationListController.state.currentPatientDiseases =
                  value;
            },
          ),
          isExpanded: true,
        ),
        _buildFilterItem(
          title: i18nBook.realTimeConsultation.preliminaryDiagnosis.t,
          filterWidget: _buildCommonInput(
            value: realTimeConsultationListController
                .state.currentPatientPrimaryDiagnosis,
            onChanged: (value) {
              realTimeConsultationListController
                  .state.currentPatientPrimaryDiagnosis = value;
            },
          ),
          isExpanded: true,
        ),
      ],
    );
  }

  // 关闭按钮
  FWidget _buildCloseDrawer() {
    return FSizedBox(
      height: Get.height * 0.08,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FIconButton(
            onPressed: () {
              widget.closeDrawer!();
            },
            icon: FIcon(
              Icons.close,
            ),
            businessParent: this.widget,
            name: 'closeDrawer',
          ),
          FSizedBox(
            width: 30,
          ),
        ],
      ),
    );
  }

  void _onSearch() {
    if (!realTimeConsultationListController.onFilterDateComparison()) {
      return;
    }
    realTimeConsultationListController.findConsultationsByPageAsync();
    widget.closeDrawer!();
  }

  List<double> _findRenderObject(GlobalKey key) {
    RenderBox? renderBox = key.currentContext!.findRenderObject() as RenderBox;
    // offset.dx , offset.dy 就是控件的左上角坐标
    renderBox.localToGlobal(Offset.zero);
    var offset = renderBox.localToGlobal(Offset.zero);
    return [offset.dx, offset.dy + 38];
  }

  void _builTimeDialog(
    GlobalKey<State<StatefulWidget>> currentKey,
    TextEditingController textEditingController,
    DateTime? initialDate,
    int inputType,
  ) {
    var timePosition = _findRenderObject(
      currentKey,
    );
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return FRealTimeConsulationFilterTime(
          position: timePosition,
          globalKey: currentKey.toString(),
          timeCallback: (dateTime) {
            initialDate = dateTime;
            textEditingController.text =
                DateFormat('yyyy-MM-dd').format(dateTime);
            if (inputType == 1) {
              realTimeConsultationListController.state.startDate =
                  textEditingController.text;
            } else {
              realTimeConsultationListController.state.endDate =
                  textEditingController.text;
            }
          },
          initialDate: initialDate,
        );
      },
    );
  }

  FWidget _buildTimeInput({
    required BuildContext context,
    required GlobalKey currentKey,
    String? hintText,
    required TextEditingController textEditingController,
    required int inputType,
  }) {
    DateTime initialDate;

    return FBorderInput(
      key: currentKey,
      hintSize: 16,
      contentSize: 16,
      maxLength: 20,
      borderColor: Color.fromRGBO(226, 228, 234, 1),
      controller: textEditingController,
      readOnly: true,
      onTap: () {
        initialDate = textEditingController.text.isNotEmpty
            ? DateTime.parse(textEditingController.text)
            : DateTime.now();
        _builTimeDialog(
            currentKey, textEditingController, initialDate, inputType);
      },
      suffixIcon: FMaterial(
        color: Colors.transparent,
        child: FIconButton(
          name: "startTimePosition",
          businessParent: this.widget,
          onPressed: () {
            initialDate = textEditingController.text.isNotEmpty
                ? DateTime.parse(textEditingController.text)
                : DateTime.now();
            _builTimeDialog(
                currentKey, textEditingController, initialDate, inputType);
          },
          icon: FIcon(
            Icons.date_range_rounded,
          ),
        ),
      ),
      height: 36,
      hintText: hintText,
    );
  }

  FWidget _buildCommonInput({
    String? hintText,
    String? value,
    List<TextInputFormatter>? inputFormatters,
    required ValueCallback onChanged,
  }) {
    return FBorderInput(
      hintSize: 16,
      contentSize: 16,
      maxLength: 20,
      inputFormatters: inputFormatters,
      borderColor: Color.fromRGBO(226, 228, 234, 1),
      height: 38,
      hintText: hintText,
      controller: TextEditingController(text: value ?? ''),
      onChanged: (value) => onChanged(value),
    );
  }

  /// 申请分类
  FWidget _buildClassification() {
    final select = FObx(() {
      final state = realTimeConsultationListController.state;
      ConsultationQueryTypeEnum? consultationQueryType =
          state.consultationQueryType;
      return FSelect<FSelectModel, String>(
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        source: state.classificationList,
        hintText: i18nBook.realTimeConsultation.pleaseSelectCategory.t,
        value: consultationQueryType == null
            ? null
            : consultationQueryType.index.toString(),
        clearable: false,
        height: 36,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          realTimeConsultationListController.state.consultationQueryType =
              ConsultationQueryTypeEnum.values[int.parse(value ?? '0')];
        },
      );
    });
    return select;
  }

  /// 筛选框
  FWidget _buildFilterItem({
    required String title,
    required FWidget filterWidget,
    bool isExpanded = false,
  }) {
    return FContainer(
      margin: EdgeInsets.only(
        left: 30,
        right: 30,
        bottom: 20,
      ),
      child: FRow(
        children: [
          FExpanded(
            child: FContainer(
              child: FRow(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  FSizedBox(
                    width: 100,
                    child: FText(
                      title,
                    ),
                  ),
                  FSizedBox(
                    width: 20,
                  ),
                  if (isExpanded) ...[
                    filterWidget
                  ] else ...[
                    FExpanded(
                      child: filterWidget,
                    ),
                  ]
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 会诊评价
  FWidget _buildConsultationEvaluation() {
    final select = FObx(() {
      final state = realTimeConsultationListController.state;
      QueryEvaluateGradeEnum? consultationEvaluationType =
          state.consultationEvaluationType;
      return FSelect<FSelectModel, String>(
        source: state.consultationEvaluationList,
        hintText: i18nBook.realTimeConsultation.selectConsultationEvaluation.t,
        value: consultationEvaluationType?.index.toString(),
        clearable: false,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        height: 36,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          realTimeConsultationListController.state.consultationEvaluationType =
              QueryEvaluateGradeEnum.values[int.parse(value ?? '0')];
        },
      );
    });
    return select;
  }

  /// 会诊状态
  FWidget _buildConsultationStatus() {
    final select = FObx(() {
      final state = realTimeConsultationListController.state;
      QueryConsultationStatusEnum? transactionStatus = state.consultationStatus;

      return FSelect<FSelectModel, String>(
        source: state.consultationStatusList,
        hintText: i18nBook.realTimeConsultation.selectConsultationStatus.t,
        value: transactionStatus?.index.toString(),
        clearable: false,
        height: 36,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        onSelectChanged: (value, index) {
          realTimeConsultationListController.state.consultationStatus =
              QueryConsultationStatusEnum.values[int.parse(value ?? '1')];
        },
      );
    });
    return select;
  }

  /// 性别
  // FWidget _buildSexSelect() {
  //   final select = FObx(() {
  //     final state = realTimeConsultationListController.state;
  //     return FSelect<FSelectModel, String>(
  //       source: state.consultationSexList,
  //       value: state.currentSex,
  //       clearable: false,
  //       height: 36,
  //       fontFamily: FTheme.ins.localeSetting.fontFamily,
  //       optionLabelExtractor: (data) => data.name,
  //       optionValueExtractor: (data) => data.code,
  //       onSelectChanged: (value, index) {
  //         realTimeConsultationListController.state.currentSex = value!;
  //       },
  //     );
  //   });
  //   return select;
  // }

  /// 需要调接口获取的下拉选择数据
  FWidget _buildSelectData(
    List<FSelectModel> selectList,
    String? valueString,
    ValueCallback onSelectChanged,
  ) {
    final select = FSelect<FSelectModel, String>(
      source: selectList,
      value: valueString,
      fontFamily: FTheme.ins.localeSetting.fontFamily,
      clearable: false,
      height: 36,
      optionLabelExtractor: (data) => data.name,
      optionValueExtractor: (data) => data.code,
      onSelectChanged: (value, index) => onSelectChanged(value),
    );

    return select;
  }
}

// 自定义 RangeTextInputFormatter 类，用于限制输入数字的范围
class RangeTextInputFormatter extends TextInputFormatter {
  final int from;
  final int to;

  RangeTextInputFormatter({required this.from, required this.to});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    final int value = int.tryParse(newValue.text) ?? 0;

    if (value < from) {
      return TextEditingValue(
        text: from.toString(),
        selection: TextSelection.collapsed(offset: from.toString().length),
      );
    } else if (value > to) {
      return TextEditingValue(
        text: to.toString(),
        selection: TextSelection.collapsed(offset: to.toString().length),
      );
    }

    return newValue;
  }
}
