import 'package:fis_common/event/event_type.dart';
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/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/services/entity/default_entry_setting.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_record_util.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/report_entry_selection.dart';
import 'package:get/get.dart';

import 'item_selected.dart';

class WriteReport extends StatefulWidget implements FPage {
  final TextEditingController desTextController;
  final TextEditingController conTextController;
  final TextEditingController? hospitalController;
  final TextEditingController? ownerController;
  final TextEditingController? nameController;
  final TextEditingController? ageController;
  final TextEditingController? speciesController;
  final TextEditingController? inspectionPhysicianController;
  final TextEditingController? reportPhysicianController;
  final List<String>? genderItems;
  final List<String>? speciesItems;
  final FEventHandler<List<String>> onSelectedImages;
  final void Function(String)? onSelectedGender;
  final void Function(String)? onSelectedSpecies;

  final List<String>? selectedRemedicalImages;
  final void Function()? onSubmit;
  final void Function(String)? onRemoveImage;
  final void Function(bool, String)? onInputChange;
  final Future<void> Function()? onTapSelectImage;
  final bool isLandscapeMode;
  final bool isNew;
  @override
  final String pageName;

  WriteReport({
    this.pageName = 'WriteReport',
    this.selectedRemedicalImages,
    this.onSubmit,
    this.onInputChange,
    this.onRemoveImage,
    this.onTapSelectImage,
    required this.desTextController,
    required this.conTextController,
    required this.onSelectedImages,
    this.hospitalController,
    this.ownerController,
    this.nameController,
    this.ageController,
    this.speciesController,
    this.inspectionPhysicianController,
    this.reportPhysicianController,
    this.genderItems,
    this.speciesItems,
    this.isLandscapeMode = false,
    this.onSelectedGender,
    this.onSelectedSpecies,
    required this.isNew,
  });

  @override
  State<StatefulWidget> createState() {
    return WriteReportState();
  }
}

