import 'package:flutter/material.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/lab_loading_wrapper.dart';
import 'package:flyinsono/lab/components/video/widget/video_player_page.dart';
import 'package:flyinsono/lab/manager/page_manager.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_magnifier/image_magnifier.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_play_progress/image_play_progress.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/urm_child_data_panel/view.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/urm_result_overlay/index.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/vid_ui_repaint_overlay/index.dart';
import 'package:flyinsono/lab/router/lab_route_names.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:get/get.dart';

import '../../mock_data/mock_rpc.dart';
import 'index.dart';
import 'widgets/image_trace/view.dart';
import 'widgets/image_zoom_preview/view.dart';
import 'widgets/mark_overlay/view.dart';
import 'widgets/vid_repaint_overlay/index.dart';
import 'widgets/widgets.dart';

class LabImagePage extends GetView<LabImageController> {
  const LabImagePage({Key? key}) : super(key: key);

  get tabHashCode => this.hashCode.toString();

  // 主视图
  Widget _buildView() {
    return Obx(() {
      if (controller.state.noImage) {
        return _buildNoImage();
      }

      return Row(
        children: [
          _buildLeftPart(),
          Expanded(
            child: _buildVideoOrVidPlayer(),
          ),
          _buildRightPart(),
        ],
      );
    });
  }

