import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/webviewx.dart';
import 'package:flyinsono/managers/interfaces/entities/vidImage_parameters.dart';
import 'package:flyinsono/managers/interfaces/local_rtmp.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';
import 'dart:convert';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/channel/channel.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/widgets/remote_view/remote_view.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/members.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/models.dart';
import 'package:fis_common/index.dart';
import 'package:fis_lib_media_rt/interface/index.dart';

import 'video_frame_widget.dart';

class CaptureLiveView extends FStatefulWidget implements FPage {
  @override
  String get pageName => "CaptureLiveView";

  final String recordCode;

  CaptureLiveView(this.recordCode);

  @override
  FState<FStatefulWidget> createState() {
    return CaptureLiveViewState();
  }
}

class CaptureLiveViewState extends FState<CaptureLiveView> {
  final webviewControllerManager = Get.find<IWebviewControllerManager>();
  final localRtmpManager = Get.find<ILocalRtmpManager>();
  final controller = Get.find<ConsultationRecordViewController>();
  late WebViewXController webViewController;
  late ICapturer capturer;
  late NTPlayChannel channel;
  List<VidImageParameters> _images = [];
  bool _isRecording = false;

  @override
  void initState() {
    localRtmpManager.onUploadImage.addListener(_onImageUploaded);
    localRtmpManager.onRecord.addListener(onRecord);
    super.initState();
  }

  @override
  void dispose() {
    localRtmpManager.onUploadImage.removeListener(_onImageUploaded);
    localRtmpManager.onRecord.removeListener(onRecord);
    controller.captureLiveController.stopRtmpServer();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);

    ///屏幕缩放比例
    final devicePixelRatio = mediaQuery.devicePixelRatio;

    return FSimpleDialog(
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      title: FText(
        i18nBook.common.imageCapture.t,
        style: TextStyle(color: Colors.white),
      ),
      children: [
        FRow(
          children: [
            FContainer(
              color: Colors.black,
              height: 800 / devicePixelRatio,
              width: 1300 / devicePixelRatio,
              alignment: Alignment.center,
              child: QuickFWidget(
                VideoFrameWidget(),
              ),
            ),
            FSizedBox(
              width: 320 / devicePixelRatio,
              height: 800 / devicePixelRatio,
              child: _buildImagesView(),
            ),
          ],
        ),
      ],
    );
  }

  FWidget _buildImagesView() {
    return FColumn(
      children: [
        FExpanded(
          child: _buildImages(),
        ),
        FContainer(
          margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          width: 320,
          child: FButtonGroup(children: [
            FElevatedButton(
              name: '',
              businessParent: this.widget,
              child: FText(i18nBook.common.screenshot.t),
              onPressed: () {
                localRtmpManager.onCaptureFrame.emit(this, true);
              },
            ),
            FElevatedButton(
              name: '',
              businessParent: this.widget,
              child: FText(_isRecording
                  ? i18nBook.realTimeConsultation.endRecording.t
                  : i18nBook.common.startRecording.t),
              onPressed: () {
                setState(() {
                  _isRecording = !_isRecording;
                });
                localRtmpManager.onRecord.emit(this, _isRecording);
              },
            ),
          ]),
        )
      ],
    );
  }

  FWidget _buildImages() {
    return FGridView.count(
      crossAxisCount: 2,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
      children: _images.map((e) {
        FWidget child;
        if (e.previewImage.isEmpty) {
          child = FCenter(
            child: FSizedBox(
              width: 30,
              height: 30,
              child: FCircularProgressIndicator(),
            ),
          );
        } else {
          child = FImage.network(
            e.previewImage,
            fit: BoxFit.fitWidth,
          );
        }
        return FContainer(
          color: Colors.black,
          child: FStack(
            children: [
              FPositioned(
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                child: child,
              ),
              if (e.isVideo) ...[
                FPositioned(
                  left: 0,
                  top: 0,
                  right: 0,
                  bottom: 0,
                  child: FIcon(
                    Icons.play_circle_outline,
                    color: Colors.white,
                  ),
                ),
              ],
              FPositioned(
                left: 5,
                top: 5,
                child: FText(
                  (_images.indexOf(e) + 1).toString(),
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  void onRecord(Object sender, bool e) {
    setState(() {
      _isRecording = e;
    });
  }

  void _onImageUploaded(Object sender, VidImageParameters e) {
    var image = _images.firstWhereOrNull((ele) => ele.code == e.code);
    if (image == null) {
      _images.add(e);
    } else {
      _images[_images.indexOf(image)] = e;
    }
    localRtmpManager.createExamData(
      widget.recordCode,
      fileDataType: e.isVideo
          ? RemedicalFileDataTypeEnum.VinnoVidMovie
          : RemedicalFileDataTypeEnum.VinnoVidSingle,
      previewFileToken: e.previewImage,
      coverImageToken: e.corverImage,
      fileToken: e.vidImage,
      fileSize: e.size,
    );
    setState(() {});
  }
}