class WriteReportState extends State<WriteReport> {
  final ScrollController _scrollController = ScrollController();
  final ScrollController _mainScrollController = ScrollController();
  final ScrollController desScrollController = ScrollController();
  final ScrollController conScrollController = ScrollController();
  final TextStyle _textStyle = TextStyle(fontSize: 14);
  bool _isLandscapeMode = false;
  List<String> _selectedImages = [];
  DefaultEntrySetting defaultEntrySetting = DefaultEntrySetting.ins;
  String _gender = '';
  String _specie = '';

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: ExamRecordsMobileAppbar(
        title: FText(
          widget.isNew
              ? i18nBook.remedical.writeNewReport.t
              : i18nBook.remedical.editReport.t,
          style: TextStyle(
            fontSize: 16,
            color: Colors.white,
          ),
        ),
        // isSingle: true,
      ),
      body: FGestureDetector(
        name: 'WriteReportState',
        businessParent: widget,
        onTap: () {
          // 关闭键盘
          FocusScope.of(context).unfocus();
        },
        child: _buildWriteReportView(),
      ),
      backgroundColor: Colors.white,
      bottomNavigationBar: FBottomSubmitButton(
        businessParent: this.widget,
        name: "WriteReport",
        title: i18nBook.common.submit.t,
        onPressed: () async {
          _isLandscapeMode = false;
          widget.onSubmit?.call();
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (_isLandscapeMode) {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    }
    widget.onSelectedImages.removeListener(_onSelectedImages);
  }

  @override
  void initState() {
    _isLandscapeMode = widget.isLandscapeMode;
    if (_isLandscapeMode) {
      // 强制竖屏
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    }
    super.initState();
    _selectedImages = widget.selectedRemedicalImages ?? [];
    widget.onSelectedImages.addListener(_onSelectedImages);
  }

  ///分割线
  FWidget _buildDriver() {
    return FDivider(
      thickness: 1,
      height: 1,
      color: Colors.grey[400],
    );
  }

  ///词条和描述
  FWidget _buildEntryOrDescription({bool isDescription = true}) {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          margin: EdgeInsets.symmetric(
            horizontal: 15,
            vertical: 15,
          ),
          child: FText(
            isDescription
                ? i18nBook.remedical.description.t
                : i18nBook.remedical.summary.t,
            style: _textStyle,
          ),
        ),
        FContainer(
          margin: EdgeInsets.only(left: 15, right: 10),
          child: _buildInputElement(isDescription: isDescription),
        ),
      ],
    );
  }

  ///手机端图像选择
  FWidget _buildImageSelect() {
    final allWidth = MediaQuery.of(context).size.width - 20;

    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          margin: EdgeInsets.symmetric(
            horizontal: 15,
            vertical: 15,
          ),
          child: FText(
            i18nBook.common.image.t,
            style: _textStyle,
          ),
        ),
        FRow(
          children: [
            FContainer(
              width: allWidth / 4,
              margin: EdgeInsets.only(left: 15, bottom: 5),
              child: _buildImageUploadBorder(),
            ),
            FContainer(
              width: allWidth / 4 * 3,
              height: allWidth / 4,
              child: QuickFWidget(
                ScrollConfiguration(
                    behavior: ScrollConfiguration.of(context)
                        .copyWith(scrollbars: false),
                    child: FAlwaysScrollListView(
                      scrollController: _scrollController,
                      child: FListView.builder(
                        controller: _scrollController,
                        scrollDirection: Axis.horizontal,
                        itemCount: _selectedImages.length,
                        itemBuilder: (BuildContext context, int index) {
                          final image = _selectedImages[index];
                          return FContainer(
                            margin: EdgeInsets.only(left: 5, bottom: 5),
                            width: allWidth / 4,
                            height: allWidth / 4,
                            color: Colors.black,
                            child: FStack(
                              alignment: Alignment.center,
                              children: [
                                FImage.network(image),
                                FPositioned(
                                    right: 0,
                                    top: 0,
                                    child: FIconButton(
                                      businessParent: this.widget,
                                      name: "$image",
                                      padding: EdgeInsets.all(0),
                                      alignment: Alignment.topRight,
                                      icon: FIcon(
                                        Icons.close,
                                        color: Colors.red,
                                      ),
                                      onPressed: () {
                                        widget.onRemoveImage?.call(image);
                                        setState(() {});
                                      },
                                    )),
                              ],
                            ),
                          );
                        },
                      ),
                    )),
              ),
            ),
          ],
        ),
      ],
    );
  }

  ///选择上传图片按钮
  FWidget _buildImageUploadBorder() {
    return FContainer(
      width: (MediaQuery.of(context).size.width - 20) / 4 - 5,
      height: (MediaQuery.of(context).size.width - 20) / 4 - 5,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: FTheme.ins.colorScheme.secondary,
          width: 0.5,
        ),
      ),
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          businessParent: this.widget,
          name: "selectedRemedicalImages",
          onTap: () async {
            await widget.onTapSelectImage?.call();
            setState(() {});
          },
          child: FContainer(
            color: Colors.transparent,
            child: FIcon(
              Icons.add,
              color: FTheme.ins.colorScheme.secondary,
            ),
          ),
        ),
      ),
    );
  }

  ///输入框和选择词条、撤销按钮
  FWidget _buildInputElement({bool isDescription = true}) {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        FTextField(
          maxLines: 5,
          controller: isDescription
              ? widget.desTextController
              : widget.conTextController,
          scrollController:
              isDescription ? desScrollController : conScrollController,
          style: _textStyle,
          decoration: InputDecoration(border: InputBorder.none),
        ),
        FButtonGroup(
          spacing: 10,
          buttonPadding: 18,
          children: [
            FElevatedButton(
              name: "selectWord",
              businessParent: this.widget,
              onPressed: () async {
                if (defaultEntrySetting.defaultEntry.isEmpty) {
                  PromptBox.toast(i18nBook.remedical.noEntrys.t);
                  return;
                }
                _enterEntrySelection();
              },
              child: FText(i18nBook.remedical.selectWord.t),
            ),
            FElevatedButton(
              businessParent: this.widget,
              name: "revokeConclusion",
              onPressed: () {
                if (isDescription) {
                  widget.desTextController.text = '';
                } else {
                  widget.conTextController.text = '';
                }
              },
              child: FText(i18nBook.common.revoke.t),
            ),
          ],
        ),
      ],
    );
  }

  // 进入词条选择
  void _enterEntrySelection() async {
    EntrySelectResult? result = await Get.to<EntrySelectResult>(
      ReportEntryelectionPage(
        descriptionInitValue: widget.desTextController.text,
        conclusionInitValue: widget.conTextController.text,
      ),
    );
    if (result != null) {
      widget.desTextController.text = result.description;
      widget.conTextController.text = result.conclusion;
      // 文本框失焦
      FocusScope.of(context).requestFocus(FocusNode());
      // 下一帧执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        /// 滚动到底部
        desScrollController.animateTo(
          desScrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeOut,
        );
        conScrollController.animateTo(
          conScrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeOut,
        );
      });
    } else {
      print("get null result");
    }
  }

  ///手机端写报告
  FWidget _buildWriteReportView() {
    return FAlwaysScrollListView(
      scrollController: _mainScrollController,
      child: FListView(
        controller: _mainScrollController,
        children: [
          if (widget.hospitalController != null) ...[
            _buildlInputLine(
                widget.hospitalController!, i18nBook.organization.orgName.t),
          ],
          if (widget.ownerController != null) ...[
            _buildlInputLine(
                widget.ownerController!, i18nBook.remedical.owner.t),
          ],
          if (widget.nameController != null) ...[
            _buildlInputLine(
                widget.nameController!, i18nBook.remedical.petName.t),
          ],
          if (widget.ageController != null) ...[
            _buildlInputLine(widget.ageController!, i18nBook.remedical.age.t),
          ],
          if (widget.hospitalController != null ||
              widget.ownerController != null ||
              widget.nameController != null ||
              widget.ageController != null) ...[
            const FSizedBox(height: 15),
            _buildDriver(),
          ],
          if (widget.genderItems?.isNotEmpty ?? false) ...[
            SelectRow(
              title: i18nBook.remedical.gender.t,
              hintText: i18nBook.remedical.notFill.t,
              value: _gender,
              onClick: () {
                _openGenderSelectedPage(widget.genderItems!, _gender,
                    i18nBook.remedical.selectGender.t, (v) {
                  setState(() {
                    _gender = v;
                  });
                  widget.onSelectedGender?.call(v);
                });
              },
            ),
          ],
          if (widget.speciesItems?.isNotEmpty ?? false) ...[
            SelectRow(
              title: i18nBook.remedical.type.t,
              hintText: i18nBook.remedical.notFill.t,
              value: _specie,
              onClick: () {
                _openGenderSelectedPage(widget.speciesItems!, _specie,
                    i18nBook.remedical.selectCategory.t, (v) {
                  setState(() {
                    _specie = v;
                  });
                  widget.onSelectedSpecies?.call(v);
                });
              },
            ),
          ],
          if ((widget.speciesItems?.isNotEmpty ?? false) ||
              (widget.genderItems?.isNotEmpty ?? false)) ...[
            const FSizedBox(height: 15),
            _buildDriver(),
          ],
          _buildImageSelect(),
          _buildDriver(),
          _buildEntryOrDescription(),
          _buildDriver(),
          _buildEntryOrDescription(isDescription: false),
          _buildDriver(),
          if (widget.inspectionPhysicianController != null) ...[
            _buildlInputLine(widget.inspectionPhysicianController!,
                i18nBook.remedical.checkDoctor.t),
          ],
          if (widget.reportPhysicianController != null) ...[
            _buildlInputLine(widget.reportPhysicianController!,
                i18nBook.remedical.reportDoctor.t),
          ],
          const FSizedBox(height: 15),
        ],
      ),
    );
  }

  void _onSelectedImages(Object sender, List<String> e) {
    setState(() {
      _selectedImages = e;
    });
  }

  FWidget _buildlInputLine(TextEditingController controller, String title) {
    return FRow(
      children: [
        FContainer(
          margin: EdgeInsets.only(
            left: 15,
            top: 10,
          ),
          width: 80,
          child: FText(title),
        ),
        FExpanded(
          child: FContainer(
            margin: EdgeInsets.only(left: 15, right: 15, bottom: 5),
            width: double.infinity,
            child: FTextField(
              maxLines: 1,
              controller: controller,
              style: _textStyle,
              decoration: InputDecoration(
                border: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey), // 设置底部边框的颜色
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                      color: FTheme.ins.colorScheme.primary), // 设置获取焦点时底部边框的颜色
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _openGenderSelectedPage(List<String> items, String selectedItem,
      String title, Function(String) onPressed) {
    Get.to(() => ItemSelected(
          items: items,
          title: title,
          onPressed: onPressed,
          selectedItem: selectedItem,
        ));
  }
}
