import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/views/mobile/past_video_player/widgets/mobile_video_player.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_common/env/env.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flutter/material.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:get/get.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'index.dart';

class PastVideoPlayerPage extends FisView<PastVideoPlayerController>
    implements FPage {
  const PastVideoPlayerPage({Key? key}) : super(key: key);
  @override
  final String pageName = "PastVideosPage";

  @override
  FWidget build(BuildContext context) {
    return FisBuilder<PastVideoPlayerController>(
      builder: (_) {
        return kIsMobile ? _buildMobileView() : _buildDesktopView();
      },
    );
  }

  FWidget _buildMobileView() {
    return FScaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: FText(
          i18nBook.college.pastVideo.t,
          style: TextStyle(
            fontSize: FFontSizes.H6,
          ),
        ),
        leading: FIconButton(
          businessParent: this,
          name: "",
          icon: FIcon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      // title: i18nBook.college.pastVideo.t,
      body: FColumn(
        children: [
          _buildVideoPlayer(),
          FExpanded(
            child: FListView(
              children: [
                _buildVideoTitle(),
                // TODO 暂时屏蔽置顶和星级标签（需求来自群聊）
                // _buildVideoStarLevel(),
                _buildVideoCreateTime(),
                _buildVideoDescription(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildDesktopView() {
    return FColumn(
      children: [
        FExpanded(
          child: FContainer(
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
            child: FRow(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FFlexible(
                  flex: 3,
                  child: FContainer(
                    margin: EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      border: Border.all(
                          color: Colors.black,
                          width: 0.5,
                          strokeAlign: BorderSide.strokeAlignOutside),
                      borderRadius: BorderRadius.circular(5),
                    ),
                    clipBehavior: Clip.antiAliasWithSaveLayer,
                    child: _buildVideoPlayer(aspectRatio: 16 / 9),
                  ),
                ),
                FFlexible(
                  flex: 1,
                  child: FListView(
                    children: [
                      _buildVideoTitle(),
                      // TODO 暂时屏蔽置顶和星级标签（需求来自群聊）
                      // _buildVideoStarLevel(),
                      _buildVideoCreateTime(),
                      _buildVideoDescription(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建视频播放器 H5
  FWidget _buildVideoPlayer({double aspectRatio = 1}) {
    return QuickFWidget(
      AspectRatio(
        aspectRatio: aspectRatio,
        child: LayoutBuilder(
          builder: (context, constraints) {
            return Stack(
              children: [
                Obx(
                  () {
                    String videoUrl = controller.state.videoUrl;
                    bool isLoading = controller.state.isLoading;

                    if (videoUrl.isEmpty) {
                      return Container(
                          child: Center(
                        child: isLoading
                            ? Container()
                            : FText(
                                i18nBook.common.noData.t,
                                style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.grey,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                      ));
                    }
                    String encodedString = base64.encode(utf8.encode(videoUrl));
                    // var url = 'https://plyr.io';
                    var url = ServerConfigManager.flyinsonoSchoolUrl +
                        'video_player/$encodedString/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';

                    // local url for debug
                    // var url =
                    //     'http://localhost:3000/#/video_player/$encodedString/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
                    print(url);
                    if (kIsWeb) {
                      return _buildDesktopWebviewPlayer(url);
                    } else {
                      return _buildMobilePlayer(videoUrl);
                    }
                  },
                ),
                FObx(() {
                  bool isHide = !controller.state.isLoading;
                  return FOffstage(
                    offstage: isHide,
                    child: FCenter(
                      child: FCircularProgressIndicator(),
                    ),
                  );
                }),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildMobilePlayer(String url) {
    return MobileVideoPlayer(
      url: url,
      onLoaded: () {
        controller.onWebviewLoadFinished();
      },
    );
  }

  Widget _buildMobileWebviewPlayer(url) {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: Uri.parse(url)),
      initialOptions: InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          transparentBackground: true,
          mediaPlaybackRequiresUserGesture: false,
          allowFileAccessFromFileURLs: true,
          allowUniversalAccessFromFileURLs: true,
        ),
        ios: IOSInAppWebViewOptions(
          allowsInlineMediaPlayback: true,
        ),
        android: AndroidInAppWebViewOptions(
          allowFileAccess: true,
          allowContentAccess: true,
        ),
      ),
      onWebViewCreated: (c) {},
      onLoadStop: (c, url) async {
        controller.onWebviewLoadFinished();
      },
      onLoadError: (controller, url, code, message) {
        print("webview onLoadError");
      },
      onLoadHttpError: (controller, url, statusCode, description) {
        print("webview onLoadHttpError");
      },
      onConsoleMessage: (c, consoleMessage) {
        // logger.d(
        //     "[WebView Console][${consoleMessage.messageLevel}] ${consoleMessage.message}");
      },
      onEnterFullscreen: (c) {
        /// 允许屏幕旋转
        if (FPlatform.isAndroid) {
          // 安卓设备只允许右横屏
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeRight,
          ]);
          return;
        } else {
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeLeft,
            DeviceOrientation.landscapeRight,
          ]);
        }
      },
      onExitFullscreen: (c) {
        /// 禁止屏幕旋转
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
        ]);
      },
    );
  }

  Widget _buildDesktopWebviewPlayer(url) {
    return WebViewX(
      height: MediaQuery.of(Get.context!).size.height,
      width: MediaQuery.of(Get.context!).size.width,
      initialSourceType: SourceType.url,
      initialContent: url,
      javascriptMode: JavascriptMode.unrestricted,
      // initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.alwaysAllow,
      onWebResourceError: (p0) {},
      onWebViewCreated: (controller) {},
      onPageFinished: (_) {
        controller.onWebviewLoadFinished();
      },
    );
  }

  /// 构建视频标题
  FWidget _buildVideoTitle() {
    return FContainer(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 20),
      padding: EdgeInsets.symmetric(vertical: 20),
      decoration: BoxDecoration(
        // 下边框
        border: Border(
          bottom: BorderSide(
            // 设置单侧边框的样式
            color: Colors.grey,
            width: 0.5,
          ),
        ),
      ),
      child: FObx(() => FText(
            controller.state.videoTitle,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          )),
    );
  }

  /// 构建视频简介
  FWidget _buildVideoDescription() {
    return FObx(
      () => FContainer(
        width: double.infinity,
        padding: EdgeInsets.only(top: 10, left: 20, right: 20),
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(
              i18nBook.college.videoDescription.t,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            FSizedBox(height: 10),
            FText(controller.state.videoDescription),
            FSizedBox(height: 30),
          ],
        ),
      ),
    );
  }

  /// 构建视频上传时间
  FWidget _buildVideoCreateTime() {
    return FObx(
      () => FContainer(
        width: double.infinity,
        padding: EdgeInsets.only(top: 10, left: 20, right: 20),
        child: FRow(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(
              i18nBook.common.createTime.t,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            FExpanded(child: FSizedBox()),
            FText(controller.state.videoCreateTimeStr),
          ],
        ),
      ),
    );
  }

  /// 构建视频星级
  FWidget _buildVideoStarLevel() {
    return FObx(
      () => FContainer(
        width: double.infinity,
        padding: EdgeInsets.only(top: 10, left: 20, right: 20),
        child: FRow(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(
              i18nBook.college.starRating.t,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            FExpanded(child: FSizedBox()),
            for (var i = 0; i < 5; i++) ...[
              FIcon(
                i < controller.state.videoStarLevel
                    ? Icons.star_rounded
                    : Icons.star_outline_rounded,
                color: i < controller.state.videoStarLevel
                    ? Color.fromARGB(255, 235, 192, 50)
                    : Colors.grey,
                size: 18,
              ),
            ],
          ],
        ),
      ),
    );
  }
}
