import 'package:background_downloader/background_downloader.dart';
import 'package:get/get.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/components/dialog/remind_dialog.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/data/storage/offline_box.dart';
import 'package:tone_snap/global/download_manager.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';
import 'package:tone_snap/modules/sideb/personal_music_library/personal_music_library_controller.dart';

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

  @override
  void onReady() async {
    super.onReady();
    bool isFormMusicBar = Get.arguments['isFormMusicBar'] ?? false;
    String videoId = Get.arguments['videoId'] ?? '';
    String playlistId = Get.arguments['playlistId'] ?? '';
    List<MusicModel> playList = Get.arguments['playList'] ?? <MusicModel>[];

    if (!isFormMusicBar) {
      if (playList.isEmpty) {
        musicPlayerController.playlist.clear();
        musicPlayerController.resetPlaybackStatus();
        playList = await _next(videoId, playlistId);
      }
      musicPlayerController.playMusic(videoId, playList: playList);
    }
  }

  /// 获取播放列表
  Future<List<MusicModel>> _next(String? videoId, String? playlistId) 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 musicModel = MusicModel();
                var content = contents[j];
                if (content.playlistPanelVideoRenderer != null) {
                  // 封面
                  var thumbnails = content.playlistPanelVideoRenderer?.thumbnail?.thumbnails;
                  if (thumbnails != null) {
                    musicModel.coverUrl = thumbnails.last.url;
                  }

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

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

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

  /// 加入/取消收藏
  Future<void> onTapLove() async {
    if (musicPlayerController.getMusicModel()?.value.videoId == null) return;
    final isLove = LoveSongsBox().checkLove(musicPlayerController.getMusicModel()!.value.videoId);
    if (isLove) {
      await LoveSongsBox().delete(musicPlayerController.getMusicModel()!.value.videoId!);
      BaseEasyLoading.toast('Removed');
    } else {
      await LoveSongsBox().add(musicPlayerController.getMusicModel()!.value.copyWith());
      BaseEasyLoading.toast('Collected');
    }
    if (Get.isRegistered<PersonalMusicLibraryController>()) {
      PersonalMusicLibraryController.to.refreshLoveSongs();
    }
    musicPlayerController.getMusicModel()!.update((fn) => fn?.isLove = LoveSongsBox().checkLove(musicPlayerController.getMusicModel()!.value.videoId));
  }

  void onTapDownload() {
    if (OfflineBox().checkDownloaded(musicPlayerController.getMusicModel()?.value.videoId)
        || musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.complete) {
      Get.dialog(
        RemindDialog(
          content: 'Confirm to remove this song?',
          confirmOnTap: () async {
            await OfflineBox().delete(musicPlayerController.getMusicModel()!.value.videoId!);
            musicPlayerController.getMusicModel()!.update((fn) => fn?.taskStatus = null);
            BaseEasyLoading.toast('Removed');
            if (Get.isRegistered<PersonalMusicLibraryController>()) {
              PersonalMusicLibraryController.to.refreshOffline();
            }
          },
        ),
      );
    } else {
      if (musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.enqueued
          || musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.running) {
        DownloadManager().cancelDownload(musicPlayerController.getMusicModel());
      } else {
        DownloadManager().downloadMusic(musicPlayerController.getMusicModel());
      }
    }
  }

  /// 在播放列表中切换歌曲
  void switchMusic(MusicModel musicModel) {
    Get.back();
    musicPlayerController.playMusic(musicModel.videoId, isCurrentPlaylist: true);
  }

  /// 删除播放列表中的歌曲
  void deleteMusic(int index, MusicModel musicModel) {
    musicPlayerController.playlist.removeAt(index);
    if (index < musicPlayerController.currentIndex.value) {
      musicPlayerController.currentIndex.value--;
    }
  }
}