import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/entities/consultation_member.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/entitys/play_channel.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/widgets/volume_slider_mobile.dart';
import 'package:get/get.dart';
import 'package:fis_lib_media_rt/interface/index.dart';

class VolumeSettingPanel extends FStatefulWidget {
  const VolumeSettingPanel({Key? key, this.ifShowPanel = false})
      : super(key: key);
  final bool ifShowPanel;

  @override
  _VolumeSettingPanelState createState() => _VolumeSettingPanelState();
}

class _VolumeSettingPanelState extends FState<VolumeSettingPanel>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  /// 抽屉组件的显示宽度
  static const double _widgetWidth = 240.0;

  /// 组件边框宽度
  static const double _borderWidth = 2.0;

  /// 组件的回弹空间
  static const double _bounceSpace = 40.0;

  /// 动画起始偏移量
  static const double _beginOffset =
      _widgetWidth + _bounceSpace + _borderWidth * 2;

  /// 动画结束偏移量
  static const double _endOffset = _bounceSpace + _borderWidth;

  @override
  initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    //使用弹性曲线
    animation = CurvedAnimation(parent: controller, curve: Curves.elasticIn);
    animation = Tween(begin: _beginOffset, end: _endOffset).animate(animation)
      ..addListener(() {
        setState(() => {});
      });
  }

  @override
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant VolumeSettingPanel oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.ifShowPanel != widget.ifShowPanel) {
      if (widget.ifShowPanel) {
        animation =
            CurvedAnimation(parent: controller, curve: Curves.elasticOut);
        animation =
            Tween(begin: _beginOffset, end: _endOffset).animate(animation)
              ..addListener(() {
                // setState(() => {});
              });
        controller.forward();
      } else {
        animation =
            CurvedAnimation(parent: controller, curve: Curves.elasticIn);
        animation =
            Tween(begin: _beginOffset, end: _endOffset).animate(animation)
              ..addListener(() {
                // setState(() => {});
              });
        controller.reverse();
      }
    }
  }

  @override
  FWidget build(BuildContext context) {
    return QuickFWidget(
      ClipRect(
        child: Transform(
          transform: Matrix4.translationValues(-animation.value, 0, 0),
          child: Container(
            padding: const EdgeInsets.only(left: _bounceSpace),
            decoration: BoxDecoration(
              color: Color.fromARGB(178, 71, 71, 71),
              borderRadius: const BorderRadius.only(
                bottomRight: Radius.circular(10),
                topRight: Radius.circular(10),
              ),
              border: Border.all(color: Colors.grey, width: _borderWidth),
            ),
            child: SizedBox(
              width: _widgetWidth,
              child: FObx(() {
                final _controller = Get.find<LiveConsultationController>();
                final Map<String, PlayChannelInfo> _playChannels =
                    _controller.state.playChannels;
                final List<String> _playChannelkeys =
                    _playChannels.keys.toList();
                final String _localId = Store.user.code;
                final String? _deviceChannelId =
                    _controller.state.deviceDesktopChannel?.id;
                final List<ConsultationMember> consultationMembers = _controller
                    .state.memberStatus.values
                    .toList()
                    .where(
                        (element) => element.memberType == LiveMemberEnum.User)
                    .toList();
                List<IChannel> _availableChannels = [];
                List<Color> _channelColors = [];
                for (int i = 0; i < _playChannelkeys.length; i++) {
                  final String _channelId = _playChannelkeys[i];
                  final PlayChannelInfo _playChannel =
                      _playChannels[_channelId]!;
                  if (_channelId == _localId) {
                    continue;
                  }
                  if (_playChannel.channel == null) continue;
                  if (_deviceChannelId == _playChannel.channel!.id) {
                    continue;
                  }
                  int? index;
                  for (int j = 0; j < consultationMembers.length; j++) {
                    final ConsultationMember _member = consultationMembers[j];
                    if (_member.id == _channelId) {
                      index = _member.index;
                      break;
                    }
                  }
                  if (index == null) continue;
                  _channelColors.add(
                      _controller.whiteboardController.getColorByIndex(index));
                  _availableChannels.add(_playChannel.channel!);
                }
                if (_availableChannels.isEmpty)
                  return FContainer(
                    padding: EdgeInsets.all(10),
                    child: FText(
                      i18nBook.realTimeConsultation.noVolumeAdjustmentChannel.t,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    ),
                  );

                return FColumn(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    /// 带下标的迭代
                    ..._availableChannels
                        .asMap()
                        .entries
                        .map((e) => VolumeSlider4Mobile(
                              channel: e.value,
                              color: _channelColors[e.key],
                            ))
                  ],
                );
              }),
            ),
          ),
        ),
      ),
    );
  }
}
