import 'package:get/get.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/data/sideb/api/music_api.dart';
import 'package:tone_snap/data/sideb/models/next_model.dart';
import 'package:tone_snap/data/sideb/models/play_list_model.dart';
import 'package:tone_snap/data/sideb/models/player_model.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';
import 'package:tone_snap/utils/obj_util.dart';

class PlayMusicController extends GetxController {
  var musicPlayerController = MusicPlayerController.to;

  /// 当前播放的歌曲信息
  late String videoId;
  late String playlistId;
  var thumbnail = Rx<String?>(null);
  var title = Rx<String?>(null);
  var subTitle = Rx<String?>(null);

  /// 播放列表
  List<PlayListModel> playList = [];

  /// 当前播放的歌曲下标
  int currentIndex = 0;

  @override
  void onInit() {
    super.onInit();
    playlistId = Get.arguments['playlistId'];
    videoId = Get.arguments['videoId'];
  }

  @override
  void onReady() async {
    super.onReady();
    _next();
  }

  Future<dynamic> _next() async {
    BaseEasyLoading.loading();
    NextModel? model = await MusicApi.next(playlistId: playlistId, videoId: videoId);
    BaseEasyLoading.dismiss();
    if (model != null) {
      var tabs = model.contents?.singleColumnMusicWatchNextResultsRenderer?.tabbedRenderer?.watchNextTabbedResultsRenderer?.tabs;
      if (tabs != null && tabs.isNotEmpty) {
        for (var i = 0; i < tabs.length; ++i) {
          var o = tabs[i];
          if (i == 0) {
            var contents = o.tabRenderer?.content?.musicQueueRenderer?.content?.playlistPanelRenderer?.contents;
            if (contents != null && contents.isNotEmpty) {
              for (var j = 0; j < contents.length; ++j) {
                var playListModel = PlayListModel();
                var content = contents[j];
                // 封面
                var thumbnails = content.playlistPanelVideoRenderer?.thumbnail?.thumbnails;
                if (thumbnails != null) {
                  playListModel.thumbnail = thumbnails.last.url;
                }

                // 标题
                var runs = content.playlistPanelVideoRenderer?.title?.runs;
                if (runs != null && runs.isNotEmpty) {
                  playListModel.title = runs[0].text;
                }

                // 副标题
                var subRuns = content.playlistPanelVideoRenderer?.longBylineText?.runs;
                if (subRuns != null && subRuns.isNotEmpty) {
                  playListModel.subTitle = subRuns.map((e) => e.text).join();
                }

                // videoId, playlistId
                var watchEndpoint = content.playlistPanelVideoRenderer?.navigationEndpoint?.watchEndpoint;
                if (watchEndpoint != null) {
                  playListModel.videoId = watchEndpoint.videoId;
                  playListModel.playlistId = watchEndpoint.playlistId;
                }
                playList.add(playListModel);
              }
            }
          }
        }
      }
      _getCurrentMusicInfo();
      _player();
    }
  }

  /// 获取当前下标的歌曲信息
  void _getCurrentMusicInfo() {
    if (playList.isNotEmpty) {
      thumbnail.value = playList[currentIndex].thumbnail;
      title.value = playList[currentIndex].title;
      subTitle.value = playList[currentIndex].subTitle;
    }
  }

  Future<dynamic> _player() async {
    if (playList.isEmpty) return;
    BaseEasyLoading.loading();
    PlayerModel? model = await MusicApi.player(videoId: playList[currentIndex].videoId);
    BaseEasyLoading.dismiss();
    if (model != null && model.streamingData != null) {
      var formats = model.streamingData?.formats;
      if (formats != null && playList.isNotEmpty) {
        playList[currentIndex].url = formats[0].url ?? '';

        // 开始播放
        musicPlayerController.playNewUrl(playList[currentIndex].url!, ObjUtil.getStr(playList[currentIndex].videoId));
      }
    }
  }

  /// 继续/暂停
  void playPause() {
    musicPlayerController.playPause();
  }

  /// 上一首
  Future<void> previousTrack() async {
    if (currentIndex > 0) {
      currentIndex--;
    }
    _getCurrentMusicInfo();
    _player();
  }

  /// 下一首
  Future<void> nextTrack() async {
    if (currentIndex < playList.length - 1) {
      currentIndex++;
    }
    _getCurrentMusicInfo();
    _player();
  }
}
