import 'package:fis_i18n/i18n.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/muti_select.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';

import 'package:fis_theme/theme.dart';
import 'muti_selected_dialog.dart';
import 'time_filter.dart';

class RecordFilterDrawer extends FStatefulWidget implements FPage {
  @override
  FState<FStatefulWidget> createState() {
    return _RecordFilterDrawerState();
  }

  @override
  String get pageName => "RecordFilterDrawer";
}

class _RecordFilterDrawerState extends FState<RecordFilterDrawer> {
  final controller = Get.find<ConsultationRecordViewController>();
  final userInfoManager = Get.find<IUserInfoManager>();
  final GlobalKey _startKey = GlobalKey();
  final GlobalKey _endKey = GlobalKey();
  static MaterialStateProperty<EdgeInsetsGeometry> paddingEdgeInsets =
      MaterialStateProperty.all(
    EdgeInsets.symmetric(
      vertical: 15,
      horizontal: 50,
    ),
  );
  @override
  FWidget build(BuildContext context) {
    return FColumn(
      children: [
        _buildFilterClose(),
        _buildFilterTime(context),
        const FSizedBox(height: 15),
        _buildFilterOrganizationOrDevices(),
        _buildFilterStatus(context),
        _buildFilterButtonList(),
      ],
    );
  }

  FWidget _buildFilterOrganizationOrDevices() {
    return FColumn(
      children: [
        _buildFMutiSelectFilter(
          title: i18nBook.user.OrganizationLocated.t,
          selectSource: controller.organizationLocatedList,
          value: controller.selectedOrganizationLocated,
          textEditingController: controller.orgFilterController,
          onTap: () {
            router.dialog(
              () => FMutiSelectDialog<FMutiSelectModel>(
                loadMoreItems: (keyWord, index) async {
                  return await userInfoManager.getSelectOrganizations(
                    keyword: keyWord,
                    pageIndex: index,
                    pageSize: 50,
                  );
                },
                onSelectedAllChanged: (v) {
                  controller.isSelectAllOrg = v;
                },
                isSelectedAll: controller.isSelectAllOrg,
                length: controller.organizationsCount,
                selectedItems: controller.organizationLocatedList,
                onSubmit: (items) {
                  controller.organizationLocatedList = items;
                  controller.orgFilterController.text = controller
                      .organizationLocatedList
                      .map((e) => e.name)
                      .join('、');
                  controller.changeSelectedOrganizationLocated(
                      items.map((e) => e.code).toList());
                },
                buildItem: (model) {
                  return FText(model.name);
                },
              ),
            );
          },
        ),
        FSizedBox(
          height: 15,
        ),
        _buildFMutiSelectFilter(
            title: i18nBook.homePage.organizationDevices.t,
            selectSource: controller.personDeviceList,
            textEditingController: controller.deviceFilterController,
            value: controller.selectedpersonDevice,
            onTap: () {
              router.dialog(
                () => FMutiSelectDialog<FMutiSelectModel>(
                  title: i18nBook.homePage.organizationDevices.t,
                  loadMoreItems: (keyWord, index) async {
                    return await userInfoManager.getSelectPersonDevices(
                      keyword: keyWord,
                      index: index,
                      pageSize: 50,
                      restrictOrgCodes: controller.selectedOrganizationLocated,
                    );
                  },
                  onSelectedAllChanged: (v) {
                    controller.isSelectAllDevice = v;
                  },
                  length: controller.personDeviceCount,
                  selectedItems: controller.personDeviceList,
                  onSubmit: (items) {
                    controller.personDeviceList = items;
                    controller.deviceFilterController.text =
                        items.map((e) => e.name).join('、');
                  },
                  isSelectedAll: controller.isSelectAllDevice,
                  buildItem: (model) {
                    return FText(model.name);
                  },
                ),
              );
            }),
      ],
    );
  }

  FWidget _buildFMutiSelectFilter({
    required String title,
    required List<FMutiSelectModel> selectSource,
    List<String>? value,
    required TextEditingController textEditingController,
    required void Function() onTap,
  }) {
    return _buildRowTitle(
      title: title,
      rowWidget: FBorderInput(
        hintSize: 16,
        contentSize: 16,
        maxLength: 20,
        width: 340,
        borderColor: Color.fromRGBO(234, 234, 234, 1),
        height: 38,
        controller: textEditingController,
        mouseCursor: SystemMouseCursors.click,
        readOnly: true,
        onTap: onTap,
      ),
      isExpand: false,
    );
  }

