import 'package:fis_common/index.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/device_detail_info.dart';
import 'package:flyinsono/managers/interfaces/remote_maintenance.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/remote_main_tenance.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/remote_main_tenance_mobile.dart';
import 'package:flyinsono/views/common/device_live/widgets/device_online_sign.dart';
import 'package:get/get.dart';

import '../controller.dart';

/// 设备信息卡片
class DeviceInfoCard extends FStatelessWidget implements FPage {
  DeviceInfoCard(
    this.index, {
    super.key,
    this.aspectRatio = 1,
  }) {
    _loadData();
  }
  @override
  String get pageName => 'DeviceInfoCard';

  /// 索引
  final int index;

  late final DeviceLiveListController _controller;
  late final DeviceExtendInfoDTO _dto;

  bool get isOnline => _dto.isOnline == true;

  void _loadData() {
    _controller = Get.find<DeviceLiveListController>();
    _dto = _controller.state.deviceList[index];
  }

  /// 纵横比(h/w)
  final double aspectRatio;
  final remoteMaintenanceManager = Get.find<IRemoteMaintenanceManager>();
  static const _C_DEFAULT_COVER_URL = "assets/images/mock_terminal.png";
  static const _C_COVER_BGCOLOR = Colors.white;
  static TextStyle _textStyle = TextStyle(
    color: Colors.white,
    fontSize: FFontSizes.BODY,
  );
  bool _isExpanded = false;

  @override
  FWidget build(BuildContext context) {
    return FLayoutBuilder(
      builder: (context, constraints) {
        final width = constraints.maxWidth;
        final height = aspectRatio * width;
        final terminalInfoArea = FStack(
          children: [
            _buildCover(width, height),
            if (isOnline == false) _buildOfflineWrapper(),
            if (isOnline)
              const FPositioned(
                top: 8,
                left: 12,
                child: DeviceOnlineSign(),
              )
            else
              FSizedBox(),
            _buildDeviceInfos(),
            _buildDeviceDetail(),
          ],
        );
        var bottom = _buildBottomBar(width, height);
        var formerWidget;
        if (isOnline) {
          formerWidget = FInkWell(
            // cursor: SystemMouseCursors.click,
            onTap: () {
              remoteMaintenanceManager.onCancelExtendButtons.emit(this, false);
              _controller.handleEnterLive(index);
            },
            child: terminalInfoArea,
          );
        } else {
          formerWidget = terminalInfoArea;
        }

        return FContainer(
          width: width,
          height: height,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
          ),
          clipBehavior: Clip.antiAliasWithSaveLayer,
          child: FStack(
            children: [
              formerWidget,
              bottom,
            ],
          ),
        );
      },
    );
  }

  /// 封面图
  FWidget _buildCover(double width, double height) {
    final coverUrl = _dto.headPicUrl;
    final image = coverUrl.isNullOrEmpty
        ? FImage.asset(
            _C_DEFAULT_COVER_URL,
            width: width,
            height: height,
            fit: BoxFit.fill,
          )
        : FImage.network(
            coverUrl!,
            width: width,
            height: height,
            fit: BoxFit.cover,
          );
    return FContainer(
      color: _C_COVER_BGCOLOR,
      child: image,
    );
  }

  /// 离线罩层
  FWidget _buildOfflineWrapper() {
    return FPositioned(
      top: 0,
      bottom: 0,
      right: 0,
      left: 0,
      child: FOpacity(
        opacity: 0.6,
        child: Container(
          color: Colors.black,
        ),
      ),
    );
  }

  /// 底部栏
  FWidget _buildBottomBar(
    double width,
    double height,
  ) {
    return FObx(() {
      final bgColor = isOnline ? Colors.grey.withOpacity(0.94) : null;
      bool isHover = _controller.state.isShowDeviceDetailIndex == index;
      if (isHover) {
        return FSizedBox();
      }

      return FPositioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: FColumn(
          children: [
            FMouseRegion(
              cursor: SystemMouseCursors.basic,
              child: FContainer(
                height: 38,
                color: bgColor,
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: FRow(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    FExpanded(
                      child: FColumn(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          FMaterialTooltip(
                            decoration: BoxDecoration(
                              color: Colors.black,
                              borderRadius: BorderRadius.all(
                                Radius.circular(4),
                              ),
                            ),
                            enableFeedback: true,
                            message: _dto.displayName!,
                            child: FText(
                              _dto.displayName!,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: FFontSizes.BODY,
                              ),
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            ),
                          ),
                        ],
                      ),
                    ),
                    _buildDeviceLiveShare(),
                  ],
                ),
              ),
            ),

            /// （远程维护 | 远程维护管理员） & 在线
            if ((_controller.state.hasRemoteManager ||
                    _controller.state.hasRemoteMaintain) &&
                isOnline) ...[
              if (kIsMobile)
                RemoteMainTenanceMobile(
                  width: width,
                  height: height,
                  index: index,
                )
              else
                RemoteMainTenance(
                  width: width,
                  height: aspectRatio * width,
                  index: index,
                ),
            ]
          ],
        ),
      );
    });
  }

  FWidget _buildDeviceLiveShare() {
    if (isOnline) {
      return FRow(
        children: [
          _verticalDivider(),
          FGestureDetector(
            businessParent: FVirtualPageWidget("DeviceLive"),
            name: 'DeviceLiveShare',
            child: const FIcon(
              Icons.share,
              size: FFontSizes.H4,
              color: Colors.white,
            ),
            onTap: () {
              _controller.handleShare(index);
            },
          )
        ],
      );
    } else {
      return FSizedBox();
    }
  }

  FWidget _verticalDivider() {
    return const FVerticalDivider(
      color: Colors.white,
      indent: FSpacings.M,
      endIndent: FSpacings.M,
    );
  }

  /// 设备详细信息
  FWidget _buildDeviceInfos() {
    return FColumn(
      children: [
        if (_controller.state.hasRemoteManager ||
            _controller.state.hasRemoteMaintain) ...[
          FAlign(
            child: FInkWell(
              child: FContainer(
                margin: EdgeInsets.only(top: 5, right: 5),
                child: FIcon(
                  Icons.info_outline,
                  color: Colors.white,
                ),
              ),
              onTap: () {
                if (_controller.state.isShowDeviceDetailIndex != index) {
                  _controller.state.isShowDeviceDetailIndex = index;
                } else {
                  _controller.state.isShowDeviceDetailIndex = -1;
                }
              },
              onHover: (value) => _onDeviceHover(value),
            ),
            alignment: Alignment.topRight,
          ),
        ]
      ],
    );
  }

  /// 设备信息
  FWidget _buildDeviceDetail() {
    return FObx(() {
      bool isHover = _controller.state.isShowDeviceDetailIndex == index;
      if (isHover) {
        return FCenter(
          child: FLimitedBox(
            child: FContainer(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: Colors.black.withOpacity(0.7),
              ),
              margin: EdgeInsets.only(top: 30),
              padding: EdgeInsets.symmetric(
                horizontal: 4,
                vertical: 2,
              ),
              width: 230,
              child: FListView(
                children: [
                  FDeviceDetailInfo(
                    deviceExtendInfo: _dto,
                  ),
                ],
              ),
            ),
          ),
        );
      } else {
        return FSizedBox();
      }
    });
  }

  void _onDeviceHover(value) {
    if (value) {
      _controller.state.isShowDeviceDetailIndex = index;
    } else {
      _controller.state.isShowDeviceDetailIndex = -1;
    }
  }
}
