import 'package:fis_jsonrpc/services/remedical.m.dart';
import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:flutter/material.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class MobileImagesShareDialog extends FStatefulWidget implements FPage {
  const MobileImagesShareDialog(
      {super.key,
      required this.imagesList,
      required this.recordCode,
      this.patientName});

  @override
  String get pageName => "MobileImagesShareDialog";

  final List<ImagesToShare> imagesList;

  final String? patientName;

  final String recordCode;

  @override
  FState<MobileImagesShareDialog> createState() =>
      _MobileImagesShareDialogState();
}

class _MobileImagesShareDialogState extends FState<MobileImagesShareDialog> {
  List<int> imagesSelected = [];
  int imagesSelectedCount = 0;

  bool get isSelectedAll => imagesSelected.length == imagesSelectedCount;

  /// 分享到微信
  void _shareToWechat() async {
    HapticFeedback.mediumImpact();
    String linkUrl = await _getShareUrl();
    if (linkUrl.isEmpty) {
      return;
    }
    var result = await isWeChatInstalled;
    if (!result) {
      PromptBox.toast(i18nBook.remedical.noOpenWx.t);
      return;
    }
    //分享 Icon
    String imageUrl =
        "https://flyinsono-bj-1300984704.cos.ap-beijing.myqcloud.com/FlyinsonoIcon.png";

    /// 分享到好友
    WeChatShareBaseModel model = WeChatShareWebPageModel(
      //链接
      linkUrl,
      //标题
      title: i18nBook.remedical.imagesShare.t,
      //描述
      description: widget.patientName ?? " ",
      //小图
      thumbnail: WeChatImage.network(imageUrl),
      //微信消息
      scene: WeChatScene.SESSION,
    );
    final rst = await shareToWeChat(model);
    logger.i("ReportManager - share by wechat|$rst|$linkUrl");
    if (rst) {
      print(i18nBook.remedical.shareSuccess.t);
      // PromptBox.toast("分享成功");
    } else {
      print(i18nBook.remedical.shareFailed.t);
      PromptBox.toast(i18nBook.remedical.shareFailed.t);
    }
  }

  /// 复制链接
  void _copyLink() async {
    HapticFeedback.mediumImpact();
    String linkUrl = await _getShareUrl();
    if (linkUrl.isEmpty) {
      return;
    }
    if (FPlatform.isWindows || FPlatform.isMacOS) {
      rpc.platform.copyToClipboard(linkUrl);
    } else {
      Clipboard.setData(ClipboardData(text: linkUrl));
    }
    PromptBox.toast(i18nBook.remedical.copySuccess.t);
  }

  /// 获取分享链接
  Future<String> _getShareUrl() async {
    if (imagesSelected.isEmpty) {
      PromptBox.toast(i18nBook.remedical.selectContentToShare.t);
      return "";
    }

    /// 将 index list 排序
    imagesSelected.sort((a, b) => a.compareTo(b));

    /// 传入 List<MeasureExportDetailDTO>
    List<MeasureExportDetailDTO> remedicalImages = [];
    for (int i = 0; i < imagesSelected.length; i++) {
      ImagesToShare image = widget.imagesList[imagesSelected[i]];
      remedicalImages.add(MeasureExportDetailDTO(
        sortNum: i,
        remedicalMeasuredInfoCode: "", // TODO 这里先传空，后续可优化
        sourceFileToken: image.sourceUrl,
        isVideoFile: image.fileType == ImageFileType.Video,
      ));
    }
    try {
      QueryShareExamPageResult url =
          await rpc.remedical.queryShareImagesPlayUrlAsync(
        QueryShareImagesPlayUrlRequest(
          token: Store.user.token,
          languageCode: i18nBook.locale.toCodeString('-'),
          remedicalImages: remedicalImages,
          recordCode: widget.recordCode,
        ),
      );
      if (url.shareExamPageUrl != null && url.shareExamPageUrl!.isNotEmpty) {
        return url.shareExamPageUrl!;
      } else {
        PromptBox.toast(i18nBook.remedical.getShareLinkFailed.t);
        return "";
      }
    } catch (e) {
      PromptBox.toast(i18nBook.remedical.getShareLinkFailed.t);
      return "";
    }
  }

