import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/mobile_images_share_dialog.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/image_preview_mobile.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:fis_common/index.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:fis_ui/widgets/scroll/refreshIndicator.dart';
import 'package:fis_measure/view/measure/measure_images_bar.dart';
import 'package:fis_ui/widgets/insta_image_viewer/lib/insta_image_viewer.dart';

/// 图像预览列表界面（不是图像选择器）
class ExamImagesListView extends FStatefulWidget implements FPage {
  final String? patientCode;
  final String? patientName;
  final bool isCanWriteReport;
  final String recordCode;
  final List<RemedicalListResult> cloudImageInfos; // 云端图像-来自超声机
  final List<RemedicalMeasuredInfoDTO> measureImages; // 测量图像-来自测量页
  final List<RemedicalAISelectedInfoDTO> aiImages; // AI 图像-来自 AI 编辑页
  final Future<List<RemedicalListResult>> Function()? onRefreshCloudImages;

  @override
  final String pageName = 'ExamImagesListView';

  ExamImagesListView({
    this.patientCode,
    this.patientName,
    this.onRefreshCloudImages,
    this.isCanWriteReport = false,
    required this.recordCode,
    required this.cloudImageInfos,
    required this.measureImages,
    required this.aiImages,
  });

  @override
  FState<ExamImagesListView> createState() => _ExamImagesListViewState();
}

class _ExamImagesListViewState extends FState<ExamImagesListView> {
  int _imageScannedIndex = 0;
  _SelectImageSource _imageSource = _SelectImageSource.Cloud;
  List<RemedicalMeasuredInfoDTO> _measureImages = [];
  List<RemedicalAISelectedInfoDTO> _aiImages = [];
  List<RemedicalListResult> _cloudImageInfos = [];

  @override
  void initState() {
    super.initState();
    _cloudImageInfos = widget.cloudImageInfos;
    _measureImages = widget.measureImages;
    _aiImages = widget.aiImages;
  }

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

  /// 图像显示区域
  FWidget _buildImageContentView(BuildContext context) {
    FWidget contentView = NoDataWidget();
    switch (_imageSource) {
      case _SelectImageSource.Cloud:
        contentView = _buildCloudImagesContentView();
        break;
      case _SelectImageSource.Measure:
        contentView = _buildMeasureImagsContentView();
        break;
      case _SelectImageSource.AI:
        contentView = _buildAIImagsContentView();
        break;
    }
    return FColumn(
      children: [
        _buildScanDate(),
        FExpanded(child: contentView),
      ],
    );
  }

