import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_lib_business_components/components/consultation_picture_component.dart';
import 'package:fis_measure/view/measure/measure_images_bar.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/functional/popup_menu_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/image_cover_mobile.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/consultation_image_view.dart';
import 'package:get/get.dart';
import 'package:fis_ui/widgets/scroll/refreshIndicator.dart';
import 'package:intl/intl.dart';
import 'package:fis_ui/widgets/insta_image_viewer/lib/insta_image_viewer.dart';

enum _SelectImageSource {
  Cloud,
  Measure,
  Consultation,
}

/// 图像列表界面
class ExamImagesView extends FStatefulWidget implements FPage {
  ///是否单个检查的图像（true则不显示底部上一页、下一页按钮）
  final bool isSingle;

  ///是否可以选择图像（true则可选择图像用于填充报告）
  final bool isSelectImageModel;
  final List<RemedicalListResult> cloudImageInfos;
  final List<RemedicalMeasuredInfoDTO> measureImages;
  final List<String>? selectedImags;
  final void Function(int)? onTapExam;
  final String? patientCode;
  final void Function(List<String>) onSubmit;
  final List<ConsultationFileDTO>? consultationImages;
  final bool isShowConsultationImage;
  final bool isCanWriteReport;
  final void Function()? onEditReport;
  final Future<List<RemedicalListResult>> Function()? onLoadCloudImages;

  @override
  final String pageName;
  ExamImagesView({
    this.pageName = 'ExamImagesView',
    this.isSingle = false,
    this.isSelectImageModel = false,
    this.selectedImags,
    required this.cloudImageInfos,
    required this.measureImages,
    required this.onSubmit,
    this.onTapExam,
    this.consultationImages,
    this.onEditReport,
    this.patientCode,
    this.onLoadCloudImages,
    this.isShowConsultationImage = false,
    this.isCanWriteReport = false,
  });

  @override
  FState<ExamImagesView> createState() => _ExamImagesViewState();
}

class _ExamImagesViewState extends FState<ExamImagesView> {
  late ScrollController _listViewController = ScrollController();
  final remedicalManager = Get.find<IRemedicalManager>();
  final languageConfigManager = Get.find<ILanguageConfigManager>();
  late final List<String> _selectedImags;
  int _imageScannedIndex = 0;
  int _totalCount = 0;
  _SelectImageSource _imageSource = _SelectImageSource.Cloud;
  List<RemedicalMeasuredInfoDTO> _measureImages = [];
  List<RemedicalListResult> _cloudImageInfos = [];

  @override
  void initState() {
    super.initState();
    _cloudImageInfos = widget.cloudImageInfos;
    _totalCount = 0;
    for (var c in _cloudImageInfos) {
      for (RemedicalItemList i in c.remedicalItemList ?? []) {
        _totalCount += i.remedicalList?.length ?? 0;
      }
    }
    _measureImages = widget.measureImages;
    if (widget.isShowConsultationImage) {
      _imageSource = _SelectImageSource.Consultation;
      if (mounted) {
        setState(() {});
      }
    }
    _selectedImags = widget.selectedImags ?? [];
  }

  @override
  FWidget build(BuildContext context) {
    return FSafeArea(
      top: false,
      child: FScaffold(
        appBar: _buildAppBar(),
        body: _buildImageContentView(context),
      ),
    );
  }

  /// 返回每个隐藏的菜单项
  selectView(IconData icon, String text, String id) {
    return new PopupMenuItem<String>(
      value: id,
      child: new FRow(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <FWidget>[
          new FIcon(icon, color: FTheme.ins.colorScheme.primary),
          new FText(text),
        ],
      ),
    );
  }

