import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.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/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/remedical/image_pool/widgets/image_describe_view.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;
import 'entitys/Image_info.dart';
import 'index.dart';
import 'widgets/image_play_content_view.dart';
import 'package:fis_measure/process/workspace/rpc_bridge.dart';

class ImagePoolPage extends FisView<ImagePoolController> implements FPage {
  ImagePoolPage({this.pageName = "ImagePoolPage", Key? key}) : super(key: key);
  static const double _tabWidth = 95;
  static const double _tabHeight = 40;
  static const double _previewHeaderHeight = 187;
  static const double _previewImagesWidth = 198;
  static const double _previeAreaWidth = 311;
  static const double _headerHeight = 110;
  //底部按钮组内按钮间距
  static const double _bottomButtonsSpace = 10;
  //底部按钮组按钮宽度
  static const double _bottomButtonsWidth = 30;
  final ScrollController _scrollController = ScrollController();

  @override
  final String pageName;

  // 主视图
  FWidget _buildImagePoolPageView(BuildContext context) {
    return FContainer(
      color: Colors.grey.shade200,
      child: FRow(
        children: [
          FContainer(
            width: _previewImagesWidth,
            margin: EdgeInsets.only(top: 15, right: 10, left: 10),
            child: FColumn(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildImagesSelect(),
                FExpanded(
                    child: FContainer(
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                  child: FColumn(
                    children: [
                      _buildImagesPreview(context),
                      FExpanded(child: _buildImagesLayout()),
                    ],
                  ),
                )),
              ],
            ),
          ),
          FVerticalDivider(
            width: 1,
            color: Colors.grey,
            thickness: 1,
          ),
          _buildMainImagesContentView(),
        ],
      ),
    );
  }

  @override
  FWidget build(BuildContext context) {
    controller.initParameters();
    controller.initDatas();
    return _buildImagePoolPageView(context);
  }

  FWidget _buildImagesSelect() {
    final select = FObx(
      () => FSelect<FSelectOptionModel, int>(
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        source: [
          FSelectOptionModel<int>(
            title: i18nBook.remedical.cloudImageShort.t,
            value: 0,
          ),
          FSelectOptionModel<int>(
            title: i18nBook.measure.measureImageShort.t,
            value: 1,
          ),
          FSelectOptionModel<int>(
            title: i18nBook.remoteControl.aiImage.t,
            value: 2,
          ),
        ],
        decoration: BoxDecoration(color: Colors.white),
        value: controller.state.selectedIndex,
        optionValueExtractor: (data) => data.value,
        optionLabelExtractor: (data) => data.title,
        onSelectChanged: (value, index) {
          _selectChange(value);
        },
      ),
    );
    return FContainer(
      margin: EdgeInsets.only(
        bottom: 15,
      ),
      child: select,
    );
  }

  ///单个预览图片视图
  FWidget _buildPreviewImageItem(List<ExamImageInfo> images, int index) {
    return FContainer(
      height: 160,
      child: FStack(
        alignment: Alignment.center,
        children: [
          FContainer(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 5, bottom: 5, right: 5, left: 5),
            color: Colors.black,
            child: FImage.network(
              images[index].previewUrl,
              height: 100,
            ),
          ),
          FPositioned(
            left: 6,
            top: 3,
            child: FText(
              (index + 1).toString(),
              style: TextStyle(color: Colors.white),
            ),
          ),
          if (!images[index].isImage) ...[
            FContainer(
              alignment: Alignment.center,
              child: FIcon(
                Icons.play_circle_outline,
                size: 30,
                color: Colors.white,
              ),
            ),
          ],
          ImageDescribeView(
            diagnosisConclusion: images[index].diagnosisConclusion,
            diagnosisOrgans: images[index].diagnosisOrgans,
            application: images[index].application,
            applicationCategory: images[index].applicationCategory,
          ),
        ],
      ),
    );
  }

  ///图像预览列表
  FWidget _buildImagesPreview(BuildContext context) {
    return FObx(() {
      List<ExamImageInfo> images = controller.state.imageInfos;
      final imageHeight =
          MediaQuery.of(context).size.height - _previewHeaderHeight;
      return FContainer(
        padding: EdgeInsets.only(top: 10, bottom: 10),
        height: imageHeight,
        child: FListView.builder(
            shrinkWrap: true,
            controller: _scrollController,
            itemCount: images.length,
            itemBuilder: (_, index) {
              return FMouseRegion(
                cursor: SystemMouseCursors.click,
                child: FGestureDetector(
                  name: "selectedImage:$index",
                  businessParent: this,
                  onTap: () {
                    controller.selectedImage(index, images.length);
                  },
                  child: _buildPreviewImageItem(images, index),
                ),
              );
            }),
      );
    });
  }

  ///图像内容视图
  FWidget _buildMainImagesContentView() {
    return FObx(
      () {
        final currentIndex = controller.state.currentPageIndex;
        final imagePage = controller.state.imagePags[currentIndex];
        var imageContentWidth =
            MediaQuery.of(Get.context!).size.width - _previeAreaWidth;
        var imageContentHeight =
            MediaQuery.of(Get.context!).size.height - _headerHeight;
        if (imagePage == null) {
          return FColumn(
            children: [
              FSizedBox(
                width: imageContentWidth,
                height: imageContentHeight,
                child: FCenter(
                  child: _buildEmptyOrLoading(),
                ),
              ),
              const FSizedBox(height: 5),
              _buildOperateButtons(),
            ],
          );
        }
        List<ExamImageInfo> imageInfos = imagePage.images;
        final _imagesView = imageInfos.map((imageInfo) {
          var imageContentView = ImagePlayContentView(
            imageInfo,
            diagnosisConclusion: imageInfo.diagnosisConclusion,
            diagnosisOrgans: imageInfo.diagnosisOrgans,
            onTap: () {
              var selectedImages = controller.state.selectedImages;
              if (selectedImages.any((element) =>
                  element.remedicalMeasuredInfoCode ==
                  imageInfo.remedicalCode)) {
                selectedImages.removeWhere((e) =>
                    e.remedicalMeasuredInfoCode == imageInfo.remedicalCode);
                if (controller.state.isSelectAllImages) {
                  //取消全选
                  controller.state.isSelectAllImages = false;
                }
              } else {
                selectedImages.add(
                  MeasureExportDetailDTO(
                    remedicalMeasuredInfoCode: imageInfo.remedicalCode,
                    sortNum: imageInfo.index + 1,
                  ),
                );
                if (selectedImages.length ==
                    controller.state.remedicalMeasured.length) {
                  ///全选
                  controller.state.isSelectAllImages = true;
                }
              }
            },
          );
          if (imageInfo.imageType == ExamImageType.MeasureImage) {
            return imageContentView;
          } else {
            return FMouseRegion(
              cursor: SystemMouseCursors.click,
              child: FGestureDetector(
                onDoubleTap: () {
                  if (imageInfo.imageType == ExamImageType.AiImage) {
                    RPCBridge.ins.source = VidImageSource.AiResultModifier;
                  } else {
                    RPCBridge.ins.source = VidImageSource.Remedical;
                  }
                  controller.openImageMeasure(
                    imageInfo,
                  );
                },
                businessParent: this,
                name: 'ImagePlayContentView',
                child: imageContentView,
              ),
            );
          }
        }).toList();
        var childAspectRatio = 1.9;
        return FColumn(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FExpanded(
              child: FContainer(
                padding: EdgeInsets.symmetric(horizontal: 12),
                width: imageContentWidth,
                alignment: Alignment.topCenter,
                child: FGridView(
                  controller: controller.imagesController,
                  addAutomaticKeepAlives: true,
                  shrinkWrap: true,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: controller.state.column,
                    childAspectRatio: childAspectRatio,
                  ),
                  children: _imagesView,
                ),
              ),
            ),
            _buildOperateButtons(),
            const FSizedBox(height: 20),
          ],
        );
      },
    );
  }

  ///图片布局
  FWidget _buildImagesLayout() {
    const option1 = '1 X 1';
    const option2 = '2 X 2';
    const option3 = '3 X 3';
    const option4 = '4 X 4';
    List<String> source = [option1, option2, option3, option4];
    String selectedValue = option3;
    return FContainer(
      child: FRow(
        children: [
          FSizedBox(width: 10),
          FText(i18nBook.common.layout.t),
          FExpanded(
            child: FContainer(
              padding: EdgeInsets.all(5),
              child: FSelect(
                source: source,
                fontFamily: FTheme.ins.localeSetting.fontFamily,
                // width: 140,
                value: selectedValue,
                optionValueExtractor: (String v) {
                  return v;
                },
                optionLabelExtractor: (String v) {
                  return v;
                },
                onSelectChanged: (value, i) {
                  selectedValue = value == null ? '' : value.toString();
                  switch (selectedValue) {
                    case option1:
                      controller.state.column = 1;
                      break;
                    case option2:
                      controller.state.column = 2;
                      break;
                    case option3:
                      controller.state.column = 3;
                      break;
                    case option4:
                      controller.state.column = 4;
                      break;
                  }
                  controller.state.canPlayImages.clear();
                  controller.state.currentPageIndex = 0;
                  controller.initPlayVideos();
                  controller.onImageStateChange(0);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildEmptyOrLoading() {
    if (controller.state.isShowLoading) {
      return QuickFWidget(
        CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(
            FTheme.ins.colorScheme.primary,
          ),
        ),
      );
    } else {
      return FText(i18nBook.common.noneDataTip.t);
    }
  }

  ///底部操作行按钮
  FWidget _buildOperateButtons() {
    var imageContentWidth =
        MediaQuery.of(Get.context!).size.width - _previeAreaWidth;
    var noData = controller.state.imagePags.length == 0;
    var onLastPage = controller.state.currentPageIndex ==
        controller.state.imagePags.length - 1;
    var onFirstPage = controller.state.currentPageIndex == 0;
    return FSizedBox(
      width: imageContentWidth,
      child: FStack(
        children: [
          FRow(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildFunctionButton(
                  "homePage",
                  Icons.skip_previous,
                  (onFirstPage) || noData
                      ? null
                      : () {
                          controller.jumpToPage(0);
                        }),
              FSizedBox(width: _bottomButtonsSpace),
              _buildFunctionButton(
                "previousPage",
                Icons.navigate_before,
                (onFirstPage) || noData
                    ? null
                    : () {
                        controller.previewsPage();
                      },
              ),
              FSizedBox(width: _bottomButtonsSpace),
              ...controller.state.pageIndexs.map(((e) {
                return _buildPageNumButton(e);
              })),
              _buildFunctionButton(
                  "nextPage",
                  Icons.navigate_next,
                  (onLastPage || noData)
                      ? null
                      : () {
                          controller.nextPage();
                        }),
              FSizedBox(width: _bottomButtonsSpace),
              _buildFunctionButton(
                "endPage",
                Icons.skip_next,
                (onLastPage || noData)
                    ? null
                    : () {
                        controller
                            .jumpToPage(controller.state.imagePags.length - 1);
                      },
              ),
            ],
          ),
          if (controller.state.selectedIndex == 1) ...[
            FPositioned(
              left: FSpacings.L,
              top: 0,
              bottom: 0,
              child: _buildExportRow(),
            )
          ],
        ],
      ),
    );
  }

  /// 构建功能按钮【首页】【尾页】【上一页】等。。。
  FWidget _buildFunctionButton(
      String name, IconData icon, Function()? onPressed) {
    return FContainer(
      width: _bottomButtonsWidth,
      child: FElevatedButton(
        style: ButtonStyle(
          padding: MaterialStateProperty.all(EdgeInsets.zero),
        ),
        businessParent: this,
        name: name,
        child: FIcon(
          icon,
          size: 20,
        ),
        onPressed: onPressed,
      ),
    );
  }

  FWidget _buildPageNumButton(int index) {
    var currentPageIndex = controller.state.currentPageIndex;
    return FContainer(
      width: _bottomButtonsWidth,
      margin: EdgeInsets.only(right: _bottomButtonsSpace),
      child: FOutlinedButton(
        businessParent: this,
        name: "selectedIndex:$currentPageIndex",
        child: FText(
          (index + 1).toString(),
          style: TextStyle(
              color: index == currentPageIndex
                  ? Colors.white
                  : FTheme.ins.colorScheme.primary),
        ),
        style: ButtonStyle(
            padding: MaterialStateProperty.all(EdgeInsets.zero),
            backgroundColor: MaterialStateProperty.all(
                index == controller.state.currentPageIndex
                    ? FTheme.ins.colorScheme.secondary
                    : null)),
        onPressed: () {
          controller.jumpToPage(index);
        },
      ),
    );
  }

  FWidget _buildExportRow() {
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.XL),
        FText(i18nBook.common.ofTerm
            .translate([controller.state.remedicalMeasured.length.toString()])),
        const FSizedBox(width: FSpacings.MINI_BUTTON),
        QuickFWidget(
          Obx(
            () => Checkbox(
              value: controller.state.isSelectAllImages,
              onChanged: (v) {
                controller.state.isSelectAllImages = v ?? false;
                if (v ?? false) {
                  controller.state.selectedImages.clear();
                  List<MeasureExportDetailDTO> selectedImages = [];
                  var allImages = controller.state.remedicalMeasured
                      .map((e) => e.remedicalMeasuredInfoCode)
                      .toList();
                  var index = 1;
                  for (var image in allImages) {
                    selectedImages.add(
                      MeasureExportDetailDTO(
                        remedicalMeasuredInfoCode: image,
                        sortNum: index,
                      ),
                    );
                    index++;
                  }
                  controller.state.selectedImages = selectedImages;
                  controller.onSelectAllImageChange.emit(this, true);
                } else {
                  controller.state.selectedImages.clear();
                  controller.onSelectAllImageChange.emit(this, false);
                }
              },
            ),
          ),
        ),
        const FSizedBox(width: FSpacings.M),
        FElevatedButton(
          child: FText(i18nBook.remedical.resultsExported.t),
          onPressed: controller.batchExportMeasureData,
          businessParent: this,
          name: 'Bulk Export',
        ),
        const FSizedBox(width: FSpacings.MINI_BUTTON),
        FObx(() {
          if (controller.state.isExporting) {
            return FRow(
              children: [
                FText(i18nBook.realTimeConsultation.exporting.t),
                const FSizedBox(width: FSpacings.M),
                FSizedBox(
                  height: FSpacings.XL,
                  width: FSpacings.XL,
                  child: FCircularProgressIndicator(),
                ),
              ],
            );
          }
          return FSizedBox();
        }),
        FObx(() {
          if (controller.state.isExportFinish) {
            return FTextButton(
              businessParent: this,
              name: 'download',
              onPressed: () {
                var downloadUrl = controller.state.measureDataDownloadUrl;
                if (FPlatform.isPureWeb) {
                  html.AnchorElement anchorElement = new html.AnchorElement(
                      href: controller.state.measureDataDownloadUrl);
                  anchorElement.download = 'filename.extension';
                  anchorElement.click();
                } else {
                  rpc.platform.downloadMeasureData(downloadUrl);
                }
                controller.state.isExportFinish = false;
              },
              child: FText(
                i18nBook.common.clickToDownload.t,
                style: TextStyle(
                  decoration: TextDecoration.underline, // 添加下划线
                ),
              ),
            );
          }
          return FSizedBox();
        }),
      ],
    );
  }

  Future<void> _selectChange(int? value) async {
    switch (value) {
      // 云端图像
      case 0:
        controller.state.selectedIndex = 0;
        controller.state.canPlayImages.clear();
        await controller.getRemedicalListByRecordInfoAsync();
        controller.state.currentPageIndex = 0;
        controller.initPlayVideos();
        break;
      // 测量图像
      case 1:
        controller.state.currentPageIndex = 0;
        await controller.findRemedicalMeasuredInfoAsync();
        controller.state.canPlayImages.forEach((key, value) {
          value.isPlayEnd = true;
        });
        controller.state.isShowPlayIconMap.forEach((key, value) {
          value = true;
        });
        controller.state.selectedIndex = 1;
        controller.getImageUrls();
        controller.loadPageIndexs();
        break;
      // ai图像
      case 2:
        controller.state.currentPageIndex = 0;
        controller.state.canPlayImages.clear();
        controller.state.selectedIndex = 2;
        await controller.findAiImagesAsync();
        controller.getImageUrls();
        controller.loadPageIndexs();
        break;
      default:
        break;
    }
  }
}
