import 'package:get/get.dart';
import 'package:tone_snap/components/view_state_widget.dart';
import 'package:tone_snap/data/api/music_api.dart';
import 'package:tone_snap/data/enum/browse_type.dart';
import 'package:tone_snap/data/models/browse_model.dart';
import 'package:tone_snap/data/models/home_model.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/obj_util.dart';

class HomeController extends GetxController {
  var viewState = ViewState.loading.obs;
  var homeList = <HomeModel>[].obs;
  String? visitorData;

  @override
  void onReady() {
    super.onReady();
    _firstBrowse();
  }

  /// 首次请求
  Future<void> _firstBrowse() async {
    Map<String, dynamic> queryParameters = {
      'prettyPrint': false,
      'browseId': 'FEmusic_home'
    };
    BrowseModel? browseModel = await MusicApi.browse<BrowseModel>(queryParameters: queryParameters, formJson: BrowseModel.fromMap);
    if (browseModel != null) {
      _extractAssemblyData(browseModel);

      // 获取 visitorData
      visitorData = browseModel.responseContext?.visitorData;

      // 获取 continuation、clickTrackingParams
      var continuations = browseModel.contents?.singleColumnBrowseResultsRenderer?.tabs?[0].tabRenderer?.content?.sectionListRenderer?.continuations;
      String? continuation;
      String? clickTrackingParams;
      if (continuations != null && continuations.isNotEmpty) {
        continuation = continuations[0].nextContinuationData?.continuation;
        clickTrackingParams = continuations[0].nextContinuationData?.clickTrackingParams;
      }
      _reBrowse(continuation: continuation, clickTrackingParams: clickTrackingParams);
    }
  }

  /// 复用请求
  Future<void> _reBrowse({String? continuation, String? clickTrackingParams}) async {
    Map<String, dynamic> queryParameters = {
      'ctoken': continuation,
      'continuation': continuation,
      'type': 'next',
      'itct': clickTrackingParams,
      'prettyPrint': false
    };
    BrowseModel? browseModel = await MusicApi.browse<BrowseModel>(visitorData: visitorData, queryParameters: queryParameters, formJson: BrowseModel.fromMap);
    if (browseModel != null) {
      _extractAssemblyData(browseModel);

      var continuations = browseModel.continuationContents?.sectionListContinuation?.continuations;
      if (continuations != null && continuations.isNotEmpty) {
        // continuation、clickTrackingParams 若不为空，继续请求
        if (continuations[0].nextContinuationData?.continuation != null && continuations[0].nextContinuationData?.clickTrackingParams != null) {
          _reBrowse(continuation: continuations[0].nextContinuationData?.continuation, clickTrackingParams: continuations[0].nextContinuationData?.clickTrackingParams);
        }
      }
    }
  }

  /// 提取首页数据，组装展示数据
  void _extractAssemblyData(BrowseModel browseModel) {
    List<SectionListContinuationContent>? contents;
    if (browseModel.contents?.singleColumnBrowseResultsRenderer?.tabs?[0].tabRenderer?.content != null) {
      contents = browseModel.contents?.singleColumnBrowseResultsRenderer?.tabs?[0].tabRenderer?.content?.sectionListRenderer?.contents;
    } else if (browseModel.continuationContents != null) {
      contents = browseModel.continuationContents?.sectionListContinuation?.contents;
    }
    if (contents != null && contents.isNotEmpty) {
      for (var e1 in contents) {
        HomeModel model = HomeModel();

        // 获取头部标题
        var runs = e1.musicCarouselShelfRenderer?.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs;
        if (runs != null && runs.isNotEmpty) {
          model.headerTitle = runs[0].text;
        }
        var contents = e1.musicCarouselShelfRenderer?.contents;
        if (contents != null) {
          model.contents = [];
          for (var e2 in contents) {
            Content content = Content();

            // 获取封面缩略图
            List<ThumbnailElement>? thumbnails;
            if (e2.musicResponsiveListItemRenderer != null) {
              thumbnails = e2.musicResponsiveListItemRenderer?.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails;

              var flexColumns = e2.musicResponsiveListItemRenderer?.flexColumns;
              if (flexColumns != null) {
                for (var e3 in flexColumns) {
                  var runs = e3.musicResponsiveListItemFlexColumnRenderer?.text?.runs;
                  if (flexColumns.indexOf(e3) == 0) {
                    if (runs != null && runs.isNotEmpty) {
                      // 获取主标题
                      content.title = runs[0].text;

                      // 获取数据类型
                      if (runs[0].navigationEndpoint?.watchEndpoint != null) {
                        model.browseType = runs[0].navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType;
                        content.videoId = runs[0].navigationEndpoint?.watchEndpoint?.videoId;
                        content.playlistId = runs[0].navigationEndpoint?.watchEndpoint?.playlistId;
                      } else if (runs[0].navigationEndpoint?.browseEndpoint != null) {
                        model.browseType = runs[0].navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
                        content.browseId = runs[0].navigationEndpoint?.browseEndpoint?.browseId;
                        content.params = runs[0].navigationEndpoint?.browseEndpoint?.params;
                      }
                    }
                  } else {
                    // 获取副标题
                    if (runs != null && runs.isNotEmpty) {
                      content.subTitle = (ObjUtil.isNotEmptyStr(content.subTitle) ? '${content.subTitle} • ' : '') + runs.map((e) => e.text).join();
                    }
                  }
                }
              }
            } else if (e2.musicTwoRowItemRenderer != null) {
              thumbnails = e2.musicTwoRowItemRenderer?.thumbnailRenderer?.musicThumbnailRenderer?.thumbnail?.thumbnails;

              // 获取主标题
              var runs = e2.musicTwoRowItemRenderer?.title?.runs;
              if (runs != null && runs.isNotEmpty) {
                content.title = runs[0].text;
              }

              // 获取副标题
              var subtitleRuns = e2.musicTwoRowItemRenderer?.subtitle?.runs;
              if (subtitleRuns != null && subtitleRuns.isNotEmpty) {
                content.subTitle = subtitleRuns.map((e) => e.text).join();
              }

              // 获取数据类型
              if (e2.musicTwoRowItemRenderer?.navigationEndpoint != null) {
                model.browseType = e2.musicTwoRowItemRenderer?.navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
                content.browseId = e2.musicTwoRowItemRenderer?.navigationEndpoint?.browseEndpoint?.browseId;
                content.params = e2.musicTwoRowItemRenderer?.navigationEndpoint?.browseEndpoint?.params;
              }
            }
            if (thumbnails != null && thumbnails.isNotEmpty) {
              content.thumbnail = thumbnails.last.url;
            }
            model.contents?.add(content);
          }
        }
        // 根据类型判断是否添加
        if (BrowseTypeExtension.isThereAny(model.browseType)) {
          homeList.add(model);
        }
      }
    }
    viewState.value = homeList.isNotEmpty ? ViewState.normal : ViewState.empty;
  }
  
  /// 打开播放页面
  void openPlayPage(Content content) {
    Get.toNamed(AppRoutes.playPage, arguments: {'playlistId': content.playlistId, 'videoId': content.videoId});
  }

  /// 打开歌单/专辑页面
  void openSongSheet(Content content) {
    Get.toNamed(AppRoutes.album, arguments: {'browseId': content.browseId});
  }
}