  Widget _buildVideoOrVidPlayer() {
    return Obx(() {
      String url =
          controller.imageDataSourcePanelController.selectedImageUrl ?? '';
      var selectedImageType = controller.state.imageType;

      ///【TODO】 这段逻辑要改，不能这样
      if ((controller.imageDataSourcePanelController.selectedImageType ==
              ImageType.URM) ||
          (controller.imageDataSourcePanelController.selectedImageType ==
                  ImageType.Vid) &&
              (controller.state.imageType == ImageType.Measure_Result ||
                  controller.state.imageType == ImageType.Video)) {
        url = controller.state.url;
      }
      return Stack(
        children: [
          Column(
            children: [
              if (controller.state.imageType != ImageType.Video &&
                  controller.state.imageType != ImageType.Measure_Result)
                Expanded(child: _buildMainContent(url)),
              if (controller.state.imageType == ImageType.Video)
                Expanded(
                  child: _buildVideoPanel(url),
                ),
              if (controller.state.imageType == ImageType.Measure_Result)
                Expanded(
                  child: _buildImagePanel(url),
                ),
              ImagePlayProgress(),
              if (controller.state.isOnlyShowUrmInfo)
                Container(
                  height: 133,
                  alignment: Alignment.center,
                  child: UrmChildDataPanel(
                    initController: controller.urmChildDataPanelController,
                    tabHashCode: tabHashCode,
                  ),
                ),
              SizedBox(
                height: 10,
              ),
            ],
          ),
          if (selectedImageType == ImageType.Video ||
              selectedImageType == ImageType.Measure_Result) ...[
            Positioned(
              right: 15,
              top: 15,
              child: _buildSaveButton(),
            ),
          ],
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LabImageController>(
      init: LabImageController(tabHashCode: this.hashCode),
      builder: (_) {
        return Scaffold(
          backgroundColor: LabColors.base300,
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }

  Widget _buildNotMeasureTip(String typeName) {
    return Column(
      children: [
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  height: 200,
                  child: ColorFiltered(
                    colorFilter:
                        ColorFilter.mode(LabColors.base400, BlendMode.srcIn),
                    child: Image.asset(
                      Global.isVStationSlave
                          ? "assets/images/logo_icon_0.png"
                          : "assets/images/logo_icon.png",
                      filterQuality: FilterQuality.medium,
                      isAntiAlias: true,
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                // Text(
                //   "该$typeName不支持测量",
                //   style: TextStyle(
                //     color: LabColors.text600,
                //     fontSize: 16,
                //   ),
                // ),
                // SizedBox(
                //   height: 30,
                // ),
              ],
            ),
          ),
        ),
        if (controller.imageDataSourcePanelController.selectedImageType ==
            controller.state.imageType)
          Container(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                elevation: 0.0,
                backgroundColor: LabColors.buttonColor,
              ),
              onPressed: () {
                controller.viewOriginalImage();
              },
              child: const Text("查看原始数据"),
            ),
          ),
      ],
    );
  }

  Widget _buildLeftPart() {
    return Container(
      width: 220,
      height: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      child: ImageDataSourcePanel(
        tabHashCode: tabHashCode,
        initController: controller.imageDataSourcePanelController,
      ),
    );
  }

  Widget _buildMainContent(String url) {
    return Container(
      height: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 10),
      child: LabLoadingWrapper(
        loading: controller.state.isImageDownloading,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(5),
          ),
          child: Column(
            children: [
              Expanded(
                child: RepaintBoundary(
                  key: controller.imageCaptureAreakey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Expanded(child: _buildURMMainPanel()),
                      _buildURMChartPanel(),
                    ],
                  ),
                ),
              ),
              _buildProgressPanel(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildURMMainPanel() {
    return Stack(
      children: [
        ImageDataPlayer(
          initController: controller.imageDataPlayerController,
          tabHashCode: tabHashCode,
        ),
        // CanvasMagnifier(),
        VidRepaintOverlay(
          initController: controller.vidRepaintOverlayController,
          tabHashCode: tabHashCode,
        ),
        URMResultOverlay(
          initController: controller.urmResultOverlayController,
          tabHashCode: tabHashCode,
        ),
        VidUIRepaintOverlay(
          initController: controller.vidUIRepaintOverlayController,
          tabHashCode: tabHashCode,
        ),
        MarkOverLay(
          initController: controller.markOverlayController,
          tabHashCode: tabHashCode,
        ),
        ImageMeasureOverlay(
          initController: controller.imageMeasureOverlayController,
          tabHashCode: tabHashCode,
          currentURMProcessor: controller.currentURMProcessor,
        ),
        ImageRoiOverlay(
          initController: controller.imageRoiOverlayController,
          tabHashCode: tabHashCode,
        ),
        ImageTraceOverlay(
          initController: controller.imageTraceOverlayController,
          tabHashCode: tabHashCode,
        ),
        ImageZoomPreview(
          initController: controller.imageZoomPreviewController,
          tabHashCode: tabHashCode,
        ),
        if (controller.state.disableMagnifier)
          CanvasMagnifier(
            initController: controller.imageMeasureOverlayController,
          ),
        // TempCanvasMagnifier(),
      ],
    );
  }

  Widget _buildURMChartPanel() {
    return Column(
      children: [
        URMChartPanel(
          initController: controller.urmChartPanelController,
          tabHashCode: tabHashCode,
        ),
      ],
    );
  }

  Widget _buildProgressPanel() {
    return Column(
      children: [
        ProgressPanel(
          initController: controller.progressController,
          tabHashCode: tabHashCode,
        ),
      ],
    );
  }

  Widget _buildVideoPanel(String url) {
    return Container(
      padding: EdgeInsets.all(10),
      margin: EdgeInsets.symmetric(vertical: 10),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(5),
      ),
      child: VideoPlayerPage(
        url: url,
      ),
    );
  }

  Widget _buildImagePanel(String url) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Image.network(url),
    );
  }

  Widget _buildRightPart() {
    if (controller.state.imageType == ImageType.Video) {
      return Container(
        width: 350,
        height: double.infinity,
        padding: EdgeInsets.all(10),
        child: Container(
          decoration: LabBoxDecoration.operatePanel,
          padding: EdgeInsets.all(10),
          child: _buildNotMeasureTip("视频"),
        ),
      );
    } else if (controller.state.imageType == ImageType.Measure_Result) {
      return Container(
        width: 350,
        height: double.infinity,
        padding: EdgeInsets.all(10),
        child: Container(
          decoration: LabBoxDecoration.operatePanel,
          padding: EdgeInsets.all(10),
          child: _buildNotMeasureTip("图像"),
        ),
      );
    } else {
      return Container(
        width: 350,
        height: double.infinity,
        padding: EdgeInsets.all(10),
        child: ImageOperatePanel(
          initController: controller.imageOperatePanelController,
          projectCode: controller.activeArguments?.projectCode,
          tabHashCode: tabHashCode,
        ),
      );
    }
  }

  Widget _buildNoImage() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            height: 200,
            child: ColorFiltered(
              colorFilter: ColorFilter.mode(LabColors.base400, BlendMode.srcIn),
              child: Image.asset(
                Global.isVStationSlave
                    ? "assets/images/logo_icon_0.png"
                    : "assets/images/logo_icon.png",
                filterQuality: FilterQuality.medium,
                isAntiAlias: true,
                fit: BoxFit.contain,
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Text(
            "暂无打开的图像",
            style: TextStyle(
              color: LabColors.text600,
              fontSize: 16,
            ),
          ),
          SizedBox(
            height: 30,
          ),
          Column(
            children: [
              Text(
                "请先选择图像",
                style: TextStyle(
                  color: LabColors.text700,
                  fontSize: 14,
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Container(
                // width: 120,
                height: 40,
                child: ElevatedButton.icon(
                  icon: const Icon(Icons.folder_open_rounded),
                  style: ElevatedButton.styleFrom(
                    elevation: 0.0,
                    backgroundColor: LabColors.buttonColor,
                  ),
                  label: const Text("去选择"),
                  onPressed: () {
                    PageManager.ins.openTab(LabRouteNames.Data);
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSaveButton() {
    return MouseRegion(
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: () {
          controller.exportCurrentImage();
        },
        child: Icon(
          Icons.save,
          size: 25,
          color: LabColors.base800,
        ),
      ),
    );
  }
}