  @override
  void initState() {
    super.initState();
    imagesSelectedCount = widget.imagesList.length;
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      clipBehavior: Clip.antiAlias,
      title: FText(
        i18nBook.remedical.selectContentToShare.t,
        style: TextStyle(color: Colors.white, fontSize: 16),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      contentPadding: EdgeInsets.all(0),
      insetPadding: EdgeInsets.all(10),
      isUseColumnLayout: true,
      children: [
        FExpanded(
          child: FContainer(
            width: Get.width,
            child: FListView.builder(
              shrinkWrap: true,
              itemCount: widget.imagesList.length,
              itemBuilder: (context, index) {
                return _buildEachImage(widget.imagesList[index], index);
              },
            ),
          ),
        ),
        FRow(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FContainer(
              margin: EdgeInsets.symmetric(horizontal: 20),
              child: FText(
                "${imagesSelected.length} / $imagesSelectedCount",
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            _buildSelectAllButton(),
          ],
        ),
        _buildShareButton(),
      ],
    );
  }

  // 每张图片区域
  FWidget _buildEachImage(ImagesToShare image, int index) {
    return FGestureDetector(
      businessParent: widget,
      name: "selectImage",
      onTap: () {
        HapticFeedback.mediumImpact();
        if (imagesSelected.contains(index)) {
          setState(() {
            imagesSelected.remove(index);
          });
        } else {
          setState(() {
            imagesSelected.add(index);
          });
        }
      },
      child: FAlign(
        alignment: Alignment.center,
        child: FContainer(
          margin: EdgeInsets.all(10),
          width: Get.width,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(10),
            border: Border.all(
              color: imagesSelected.contains(index)
                  ? Colors.blue
                  : Colors.transparent,
              width: 4,
            ),
          ),
          child: QuickFWidget(
            AspectRatio(
              aspectRatio: 4 / 3,
              child: Stack(
                children: [
                  _buildImage(image),
                  _buildIndexText(index),
                  _buildFileType(image.fileType),
                  _buildSourceText(image.source),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 图片主体
  Widget _buildImage(ImagesToShare image) {
    return Center(
      child: FImage.network(
        image.coverUrl,
        fit: BoxFit.contain,
        errorBuilder: ((context, error, stackTrace) {
          return Container(
            child: Text(i18nBook.common.error.t),
          );
        }),
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) {
            return child;
          }
          return Center(
            child: CircularProgressIndicator(
              value: loadingProgress.expectedTotalBytes != null
                  ? loadingProgress.cumulativeBytesLoaded /
                      loadingProgress.expectedTotalBytes!
                  : null,
            ),
          );
        },
      ),
    );
  }

  // 序号角标
  Widget _buildIndexText(int index) {
    return Align(
      alignment: Alignment.topLeft,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: Colors.grey.withOpacity(0.8),
        ),
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Text(
          "${index + 1}",
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  // 来源角标
  Widget _buildSourceText(ImageSource source) {
    String sourceText = "";
    switch (source) {
      case ImageSource.Cloud:
        sourceText = i18nBook.remedical.cloudImage.t;
        break;
      case ImageSource.Measure:
        sourceText = i18nBook.measure.measureImageShort.t;
        break;
      case ImageSource.AI:
        sourceText = i18nBook.remoteControl.aiImage.t;
        break;
    }
    return Align(
      alignment: Alignment.bottomRight,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: Colors.grey.withOpacity(0.8),
        ),
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Text(
          sourceText,
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  // 类型角标
  Widget _buildFileType(ImageFileType type) {
    return Align(
      alignment: Alignment.topRight,
      child: Container(
        margin: EdgeInsets.all(5),
        child: Icon(
          type == ImageFileType.Video
              ? Icons.video_collection_outlined
              : Icons.image,
          color: Colors.white,
        ),
      ),
    );
  }

  // 全选按钮
  FWidget _buildSelectAllButton() {
    return FTextButton(
      businessParent: widget,
      name: "select all",
      child: isSelectedAll
          ? FText(i18nBook.remedical.cancelAll.t)
          : FText(i18nBook.remedical.selectAll.t),
      onPressed: () {
        HapticFeedback.mediumImpact();
        if (isSelectedAll) {
          setState(() {
            imagesSelected = [];
          });
        } else {
          setState(() {
            imagesSelected = [];
            for (int i = 0; i < widget.imagesList.length; i++) {
              imagesSelected.add(i);
            }
          });
        }
      },
    );
  }

  // 分享按钮
  FWidget _buildShareButton() {
    return FRow(
      children: [
        FExpanded(
          child: FInkWell(
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(
                border: Border(
                  top:
                      BorderSide(color: Colors.grey.withOpacity(0.5), width: 1),
                ),
              ),
              child: Center(
                child: FText(i18nBook.remedical.copyLink.t),
              ),
            ),
            onTap: _copyLink,
          ),
        ),
        FExpanded(
          child: FInkWell(
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 10.5),
              color: Colors.blue,
              child: Center(
                child: FText(
                  i18nBook.remedical.wechatShare.t,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            onTap: _shareToWechat,
          ),
        ),
      ],
    );
  }
}

class ImagesToShare {
  String coverUrl;
  String sourceUrl;
  String? description;
  ImageFileType fileType;
  ImageSource source;
  ImagesToShare({
    required this.coverUrl,
    required this.sourceUrl,
    required this.fileType,
    required this.source,
    this.description,
  });
}

enum ImageFileType { Image, Video }

enum ImageSource { Cloud, Measure, AI }