  FWidget _buildRowTitle(
      {required String title,
      required FWidget rowWidget,
      bool isExpand = true}) {
    return FContainer(
      height: 40,
      margin: EdgeInsets.only(bottom: 5),
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FContainer(
            width: 150,
            padding: EdgeInsets.only(left: 30),
            child: FText(
              title,
              overflow: TextOverflow.ellipsis,
              maxLines: 2,
            ),
          ),
          if (isExpand) ...[
            FExpanded(
              child: rowWidget,
            )
          ] else ...[
            rowWidget,
          ]
        ],
      ),
    );
  }

  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];
  }

  FWidget _buildTimeInputSelect({
    required DateTime dateTime,
    required String keyString,
    required ValueCallback valueCallback,
    required BuildContext context,
    required GlobalKey globalKey,
  }) {
    void selectInput() {
      var timePosition = _findRenderObject(globalKey);
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return TimeSelectDialog(
            globalKey: keyString,
            position: timePosition,
            selectedfn: (datetime) {
              valueCallback.call(datetime);
            },
            startDateTime: controller.startDateTime,
            endDateTime: controller.endDateTime,
          );
        },
      );
    }

    return FBorderInput(
      key: globalKey,
      hintSize: 16,
      contentSize: 16,
      maxLength: 20,
      width: 340,
      borderColor: Color.fromRGBO(234, 234, 234, 1),
      controller: TextEditingController(
        text: DateFormat('yyyy-MM-dd')
            .format(
              dateTime,
            )
            .toString(),
      ),
      onTap: () => selectInput(),
      readOnly: true,
      suffixIcon: FMaterial(
        color: Colors.transparent,
        child: FIconButton(
          businessParent: widget,
          name: "endTimePosition",
          onPressed: () => selectInput(),
          icon: FIcon(
            Icons.date_range_rounded,
          ),
        ),
      ),
      height: 38,
      hintText: i18nBook.remedical.selectEndTime.t,
      onChanged: (value) {},
    );
  }

  FWidget _buildFilterClose() {
    return FSizedBox(
      height: Get.height * 0.08,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FIconButton(
            icon: FIcon(Icons.close),
            onPressed: () {
              controller.openOrCloseMoreFilter();
              controller.scaffoldKey.currentState?.closeEndDrawer();
            },
            businessParent: widget,
            name: 'close filter',
          )
        ],
      ),
    );
  }

  FWidget _buildFilterStatus(BuildContext context) {
    return FColumn(
      children: [
        const FSizedBox(height: 15),
        _buildRowTitle(
          title: i18nBook.common.status.t,
          rowWidget: FSelect<FSelectOptionModel, RecordQueryStateEnum>(
            source: controller.recordStatusList,
            fontFamily: FTheme.ins.localeSetting.fontFamily,
            hintText: i18nBook.common.status.t,
            optionLabelExtractor: (data) => data.title,
            optionValueExtractor: (data) => data.value,
            value: controller.selectRecordStatus,
            onSelectChanged: (value, index) {
              controller.selectRecordStatus = value!;
            },
          ),
        ),
      ],
    );
  }

  FWidget _buildFilterTime(BuildContext context) {
    return FisBuilder<ConsultationRecordViewController>(
      id: "record_time_filter",
      builder: (_) {
        return FColumn(
          children: [
            _buildRowTitle(
              title: i18nBook.realTimeConsultation.startTime.t,
              rowWidget: _buildTimeInputSelect(
                keyString: '_startKey',
                globalKey: _startKey,
                dateTime: controller.startDateTime,
                context: context,
                valueCallback: (value) {
                  controller.startDateTime = value;
                  controller.update(['record_time_filter']);
                  // setState(() {});
                },
              ),
              isExpand: false,
            ),
            const FSizedBox(height: 15),
            _buildRowTitle(
              title: i18nBook.realTimeConsultation.endTime.t,
              rowWidget: _buildTimeInputSelect(
                keyString: '_endKey',
                globalKey: _endKey,
                dateTime: controller.endDateTime,
                context: context,
                valueCallback: (value) {
                  controller.endDateTime = value;
                  controller.update(['record_time_filter']);
                  // setState(() {});
                },
              ),
              isExpand: false,
            ),
          ],
        );
      },
    );
  }

  FWidget _buildFilterButtonList() {
    return FContainer(
      margin: EdgeInsets.only(top: 10),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _buildTextButton(
            i18nBook.common.search.t,
            () async {
              await controller.searchFindRecordPages(
                organizationCodes: controller.isSelectAllOrg
                    ? null
                    : controller.selectedOrganizationLocated,
                deviceCodes: controller.isSelectAllDevice
                    ? null
                    : controller.selectedpersonDevice,
              );
            },
            textButtonPadding: paddingEdgeInsets,
          ),
          FSizedBox(
            width: 15,
          ),
          _buildTextButton(
            i18nBook.measure.resetTone4Btn.t,
            () async {
              await controller.resetFilter();
            },
            textButtonPadding: paddingEdgeInsets,
          ),
        ],
      ),
    );
  }

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