import 'package:get/get.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/components/view_state_widget.dart';
import 'package:tone_snap/data/api/music_api.dart';
import 'package:tone_snap/data/models/browse_model.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/collect_playlists_box.dart';
import 'package:tone_snap/modules/sideb/collect_playlists/collect_playlists_controller.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/num_util.dart';
import 'package:tone_snap/utils/obj_util.dart';

class AlbumSongListController extends GetxController {
  var musicPlayerController = MusicPlayerController.to;
  var browseId = '';
  var params = '';

  /// 封面 url、标题 、描述
  var coverUrl = ''.obs;
  var title = ''.obs;
  var subtitle = '';
  var description = ''.obs;

  var viewState = ViewState.loading.obs;
  /// 专辑/歌单预览列表
  var musicList = <Rx<MusicModel>>[].obs;

  /// 是否收藏
  var isCollect = false.obs;

  @override
  void onInit() {
    super.onInit();
    Map<String, dynamic> arguments = Get.arguments;
    browseId = arguments['browseId'] ?? '';
    params = arguments['params'] ?? '';
    coverUrl.value = arguments['coverUrl'] ?? '';
    title.value = arguments['title'] ?? '';
    subtitle = arguments['subtitle'] ?? '';
  }

  @override
  void onReady() async {
    super.onReady();
    _checkIsCollect();
    await _requestBrowse();
    viewState.value = musicList.isNotEmpty ? ViewState.normal : ViewState.empty;
  }

  void _checkIsCollect() {
    var model = CollectPlaylistsBox().getList().firstWhereOrNull((e) => e.id == browseId);
    isCollect.value = model != null;
  }

  Future<void> _requestBrowse() async {
    Map<String, dynamic> queryParameters = {
      'browseId': browseId,
      'params': params,
      'prettyPrint': false
    };
    BrowseModel? browseModel = await MusicApi.browse<BrowseModel>(
      queryParameters: queryParameters,
      formJson: BrowseModel.fromMap,
      showToast: true,
    );
    if (browseModel != null) {
      var thumbnails = browseModel.background?.musicThumbnailRenderer?.thumbnail?.thumbnails;
      if (thumbnails != null && thumbnails.isNotEmpty) {
        coverUrl.value = thumbnails.last.url ?? '';
      }
      var tabs = browseModel.contents?.twoColumnBrowseResultsRenderer?.tabs;
      if (tabs != null && tabs.isNotEmpty) {
        var contents = tabs[0].tabRenderer?.content?.sectionListRenderer?.contents;
        if (contents != null && contents.isNotEmpty) {
          var runs = contents[0].musicResponsiveHeaderRenderer?.title?.runs;
          if (runs != null && runs.isNotEmpty) {
            title.value = runs[0].text ?? '';
          }
          var runs1 = contents[0].musicResponsiveHeaderRenderer?.description?.musicDescriptionShelfRenderer?.description?.runs;
          if (runs1 != null && runs1.isNotEmpty) {
            description.value = runs1.map((e) => e.text).join();
          }
        }
      }

      var contents = browseModel.contents?.twoColumnBrowseResultsRenderer?.secondaryContents?.sectionListRenderer?.contents;
      if (contents != null && contents.isNotEmpty) {
        List<MusicShelfRendererContent>? contents1;
        if (contents[0].musicShelfRenderer != null) {
          contents1 = contents[0].musicShelfRenderer?.contents;
        } else if (contents[0].musicPlaylistShelfRenderer != null) {
          contents1 = contents[0].musicPlaylistShelfRenderer?.contents;
        }
        if (contents1 != null && contents1.isNotEmpty) {
          for (var o in contents1) {
            var musicModel = MusicModel();
            var thumbnails = o.musicResponsiveListItemRenderer?.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails;
            if (thumbnails != null && thumbnails.isNotEmpty) {
              musicModel.coverUrl = thumbnails.last.url;
            }

            var flexColumns = o.musicResponsiveListItemRenderer?.flexColumns;
            if (flexColumns != null && flexColumns.isNotEmpty) {
              var runs = flexColumns[0].musicResponsiveListItemFlexColumnRenderer?.text?.runs;
              if (runs != null && runs.isNotEmpty) {
                musicModel.title = runs[0].text;
                if (runs[0].navigationEndpoint?.watchEndpoint != null) {
                  musicModel.videoId = runs[0].navigationEndpoint?.watchEndpoint?.videoId;
                  musicModel.playlistId = runs[0].navigationEndpoint?.watchEndpoint?.playlistId;
                }
              }
              for (var o in flexColumns) {
                var runs = o.musicResponsiveListItemFlexColumnRenderer?.text?.runs;
                if (runs != null && runs.isNotEmpty) {
                  musicModel.subtitle = runs.map((e) => e.text).join();
                }
              }
            }
            var fixedColumns = o.musicResponsiveListItemRenderer?.fixedColumns;
            if (fixedColumns != null && fixedColumns.isNotEmpty) {
              var runs = fixedColumns[0].musicResponsiveListItemFixedColumnRenderer?.text?.runs;
              if (runs != null && runs.isNotEmpty) {
                musicModel.subtitle = '${ObjUtil.getStr(musicModel.subtitle)} • ${runs.map((e) => e.text).join()}';
              }
            }
            var playlistItemData = o.musicResponsiveListItemRenderer?.playlistItemData;
            if (playlistItemData != null) {
              musicModel.videoId = playlistItemData.videoId;
            }
            musicList.add(musicModel.obs);
          }
        }
      }
    }
  }

  /// 点击播放全部歌曲
  Future<void> onTapPlayAll(int type) async {
    if (musicList.isNotEmpty) {
      int index = 0;
      if (type == 1) {
        if (musicPlayerController.getMusicModel() != null) {
          int currentIndex = musicList.indexWhere((e) => e.value.videoId == musicPlayerController.getMusicModel()!.value.videoId);
          index = NumUtil.getRandomNumberExcludingCurrent(0, musicList.length, currentIndex);
        }
      }
      List<MusicModel> playList = await _next(musicList[index].value.videoId, playlistId: musicList[index].value.playlistId);
      musicPlayerController.playMusic(playList[index].videoId, playList: playList);
    }
  }

  /// 获取播放列表
  Future<List<MusicModel>> _next(String? videoId, {String? playlistId}) async {
    List<MusicModel> playList = [];
    NextModel? model = await MusicApi.next(playlistId: playlistId, videoId: videoId, showLoading: true);
    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> onTapCollect() async {
    if (ObjUtil.isNotEmpty(title.value) && musicList.isNotEmpty) {
      if (isCollect.value) {
        await CollectPlaylistsBox().delete(browseId);
        BaseEasyLoading.toast('Removed');
      } else {
        await CollectPlaylistsBox().add(
          id: browseId,
          title: title.value,
          params: params,
          coverUrl: coverUrl.value,
          subtitle: subtitle,
        );
        BaseEasyLoading.toast('Collected');
      }
      _checkIsCollect();
      if (Get.isRegistered<CollectPlaylistsController>()) {
        CollectPlaylistsController.to.getList();
      }
    }
  }

  /// 点击列表
  void onTapItem(MusicModel musicModel) {
    Get.toNamed(AppRoutes.playPage, arguments: {
      'videoId': musicModel.videoId,
      'playlistId': musicModel.playlistId,
    });
  }
}
