import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:hello_wallpaper/common/components/view_state_widget.dart';
import 'package:hello_wallpaper/common/utils/obj_util.dart';
import 'package:hello_wallpaper/models/wallpaper_model.dart';
import 'package:hello_wallpaper/modules/home/home_controller.dart';
import 'package:hello_wallpaper/routes/app_pages.dart';

class DiscoverController extends GetxController {
  static DiscoverController get to => Get.find<DiscoverController>();
  late final EasyRefreshController refreshController;
  late ViewState viewState;
  var allWallpaper = <WallpaperData>[];
  var wallpaperDataList = <WallpaperData>[];
  var todayNewestList = <WallpaperData>[];
  WallpaperModel? todayNewestData;

  /// 分类名称
  var clsName = '';

  /// 页码、每页数量
  int pageNum = 1;
  int pageSize = 10;

  @override
  void onInit() {
    super.onInit();
    refreshController = EasyRefreshController(controlFinishLoad: true);
    getData();
  }

  void getData() {
    todayNewestData = HomeController.to.getRandomCls();
    if (todayNewestData != null &&
        todayNewestData!.data != null &&
        todayNewestData!.data!.length >= 3) {
      clsName = ObjUtil.getStr(todayNewestData!.name);
      var flatList = todayNewestData!.data!.map((e) => e).toList();
      // 随机打乱此列表中的元素，再取前3个元素
      todayNewestList = (flatList..shuffle()).take(3).toList();
    }
    viewState = HomeController.to.viewState;
    allWallpaper = HomeController.to.wallpaperModelList
        .expand((element) => element.data ?? <WallpaperData>[])
        .toList();
    // 打乱List顺序
    allWallpaper.shuffle();
    _getDataToShow();
  }

  void _getDataToShow() {
    if (allWallpaper.isNotEmpty) {
      // 开始的索引
      int startIndex = (pageNum - 1) * pageSize;
      // 结束的索引
      int endIndex = startIndex + pageSize;
      wallpaperDataList.addAll(allWallpaper.sublist(startIndex, endIndex));
      refreshController.finishLoad();
    }
    refresh();
  }

  /// 上拉加载
  void onLoad() {
    if (pageNum == (allWallpaper.length / pageSize).ceil()) {
      refreshController.finishLoad(IndicatorResult.noMore);
    } else {
      pageNum++;
      _getDataToShow();
    }
  }

  /// 点击今日最新
  void onTapTodayNewest() {
    Get.toNamed(AppPages.clsDet, arguments: todayNewestData);
  }

  /// 点击壁纸
  void onTapItem(int index) {
    Get.toNamed(AppPages.wallpaperDet, arguments: {
      'position': index,
      'wallpaperList': wallpaperDataList,
    });
  }
}