  ///图像集合
  FWidget _buildImagesView(
    RemedicalItemList remedicalItem,
    int startIndex,
  ) {
    final remedicalList = remedicalItem.remedicalList ?? [];
    final languageConfigManager = Get.find<ILanguageConfigManager>();
    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 remedicalInfo = remedicalItem.remedicalList![index];
        final remedicalCode = remedicalInfo.remedicalCode ?? '';
        final terminalImageDTO = remedicalInfo.terminalImages;

        if (terminalImageDTO == null) {
          return FFittedBox(
            fit: BoxFit.scaleDown,
            child: FSizedBox(),
          );
        }
        TerminalImage? terminalImage = TerminalImage(
          imageUrl: terminalImageDTO.imageUrl,
          previewUrl: terminalImageDTO.previewUrl,
          coverImageUrl: terminalImageDTO.coverImageUrl,
        );
        final image = ImagePreviewMobile(
          image: terminalImage,
          index: startIndex + index - 1,
          remedicalCode: remedicalCode,
          remedicalInfo: remedicalInfo,
          application: application,
          patientCode: widget.patientCode,
          isCanCreateReport: widget.isCanWriteReport,
        );
        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: cardWrap),
        ],
      ),
    );
  }

  /// 顶层 App Bar
  FAppBar _buildAppBar() {
    return FAppBar(
      actions: [
        // FSizedBox(
        //   width: 56, // 为了让 SourceSelector 居中显示
        // )
        FIconButton(
          name: "share",
          businessParent: this.widget,
          icon: FIcon(
            Icons.share,
            size: 20,
          ),
          onPressed: () {
            /// 打开图像分享器
            _openImagesShare();
          },
        ),
      ],
      title: _buildSourceSelector(),
      elevation: 0,
      centerTitle: true,
      leading: FIconButton(
        name: "back",
        businessParent: this.widget,
        icon: FIcon(
          Icons.arrow_back_ios_new,
          size: 20,
        ),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  /// 扫查日期
  FWidget _buildScanDate() {
    return FContainer(
      decoration: new BoxDecoration(
        color: FTheme.ins.colorScheme.secondary,
      ),
      padding: EdgeInsets.only(bottom: 3),
      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),
            ),
          ],
        ],
      ),
    );
  }

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

  /// App Bar 上的图像来源选择器
  FWidget _buildSourceSelector() {
    List<SourceSelectModel> selectedItems = [
      SourceSelectModel(
        name: i18nBook.remedical.cloudImageShort.t,
        source: _SelectImageSource.Cloud,
      ),
      SourceSelectModel(
        name: i18nBook.measure.measureImageShort.t,
        source: _SelectImageSource.Measure,
      ),
      SourceSelectModel(
        name: i18nBook.remoteControl.aiImage.t,
        source: _SelectImageSource.AI,
      ),
    ];
    return FContainer(
      width: 150,
      height: 50,
      child: FSelect<SourceSelectModel, _SelectImageSource>(
        source: selectedItems,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        value: _imageSource,
        optionAlignment: Alignment.center,
        width: i18nBook.isCurrentChinese
            ? 150
            : i18nBook.isCurrentRussian
                ? 200
                : 210,
        decoration: BoxDecoration(
            border: Border.all(width: 0, color: Colors.transparent)),
        optionValueExtractor: (data) => data.source,
        optionLabelExtractor: (data) => data.name,
        textColor: Colors.white,
        dropDownIcon: Icon(
          Icons.arrow_drop_down,
          color: Colors.white,
        ),
        buttonDecoration: BoxDecoration(),
        onSelectChanged: (value, index) {
          if (value != null) {
            setState(() {
              _imageSource = value;
              _imageScannedIndex = 0;
            });
          }
        },
      ),
    );
  }

  /// 云端图像视图
  FWidget _buildCloudImagesContentView() {
    int length = 0;
    int imageCount = 0;
    FWidget result = NoDataWidget();
    if (_cloudImageInfos.isNotEmpty) {
      final remedicalList =
          _cloudImageInfos[_imageScannedIndex].remedicalItemList ?? [];
      length = remedicalList.length;
      for (RemedicalItemList r in remedicalList) {
        if (r.remedicalList != null && r.remedicalList!.isNotEmpty) {
          imageCount += r.remedicalList?.length ?? 0;
        }
      }
    }
    if (imageCount == 0 || length == 0) {
      result = NoDataWidget();
    } else {
      List<int> startIndexOfEachGroup = [1];
      _cloudImageInfos.first.remedicalItemList?.forEach((element) {
        final existNum = startIndexOfEachGroup.last;
        startIndexOfEachGroup.add(element.remedicalList!.length + existNum);
      });

      List<FWidget> listChildren = List<FWidget>.generate(
        length,
        (index) {
          return _buildImagesView(
            _cloudImageInfos[_imageScannedIndex].remedicalItemList![index],
            startIndexOfEachGroup[index],
          );
        },
      );

      result = FSingleChildScrollView(
        child: FColumn(
          children: listChildren,
        ),
      );
    }

    if (widget.onRefreshCloudImages != null) {
      return FRefreshIndicator(
        onRefresh: () async {
          var infos = await widget.onRefreshCloudImages!.call();
          setState(() {
            _cloudImageInfos = infos;
          });
        },
        child: result,
      );
    } else {
      return result;
    }
  }

  /// 测量图像
  FWidget _buildMeasureImagsContentView() {
    final allWidth = Get.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 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,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  /// AI图像
  FWidget _buildAIImagsContentView() {
    final allWidth = Get.width;
    final width = (allWidth - 40) / 2;
    if (_aiImages.isEmpty) {
      return NoDataWidget();
    }
    return FContainer(
      alignment: Alignment.topCenter,
      margin: EdgeInsets.only(top: 10, left: 10, right: 10),
      child: FGridView.builder(
        itemCount: _aiImages.length,
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisSpacing: 10,
          crossAxisCount: 2,
        ),
        itemBuilder: (BuildContext context, int index) {
          final imageUrl = _aiImages[index].aICdnFileToken ?? '';
          return 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(
                        imageUrl,
                        fit: BoxFit.cover,
                      ),
                    ),
                    disableSwipeToDismiss: true,
                    isVertical: true,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  void _openImagesShare() {
    final List<ImagesToShare> imagesToShare = [];
    // 遍历云端图像
    if (_cloudImageInfos.isNotEmpty) {
      final remedicalList =
          _cloudImageInfos[_imageScannedIndex].remedicalItemList ?? [];
      for (RemedicalItemList r in remedicalList) {
        if (r.remedicalList != null && r.remedicalList!.isNotEmpty) {
          for (RemedicalInfoDTO remedicalInfo in r.remedicalList!) {
            final terminalImageDTO = remedicalInfo.terminalImages;
            if (terminalImageDTO == null) {
              continue;
            }
            final image = ImagesToShare(
              source: ImageSource.Cloud,
              fileType: getFileType(remedicalInfo.fileDataType),
              coverUrl: terminalImageDTO.coverImageUrl ?? '',
              sourceUrl: terminalImageDTO.imageUrl ?? '',
            );
            imagesToShare.add(image);
          }
        }
      }
    }

    // 遍历测量图像
    for (RemedicalMeasuredInfoDTO measuredInfo in _measureImages) {
      final image = ImagesToShare(
        source: ImageSource.Measure,
        fileType: ImageFileType.Image,
        coverUrl: measuredInfo.previewFileToken ?? "",
        sourceUrl: measuredInfo.measuredFileToken ?? "",
      );
      imagesToShare.add(image);
    }

    // 遍历 AI 图像
    // for (RemedicalAISelectedInfoDTO aiInfo in _aiImages) {
    //   final image = ImagesToShare(
    //     source: ImageSource.AI,
    //     fileType: ImageFileType.Image,
    //     coverUrl: aiInfo.aICdnFileToken ?? "",
    //     sourceUrl: aiInfo.orginalFileToken ?? "",
    //   );
    //   imagesToShare.add(image);
    // }

    if (imagesToShare.isEmpty) {
      // 提示无图像可分享
      PromptBox.toast(i18nBook.remedical.noImageToShare.t);
      return;
    }

    Get.dialog(
      MobileImagesShareDialog(
        recordCode: widget.recordCode,
        patientName: widget.patientName,
        imagesList: imagesToShare,
      ),
    );
  }

  static const singleImageType = [
    RemedicalFileDataTypeEnum.Image,
    RemedicalFileDataTypeEnum.ThirdVidSingle,
    RemedicalFileDataTypeEnum.VinnoVidSingle,
  ];
  ImageFileType getFileType(RemedicalFileDataTypeEnum fileType) {
    if (singleImageType.contains(fileType)) {
      return ImageFileType.Image;
    }
    return ImageFileType.Video;
  }
}

enum _SelectImageSource {
  Cloud,
  Measure,
  AI,
}

class SourceSelectModel {
  final String name;
  final _SelectImageSource source;
  SourceSelectModel({required this.name, required this.source});
}
