import 'package:fis_common/env/env.dart';
import 'package:fis_jsonrpc/services/liveConsultation.m.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';

/// 会诊成员头像列表
class FMemberAvatars extends FStatelessWidget {
  FMemberAvatars({
    super.key,
    required this.members,
    this.onlyShowFive = false,
    this.maxCount = 5,
  });
  final List<ConsultationMemberDTO> members;

  /// 只显示前五个
  final bool onlyShowFive;

  final int? maxCount;

  static bool get isMobile => FPlatform.isAndroid || FPlatform.isIOS;

  /// 状态角标尺寸
  static double _iconSize = 16;

  /// 单个元素占位尺寸
  static Size _itemSize = Size(60, 65);

  /// 详情页内单个元素占位尺寸
  static Size _itemSizeInDetail = Size(120, 50);

  /// 头像容器占位尺寸(上方要多10，给角标留位置)
  static Size _avatarContainerSize = Size(50, 40);

  /// 头像尺寸
  static double _avatarSize = 30;

  /// 角标偏移量()
  static Offset _iconOffset = Offset(3, 3);

  /// 滚动控制器
  final ScrollController _scrollController = ScrollController();

  @override
  FWidget build(BuildContext context) {
    /// 如果超过5人，在只显示前5人，后面的用...代替
    if (onlyShowFive) {
      final List<ConsultationMemberDTO> _members =
          members.length > (maxCount ?? 5)
              ? members.sublist(0, maxCount)
              : members;
      return FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FSizedBox(
            width: isMobile ? FSpacings.M : FSpacings.XXL,
          ),
          ..._members
              .map((e) => _buildMemberItem(
                    e.name ?? "",
                    e.headImageToken ?? "",
                    e.memberStatus,
                  ))
              .toList(),
        ],
      );
    } else {
      return FSizedBox(
        height: 70,
        child: FAlwaysScrollListView(
          scrollController: _scrollController,
          child: QuickFWidget(ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: FListView(
              controller: _scrollController,
              scrollDirection: Axis.horizontal,
              children: [
                FRow(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    ...members
                        .map((e) => _buildDetailMemberItem(
                              e.name ?? "",
                              e.headImageToken ?? "",
                              e.memberStatus,
                            ))
                        .toList(),
                  ],
                ),
              ],
            ),
          )),
        ),
      );
    }
  }

  /// 参与人展示
  FWidget _buildMemberItem(
      String name, String avatar, LiveConsultationMemberStatus status) {
    return FTextTooltip(
      message: name,
      position: DisplayPosition.bottom,
      child: FContainer(
        width: _itemSize.width,
        height: _itemSize.height,
        padding: EdgeInsets.symmetric(horizontal: 5),
        child: FColumn(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildAvatarWithStatus(avatar, name, status),
            const FSizedBox(
              height: 5,
            ),
            FText(
              name,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14, color: Colors.black87),
            ),
          ],
        ),
      ),
    );
  }

  /// 详情页的参与人展示
  FWidget _buildDetailMemberItem(
      String name, String avatar, LiveConsultationMemberStatus status) {
    return FTextTooltip(
      message: name,
      position: DisplayPosition.bottom,
      child: FContainer(
        width: _itemSizeInDetail.width,
        height: _itemSizeInDetail.height,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black38),
          borderRadius: BorderRadius.circular(4),
        ),
        margin: EdgeInsets.only(right: 5),
        child: FStack(
          children: [
            FRow(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildAvatar(avatar, name),
                FExpanded(
                  child: FAlign(
                    alignment: Alignment.centerLeft,
                    child: FText(
                      name,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: 14, color: Colors.black87),
                    ),
                  ),
                ),
              ],
            ),
            FPositioned(
              child: _buildStatusIcon(status),
              right: _iconOffset.dx,
              top: _iconOffset.dy,
            )
          ],
        ),
      ),
    );
  }

  FWidget _buildAvatarWithStatus(
      String avatar, String name, LiveConsultationMemberStatus status) {
    return FContainer(
      width: _avatarContainerSize.width,
      height: _avatarContainerSize.height,
      child: FStack(
        children: [
          FContainer(
            margin: EdgeInsets.only(top: 10),
            child: _buildAvatar(avatar, name),
          ),
          FPositioned(
            right: _iconOffset.dx,
            top: _iconOffset.dy,
            child: _buildStatusIcon(status),
          ),
        ],
      ),
    );
  }

  FWidget _buildAvatar(String avatar, String name) {
    FWidget avatarWidget;
    if (avatar == '') {
      avatarWidget = FImage(
        image: AssetImage("assets/images/avatar_man.png"),
        width: _avatarSize,
        height: _avatarSize,
      );
    } else {
      avatarWidget = FImage(
        image: NetworkImage(avatar),
        width: _avatarSize,
        height: _avatarSize,
        errorBuilder: (context, error, stackTrace) {
          return FImage.asset(
            'assets/images/avatar_man.png',
            fit: BoxFit.cover,
          );
        },
      );
    }
    return FContainer(
      width: _avatarContainerSize.width,
      height: _avatarContainerSize.height,
      child: FCenter(
        child: FContainer(
            width: _avatarSize,
            height: _avatarSize,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
            ),
            clipBehavior: Clip.antiAlias,
            child: avatarWidget),
      ),
    );
  }

  FWidget _buildStatusIcon(LiveConsultationMemberStatus status) {
    /// 状态映射
    Color iconColor = Colors.transparent;
    Color bgColor = Colors.transparent;
    IconData iconData = Icons.check_circle;
    switch (status) {
      case LiveConsultationMemberStatus.Default:
        iconColor = Colors.orange;
        bgColor = Colors.orange.shade100;
        iconData = Icons.info;
        break;
      case LiveConsultationMemberStatus.Accepted:
        iconColor = Colors.green;
        bgColor = Colors.green.shade100;
        iconData = Icons.check_circle;
        break;
      case LiveConsultationMemberStatus.Rejected:
        iconColor = Colors.red;
        bgColor = Colors.red.shade100;
        iconData = Icons.do_not_disturb_on;
        break;
      case LiveConsultationMemberStatus.Left:
        iconColor = Colors.grey;
        bgColor = Colors.grey.shade100;
        iconData = Icons.cancel;
        break;
      default:
        iconColor = Colors.transparent;
        break;
    }
    return FContainer(
        width: _iconSize,
        height: _iconSize,
        decoration: BoxDecoration(
          color: iconColor,
          borderRadius: BorderRadius.circular(
            _iconSize,
          ),
        ),
        child: FIcon(
          iconData,
          color: bgColor,
          size: _iconSize,
        ));
  }
}
