import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/liveConsultation.m.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/views/desktop/real_time_consultation/live_consultation/controller.dart';

/// 会诊直播间-截图列表
class ImageCaptureList extends FStatefulWidget {
  const ImageCaptureList({super.key});

  @override
  FState<ImageCaptureList> createState() => _CaptureImageListState();
}

class _CaptureImageListState extends FState<ImageCaptureList> {
  final _kisMobile = kIsMobile;

  @override
  FWidget build(BuildContext context) {
    return _CaptureImageListView(
      kisMobile: _kisMobile,
    );
  }
}

class _CaptureImageListView extends FisView<LiveConsultationController> {
  const _CaptureImageListView({Key? key, required this.kisMobile})
      : super(key: key);
  final bool kisMobile;
  @override
  FWidget build(BuildContext context) {
    return FisBuilder<LiveConsultationController>(
      initState: (state) => controller.initCaptureImageList(),
      id: "capture_image_list",
      builder: (_) {
        return _buildView(context);
      },
    );
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return FObx(
      () {
        if (!controller.state.isShowCaptureImageList)
          return _buildExpandButton();
        final _scrollController = ScrollController();
        return FContainer(
          width: kisMobile ? 100 : 120,
          margin: kisMobile
              ? EdgeInsets.only(
                  left: FSpacings.M, top: 60, bottom: FSpacings.XL)
              : EdgeInsets.symmetric(vertical: 80, horizontal: FSpacings.XXL),
          padding: EdgeInsets.symmetric(horizontal: 3, vertical: 10),
          decoration: BoxDecoration(
            color: Color.fromARGB(255, 45, 48, 50),
            borderRadius: BorderRadius.all(Radius.circular(10)),
            border: Border.all(
                width: kisMobile ? 1 : 1.5,
                color: Color.fromARGB(255, 170, 170, 170)),
          ),
          child: FColumn(
            children: [
              _buildListHead(),
              FSizedBox(height: 10),
              FExpanded(
                child: _buildListBody(_scrollController, context),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 列表主体
  FContainer _buildListBody(
      ScrollController _scrollController, BuildContext context) {
    return FContainer(
      child: QuickFWidget(ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: FObx(
          () {
            List<CaptureImage> displayImagesList = [];
            if (controller.state.captureImageUploadingCount > 0) {
              /// 下一帧执行
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                _scrollController.animateTo(0,
                    duration: Duration(milliseconds: 200),
                    curve: Curves.easeIn);
              });
              displayImagesList.addAll(
                List.generate(
                  controller.state.captureImageUploadingCount,
                  (index) => CaptureImage(type: CaptureImageType.uploading),
                ),
              );
              displayImagesList.addAll(
                List.generate(
                  controller.state.captureImageUploadOnceSum -
                      controller.state.captureImageUploadingCount,
                  (index) => CaptureImage(type: CaptureImageType.success),
                ),
              );
            }
            displayImagesList.addAll(controller.state.captureImageList
                .map((e) => CaptureImage(
                    type: e.fileDataType ==
                            RemedicalFileDataTypeEnum.ThirdVidSingle
                        ? CaptureImageType.image
                        : CaptureImageType.video,
                    previewImageUrl: e.previewImageUrl,
                    videoCoverUrl: e.coverImageUrl))
                .toList()
                .reversed
                .toList());
            if (displayImagesList.isEmpty)
              return FContainer(
                padding: EdgeInsets.symmetric(vertical: 20),
                child: FCenter(
                  child: FText(
                    i18nBook.realTimeConsultation.noCaptureImage.t,
                    style: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                ),
              );
            return FListView.builder(
              controller: _scrollController,
              itemCount: displayImagesList.length,
              prototypeItem: _buildImageInProgressing(''),
              padding: EdgeInsets.zero,
              itemBuilder: (context, index) {
                return FContainer(
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  child: _buildPreviewImage(displayImagesList[index]),
                );
              },
            );
          },
        ),
      )),
    );
  }

  /// 列表头部
  FWidget _buildListHead() {
    return FContainer(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: FRow(
        children: [
          FText(
            i18nBook.realTimeConsultation.captureImageList.t,
            style:
                TextStyle(color: Colors.white, fontSize: kisMobile ? 12 : 16),
          ),
          FExpanded(child: FContainer()),
          FTextTooltip(
            message: i18nBook.measure.collapseGroup.t,
            child: FInkWell(
              onTap: () => controller.state.isShowCaptureImageList = false,
              child: FIcon(
                Icons.expand_more,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 预览图
  FWidget _buildPreviewImage(CaptureImage image) {
    if (image.type == CaptureImageType.uploading)
      return _buildImageInProgressing(
          i18nBook.realTimeConsultation.uploading.t);
    if (image.type == CaptureImageType.success)
      return _buildImageInProgressing(
          i18nBook.realTimeConsultation.uploadFinished.t);
    return _buildCaptureImagePreview(image);
  }

  /// 未准备好的图片
  FWidget _buildImageInProgressing(String text) {
    return FContainer(
      margin: EdgeInsets.only(bottom: 10),
      child: FContainer(
        width: 80,
        height: 60,
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          border:
              Border.all(width: 1.5, color: Color.fromARGB(255, 200, 200, 200)),
        ),
        child: FCenter(
          child: FText(
            text,
            style: TextStyle(
                color: Color.fromARGB(255, 200, 200, 200), fontSize: 14),
          ),
        ),
      ),
    );
  }

  /// 截图预览图
  FWidget _buildCaptureImagePreview(CaptureImage image) {
    if (image.previewImageUrl == null || image.previewImageUrl!.isEmpty)
      return FContainer();
    return FContainer(
      margin: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        border:
            Border.all(width: 1.5, color: Color.fromARGB(255, 200, 200, 200)),
      ),
      child: FStack(
        children: [
          FContainer(
            height: 60,
            color: Colors.black,
            child: FCenter(
              child: FImage.network(
                image.previewImageUrl ?? '',
                fit: BoxFit.cover,
              ),
            ),
          ),
          FPositioned(
            right: 0,
            bottom: 0,
            child: FContainer(
              width: 20,
              height: 20,
              child: FCenter(
                child: FIcon(
                  image.type == CaptureImageType.video
                      ? Icons.play_arrow
                      : Icons.image,
                  color: Colors.white,
                  size: 16,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 展开截图列表按钮
  FWidget _buildExpandButton() {
    return FInkWell(
      onTap: () {
        controller.state.isShowCaptureImageList = true;
      },
      child: FContainer(
        width: 60,
        height: 40,
        margin: kisMobile
            ? EdgeInsets.symmetric(
                vertical: FSpacings.XXL, horizontal: FSpacings.M)
            : EdgeInsets.symmetric(vertical: 80, horizontal: FSpacings.XXL),
        decoration: BoxDecoration(
          color: Color.fromARGB(255, 45, 48, 50),

          /// 右上右下圆角
          borderRadius: BorderRadius.all(Radius.circular(10)),
          border:
              Border.all(width: 1.5, color: Color.fromARGB(255, 170, 170, 170)),
          // color: Color.fromARGB(255, 14, 16, 17)
        ),
        child: FIcon(
          Icons.perm_media,
          color: Colors.white,
          size: 20,
        ),
      ),
    );
  }
}

enum CaptureImageType {
  /// 图片
  image,

  /// 视频
  video,

  /// 上传中
  uploading,

  /// 上传成功
  success,
}

class CaptureImage {
  /// 图片类型
  CaptureImageType type;

  /// 预览图地址
  String? previewImageUrl;

  /// 首帧图地址
  String? videoCoverUrl;

  CaptureImage({
    required this.type,
    this.previewImageUrl,
    this.videoCoverUrl,
  }) : assert(
            type == CaptureImageType.image || type == CaptureImageType.video
                ? previewImageUrl != null && videoCoverUrl != null
                : true,
            'image or video must have previewImageUrl and videoCoverUrl');
}
