import 'package:get/get.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/data/api/music_api.dart';
import 'package:tone_snap/data/models/music_model.dart';
import 'package:tone_snap/data/models/next_model.dart';
import 'package:tone_snap/data/storage/love_songs_box.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';

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

  /// 是否从 MusicBar 打开
  bool isMusicBarOpen = false;

  /// 是否添加到喜欢
  var isLove = false.obs;

  /// 当前播放的歌曲信息
  late String videoId;
  String? playlistId;
  List<MusicModel>? playList;

  @override
  void onInit() {
    super.onInit();
    videoId = Get.arguments['videoId'] ?? '';
    playlistId = Get.arguments['playlistId'];
    playList = Get.arguments['playList'];
    isMusicBarOpen = Get.arguments['isMusicBarOpen'] ?? false;

    isLove.value = LoveSongsBox().isLove(videoId);
  }

  @override
  void onReady() async {
    super.onReady();
    if (!isMusicBarOpen) {
      if (musicPlayerController.musicModel.value.videoId != videoId) {
        playList ??= await _next();
        musicPlayerController.setPlayList(videoId, playList!);
        musicPlayerController.playMusic();
      }
    }
  }

  /// 获取播放列表
  Future<List<MusicModel>> _next() async {
    List<MusicModel> playList = [];
    NextModel? model = await MusicApi.next(playlistId: playlistId, videoId: videoId);
    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 = MusicModel();
                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);
              }
            }
          }
        }
      }
    }
    return playList;
  }

  /// 加入/取消喜欢
  Future<void> addCancelLove() async {
    if (isLove.value) {
      await LoveSongsBox().delete(musicPlayerController.musicModel.value.videoId!);
      isLove.value = false;
      BaseEasyLoading.toast('Cancelled');
    } else {
      await LoveSongsBox().addData(musicPlayerController.musicModel.value.copyWith());
      isLove.value = true;
      BaseEasyLoading.toast('Collected');
    }
  }

  /// 在播放列表中切换歌曲
  void switchMusic(int index, MusicModel model) {
    if (musicPlayerController.musicModel.value.videoId != model.videoId) {
      musicPlayerController.playMusicSpecifyIndex(index);
    }
    Get.back();
  }

  /// 删除播放列表中的歌曲
  void deleteMusic(int index) {
    musicPlayerController.playList.removeAt(index);
  }
}