  ///图像显示区域
  FWidget _buildImageContentView(BuildContext context) {
    FWidget? body;
    if (_imageSource == _SelectImageSource.Cloud) {
      body = _buildCloudImagesContentView();
    } else if (_imageSource == _SelectImageSource.Measure) {
      body = _buildMeasureImagsContentView(context);
    } else {
      body = _buildConsultationImages(widget.consultationImages ?? []);
    }
    return FScaffold(
      appBar: _buildImageContentViewAppBar(),
      body: body,
      bottomNavigationBar: widget.isSingle ? null : _buildOperateLine(),
    );
  }

  ///图像集合
  FWidget _buildImagesView(
    RemedicalItemList remedicalItem,
    BuildContext context,
    int startIndex,
  ) {
    final remedicalList = remedicalItem.remedicalList ?? [];
    if ((remedicalList.length % 4) != 0 &&
        (remedicalList.length % 4) % 3 == 0 &&
        kIsMobile) {
      if (widget.isSelectImageModel)
        remedicalList.add(
          RemedicalInfoDTO(),
        ); //占位作用
    }
    var applicationCategory = languageConfigManager
        .getApplicationLanguageValue(remedicalItem.applicationCategory ?? '');
    var application = languageConfigManager
        .getApplicationLanguageValue(remedicalItem.application ?? '');
    var totalCount = remedicalList.length;
    List<FWidget> listChildren = List<FWidget>.generate(
      totalCount,
      (index) {
        final remedicalList = remedicalItem.remedicalList![index];
        final remedicalCode = remedicalList.remedicalCode ?? '';
        final fileDataType = remedicalList.fileDataType;
        final terminalImageDTO = remedicalList.terminalImages;

        if (terminalImageDTO == null) {
          return FFittedBox(
            fit: BoxFit.scaleDown,
            child: FSizedBox(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
            ),
          );
        }
        TerminalImage? terminalImage = TerminalImage(
          imageUrl: terminalImageDTO.imageUrl,
          previewUrl: terminalImageDTO.previewUrl,
          coverImageUrl: terminalImageDTO.coverImageUrl,
        );
        final image = ImageCorverMobile(
          widget.isSelectImageModel,
          terminalImage,
          startIndex + index - 1,
          remedicalCode,
          fileDataType,
          remedicalList,
          application,
          _selectedImags.contains(
            terminalImage.coverImageUrl,
          ),
          patientCode: widget.patientCode,
          isCanCreateReport: widget.isCanWriteReport,
          onImageTap: (image) {
            if (_selectedImags.contains(image)) {
              _selectedImags.remove(image);
            } else {
              _selectedImags.add(image);
            }
          },

          ///这里的_totalCount要取整个检查的图像数量，而不是某个分类下的数量
          totalCount: _totalCount,
        );
        return FStack(children: [
          image,
          FPositioned(
            left: 5,
            child: FText(
              (startIndex + index).toString(),
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          ),
        ]);
      },
    );

    final FWidget cardWrap = FGridView.count(
      addRepaintBoundaries: false,
      addAutomaticKeepAlives: false,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
      shrinkWrap: true,
      crossAxisCount: 2,
      controller: ScrollController(),
      children: listChildren,
    );
    return FContainer(
      margin: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            height: 25,
            child: FText(
              application.isNullOrEmpty
                  ? applicationCategory
                  : '$applicationCategory-$application',
            ),
          ),
          FCenter(child: FScrollbar(thickness: 0.0, child: cardWrap)),
        ],
      ),
    );
  }

  ///mobile appBar
  FAppBar _buildAppBar() {
    return FAppBar(
      actions: widget.isSingle && !widget.isSelectImageModel
          ? [
              FSizedBox(
                width: 56,
              ) //这里56的宽度会让title居中
            ]
          : [
              if (this.widget.isSelectImageModel) ...[
                FContainer(
                  margin: EdgeInsets.only(left: 10),
                  child: FElevatedButton(
                    name: "confirm",
                    businessParent: this.widget,
                    style: ButtonStyle(elevation: MaterialStateProperty.all(0)),
                    onPressed: () {
                      router.back();
                      widget.onSubmit.call(_selectedImags);
                    },
                    child: FText(i18nBook.common.confirm.t),
                  ),
                )
              ] else ...[
                FPopupMenuButton<String>(
                  itemBuilder: ((context) => <PopupMenuItem<String>>[
                        this.selectView(
                          Icons.my_library_books_outlined,
                          i18nBook.remedical.associateCheck.t,
                          'A',
                        ),
                      ]),
                  onSelected: (String action) async {
                    switch (action) {
                      case 'A':
                        widget.onTapExam?.call(_imageScannedIndex);
                        break;
                    }
                  },
                ),
              ]
            ],
      title: _buildAppBarTitle(),
      elevation: 0,
      centerTitle: true,
      leading: FIconButton(
        name: "back",
        businessParent: this.widget,
        icon: FIcon(
          Icons.arrow_back_ios_new,
          size: 20,
        ),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  ///第二层APPBar
  FAppBar _buildImageContentViewAppBar() {
    return FAppBar(
      toolbarHeight: 30,
      leadingWidth: 0,
      titleSpacing: 0,
      centerTitle: false,
      elevation: 0,
      title: FContainer(
        decoration: new BoxDecoration(
          border: new Border.all(
            width: 1,
            color: FTheme.ins.colorScheme.secondary,
          ),
          color: FTheme.ins.colorScheme.secondary,
        ),
        height: 30,
        child: FRow(
          children: [
            FSizedBox(
              width: 20,
            ),
            if (_cloudImageInfos.isNotEmpty) ...[
              FText(
                i18nBook.remedical.scanDate.translate([
                  _getDateStr(_cloudImageInfos[_imageScannedIndex].scanDate!)
                ]),
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
            ],
          ],
        ),
      ),
      leading: FSizedBox(),
    );
  }

  String _getDateStr(String rawTimeStr) {
    try {
      var dateTime =
          DateTime.parse(_cloudImageInfos[_imageScannedIndex].scanDate!);
      return DateFormat('yyyy-MM-dd').format(dateTime);
    } catch (e) {
      return "";
    }
  }

  ///底部操作行
  FWidget _buildOperateLine() {
    return FRow(
      children: [
        FExpanded(
          flex: 1,
          child: FBottomCanCelButton(
            name: "previous",
            businessParent: this.widget,
            title: i18nBook.remedical.previousPage.t,
            onPressed: _imageScannedIndex == 0
                ? null
                : () async {
                    setState(() {
                      _imageScannedIndex--;
                    });
                    if (_imageSource == _SelectImageSource.Measure) {
                      var recordCode = widget
                          .cloudImageInfos[_imageScannedIndex].recordCode!;
                      var images = await remedicalManager
                          .findRemedicalMeasuredInfoAsync(recordCode);
                      setState(() {
                        _measureImages = images;
                      });
                    }
                  },
          ),
        ),
        FExpanded(
          flex: 1,
          child: FBottomSubmitButton(
            name: "next",
            businessParent: this.widget,
            title: i18nBook.remedical.nextPage.t,
            onPressed: _imageScannedIndex + 1 == _cloudImageInfos.length
                ? null
                : () async {
                    setState(() {
                      _imageScannedIndex++;
                    });
                    if (_imageSource == _SelectImageSource.Measure) {
                      var recordCode = widget
                          .cloudImageInfos[_imageScannedIndex].recordCode!;
                      var images = await remedicalManager
                          .findRemedicalMeasuredInfoAsync(recordCode);
                      setState(() {
                        _measureImages = images;
                      });
                    }
                  },
          ),
        ),
      ],
    );
  }

  ///APPBar头部按钮
  FWidget _buildAppBarTitle() {
    List<FSelectModel> selectedItems = [
      FSelectModel(
        name: i18nBook.remedical.cloudImageShort.t,
        code: _SelectImageSource.Cloud.name,
      ),
      FSelectModel(
        name: i18nBook.measure.measureImageShort.t,
        code: _SelectImageSource.Measure.name,
      ),
    ];
    if (widget.isShowConsultationImage) {
      selectedItems.insert(
        0,
        FSelectModel(
          name: i18nBook.realTimeConsultation.consultationImageShort.t,
          code: _SelectImageSource.Consultation.name,
        ),
      );
    }
    return FContainer(
      width: 150,
      height: 50,
      child: FSelect(
        source: selectedItems,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        value: _imageSource.name,
        optionAlignment: Alignment.center,
        width: i18nBook.isCurrentChinese
            ? 150
            : i18nBook.isCurrentRussian
                ? 200
                : 210,
        decoration: BoxDecoration(
            border: Border.all(width: 0, color: Colors.transparent)),
        optionValueExtractor: (data) => data.code,
        optionLabelExtractor: (data) => data.name,
        textColor: Colors.white,
        dropDownIcon: Icon(
          Icons.arrow_drop_down,
          color: Colors.white,
        ),
        buttonDecoration: BoxDecoration(),
        onSelectChanged: (value, index) {
          setState(() {
            _imageSource = _SelectImageSource.values
                .firstWhere((element) => element.name == value);
            _imageScannedIndex = 0;
          });
        },
      ),
    );
  }

  ///云端图像视图
  FWidget _buildCloudImagesContentView() {
    int length = 0;
    int imageCount = 0;
    if (_cloudImageInfos.isNotEmpty) {
      final remedicalList =
          _cloudImageInfos[_imageScannedIndex].remedicalItemList ?? [];
      length = remedicalList.length;
      for (RemedicalItemList r in remedicalList) {
        if (r.remedicalList?.isNotEmpty ?? false) {
          imageCount += r.remedicalList?.length ?? 0;
        }
      }
    } else {
      return NoDataWidget();
    }
    if (imageCount == 0) {
      return NoDataWidget();
    }

    //每组 list 的起始下标
    List<int> startIndexOfEachGroup = [1];
    if (widget.isSingle) {
      _cloudImageInfos.first.remedicalItemList?.forEach((element) {
        final existNum = startIndexOfEachGroup.last;
        startIndexOfEachGroup.add(element.remedicalList!.length + existNum);
      });
    } else {
      _cloudImageInfos[_imageScannedIndex]
          .remedicalItemList!
          .forEach((element) {
        final existNum = startIndexOfEachGroup.last;
        startIndexOfEachGroup.add(element.remedicalList!.length + existNum);
      });
    }
    FWidget result = FListView.builder(
      shrinkWrap: true,
      itemCount: length,
      controller: _listViewController,
      itemBuilder: (BuildContext context, int index) {
        return _buildImagesView(
          widget.isSingle
              ? _cloudImageInfos.first.remedicalItemList![index]
              : _cloudImageInfos[_imageScannedIndex].remedicalItemList![index],
          context,
          startIndexOfEachGroup[index],
        );
      },
    );
    if (length == 0) {
      return NoDataWidget();
    }
    if (widget.onLoadCloudImages != null) {
      return FRefreshIndicator(
        onRefresh: () async {
          var infos = await widget.onLoadCloudImages!.call();
          setState(() {
            _cloudImageInfos = infos;
          });
        },
        child: FListView(
          children: [
            result,
          ],
        ),
      );
    }
    //列表内的起始下标
    return result;
  }

  ///测量图像
  FWidget _buildMeasureImagsContentView(BuildContext context) {
    final allWidth = MediaQuery.of(context).size.width;
    final width = (allWidth - 40) / 2;
    if (_measureImages.isEmpty) {
      return NoDataWidget();
    }
    return FContainer(
      alignment: Alignment.topCenter,
      margin: EdgeInsets.only(top: 10, left: 10, right: 10),
      child: FGridView.builder(
        itemCount: _measureImages.length,
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisSpacing: 10,
          crossAxisCount: 2,
        ),
        itemBuilder: (BuildContext context, int index) {
          final token = _measureImages[index].measuredFileToken ?? '';
          return FGestureDetector(
            behavior: HitTestBehavior.opaque,
            name: "MeasureImage:$token",
            businessParent: this.widget,
            onTap: () {
              if (widget.isSelectImageModel) {
                if (!_selectedImags.contains(token)) {
                  _selectedImags.add(token);
                } else {
                  _selectedImags.remove(token);
                }
              }
            },
            child: FStack(
              children: [
                FContainer(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(bottom: 10),
                  color: Colors.black,
                  height: width,
                  child: QuickFWidget(
                    InstaImageViewer(
                      backgroundColor: Color.fromRGBO(30, 30, 30, 1),
                      child: Center(
                        child: FImage.network(
                          token,
                          fit: BoxFit.cover,
                        ),
                      ),
                      disableSwipeToDismiss: true,
                      isVertical: true,
                    ),
                  ),
                ),
                if (widget.isSelectImageModel) ...[
                  FPositioned(
                    right: 2,
                    top: 2,
                    child: FCheckbox<bool>(
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      fillColor: MaterialStateProperty.all(Colors.white),
                      checkColor: FTheme.ins.colorScheme.primary,
                      isCheck: _selectedImags.contains(token),
                      value: _selectedImags.contains(token),
                      visualDensity:
                          VisualDensity(horizontal: -4, vertical: -4),
                      onChange: (dynamic value, bool? isCheck) {
                        if (!_selectedImags.contains(token)) {
                          _selectedImags.add(token);
                        } else {
                          _selectedImags.remove(token);
                        }
                      },
                    ),
                  ),
                ],
              ],
            ),
          );
        },
      ),
    );
  }

  ///会诊图像
  FWidget _buildConsultationImages(
      List<ConsultationFileDTO> consultationImages) {
    if (consultationImages.isEmpty) {
      return NoDataWidget();
    }
    return FGridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      controller: _listViewController,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisSpacing: 10,
        mainAxisSpacing: 10.0, //主轴（行）间距
        crossAxisCount: 2,
      ),
      itemCount: consultationImages.length,
      shrinkWrap: true,
      itemBuilder: ((context, index) {
        var imageInfo = consultationImages[index];
        final image = FConsultationContentImage(
          consultationFileInfo: imageInfo,
          onDoubleTap: () {
            _onTapConsultationImage(imageInfo);
          },
          onTap: () {
            _onTapConsultationImage(imageInfo);
          },
          serialNo: index + 1,
          description:
              " ${i18nBook.realTimeConsultation.uploader.t} ${imageInfo.creatorName!} ",
        );
        return FStack(
          children: [
            image,
            FPositioned(
              right: 0,
              child: FCheckbox<bool>(
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  fillColor: MaterialStateProperty.all(Colors.white),
                  checkColor: FTheme.ins.colorScheme.primary,
                  value: _selectedImags.contains(imageInfo.coverImageUrl),
                  isCheck: _selectedImags.contains(imageInfo.coverImageUrl),
                  visualDensity: VisualDensity(horizontal: -4, vertical: -4),
                  onChange: (dynamic value, bool? isCheck) {
                    if (_selectedImags.contains(imageInfo.coverImageUrl)) {
                      _selectedImags.remove(imageInfo.coverImageUrl);
                    } else {
                      _selectedImags.add(imageInfo.coverImageUrl ?? '');
                    }
                  }),
            ),
          ],
        );
      }),
    );
  }

  Future<void> _onTapConsultationImage(ConsultationFileDTO imageInfo) async {
    // 手机强制横屏
    if (FPlatform.isIOS || FPlatform.isAndroid) {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    }
    await Get.to(() => ConsultationImagePage(imageInfo));
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }
}
