import 'package:fis_lib_media_rt/config.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/widgets/sub_view/sub_view.dart';
import 'package:fis_lib_media_rt/implementations/trtc/channel.dart';
import 'package:fis_lib_media_rt/implementations/trtc/widgets/remote_merged_view_sub.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../implementations/nt_rtmp/channel/channel.dart';
import '../implementations/trtc/capturer/index.dart';
import '../interface/channel.dart';

/// 实时画面视图（合图模式）旧版超声机
class FRTMergedChannelSubViewOldVersion extends StatelessWidget {
  /// 播放路源
  final IPlayChannel channel;

  /// 指定尺寸
  final Size? size;

  /// 总画面尺寸
  final Size videoSize;

  /// 主画面尺寸
  final Size mainViewSize;

  /// 子画面尺寸
  final Size cameraViewSize;

  /// 视图对齐方式
  final AlignmentGeometry viewAlignment;

  /// 主视图外部容器最大尺寸
  final Size? mainViewContainerMaxSize;

  // 只有 camera 视图会进入此处

  const FRTMergedChannelSubViewOldVersion(
    this.channel, {
    super.key,
    this.size,
    this.mainViewContainerMaxSize,
    required this.videoSize,
    required this.mainViewSize,
    required this.cameraViewSize,
    required this.viewAlignment,
  });

  @override
  Widget build(BuildContext context) {
    if (FRTMediaConfig.serviceType == FRealTimeMediaServiceType.ntRtmp) {
      return NTRemoteSubView(channel: channel as NTPlayChannel);
    }
    return LayoutBuilder(builder: (_, constraints) {
      // 为了使得移动端上的Texture纹理渲染正常，此处的主画面容器需要写死为1280x720
      Size displayViewSize = kIsWeb ? cameraViewSize : cameraViewSize;
      // 是否使用高度缩放
      final bool isHeightConstraint =
          constraints.maxWidth / constraints.maxHeight >
              displayViewSize.width / displayViewSize.height;
      double scale = isHeightConstraint
          ? videoSize.height / displayViewSize.height
          : videoSize.width / displayViewSize.width;

      /// 视图宽高比
      final double viewRatio = displayViewSize.width / displayViewSize.height;

      /// Container 的尺寸需要缩小，来满足视图的宽高比，要么宽度缩小，要么高度缩小
      final Size containerSize = viewRatio < 1
          ? Size(
              constraints.maxHeight * viewRatio,
              constraints.maxHeight,
            )
          : Size(
              constraints.maxWidth,
              constraints.maxWidth / viewRatio,
            );

      /// 通过分辨率选择合适的 transform 方案
      CssTransform cssTransform = CssTransform();
      MobileTransform mobileTransform = MobileTransform();

      if (kIsWeb) {
        cssTransform =
            _countCssTransform(videoSize, mainViewSize, cameraViewSize);
      } else {
        mobileTransform =
            _countMobileTransform(videoSize, mainViewSize, cameraViewSize);
      }

      print("最终使用的 containerSize 为: $containerSize");
      return kIsWeb
          ? _buildMergedWebCameraView(containerSize, scale, cssTransform)
          : _buildMergedMobileCameraView(containerSize, scale, mobileTransform);
    });
  }

  Widget _buildMergedWebCameraView(
      Size containerSize, double scale, CssTransform transform) {
    return Container(
      color: Colors.black,
      width: containerSize.width,
      height: containerSize.height,
      child: ClipRect(
        child: Stack(
          children: [
            FractionalTranslation(
              translation: const Offset(0, 0),
              child: Transform.scale(
                alignment: Alignment.topLeft,
                scale: 1,
                child: TrtcRemoteMergedViewSub(
                  channel as TrtcPlayChannel,
                  transform: transform,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMergedMobileCameraView(
      Size containerSize, double scale, MobileTransform transform) {
    return Align(
      alignment: Alignment.center,
      child: SizedBox(
        width: containerSize.width,
        height: containerSize.height,
        child: ClipRect(
          child: Stack(
            children: [
              FractionalTranslation(
                translation: transform.offset,
                child: Transform.scale(
                  alignment: Alignment.bottomRight,
                  scaleX: transform.scaleX,
                  scaleY: transform.scaleY,
                  child: Container(
                      margin: const EdgeInsets.only(left: 0.5),
                      child:
                          TrtcRemoteMergedViewSub(channel as TrtcPlayChannel)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 通过参数计算出合适的裁图方式
  CssTransform _countCssTransform(
      Size videoSize, Size mainView, Size cameraView) {
    if (videoSize.height == 720) {
      return CssTransform(
        scaleX: 2,
        scaleY: 4,
        translateX: 0,
        translateY: 0,
      );
    } else if (videoSize.height == 1080 || videoSize.height == 1088) {
      return CssTransform(
        scaleX: 3,
        scaleY: 9,
        translateX: 0,
        translateY: double2percent(1 - (mainView.height + 160) / 1440),
      );
    }
    print(
        "✨ videoSize: $videoSize mainView: $mainView cameraView: $cameraView  该参数下无合适的匹配项");
    return const CssTransform.empty();
  }

  // 通过参数计算出合适的裁图方式
  MobileTransform _countMobileTransform(
      Size videoSize, Size mainView, Size cameraView) {
    if (videoSize.height == 720) {
      return MobileTransform(
        offset: Offset.zero,
        scaleX: 2,
        scaleY: 4,
      );
    } else if (videoSize.height == 1080 || videoSize.height == 1088) {
      // 6.75 = 1080 / 160
      // 160 是裁剪成三份后的视频高度
      return MobileTransform(
        offset: Offset(0, 6.75 * (1 - (160 + mainView.height) / 1080)),
        scaleX: 3,
        scaleY: 6.75,
      );
    }
    print(
        "✨ videoSize: $videoSize mainView: $mainView cameraView: $cameraView  该参数下无合适的匹配项");
    return const MobileTransform.empty();
  }

  double double2percent(double value) {
    return double.parse((value * 100).toStringAsFixed(4));
  }
}

class MobileTransform {
  final Offset offset; // 偏移量
  final double scaleX; // 倍率
  final double scaleY; // 倍率

  MobileTransform({
    this.offset = Offset.zero,
    this.scaleX = 1,
    this.scaleY = 1,
  });

  // 0 构造函数
  const MobileTransform.empty()
      : offset = Offset.zero,
        scaleX = 1,
        scaleY = 1;
}
