import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/http/http_util.dart';
import 'package:wallpaperx/common/http/url.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class CategoryItemController extends GetxController {
  late final EasyRefreshController refreshController =
      EasyRefreshController(controlFinishLoad: true);
  RxList wallpaperList = [].obs;
  late String className = "";
  late ScrollController scrollController;

  /// 页码、每页数量
  int skip = 0;
  int limit = 20;

  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController();
    className = Get.arguments ?? "";
    getImageList(cname: className, cType: 0);
  }

  void getImageList({String? cname, int? cType}) {
    if (className.isNotEmpty) {
      skip = 0;
      loading(show: true);
      HttpUtil.get(Url.searchImages, (callback) async {
        if (callback != null) {
          dynamic res = json.decode(callback);
          refreshController.finishLoad();
          if (res["images"] != null) {
            List list = List.from(res["images"]);
            wallpaperList.clear();
            wallpaperList
                .addAll(list.map((e) => ImageModel.fromJson(e)).toList());
          }
        }
        dismiss(dismiss: true);
      }, params: {"limit": limit, "skip": skip, "query": className});
    }
  }

  /// 上拉加载
  void onLoad({int? loadMore}) {
    skip += limit;
    HttpUtil.get(
      Url.searchImages,
      (callback) async {
        if (callback != null) {
          dynamic res = json.decode(callback);
          refreshController.finishLoad();
          if (res["images"] != null) {
            List list = List.from(res["images"]);
            wallpaperList
                .addAll(list.map((e) => ImageModel.fromJson(e)).toList());
          }
        }
      },
      errorCallback: (e) {
        refreshController.finishLoad();
      },
      params: {"limit": limit, "skip": skip, "query": className},
    );
  }

  /// 点击壁纸
  void toImageDetail(int index, {List? images}) {
    Get.toNamed(AppPages.wallpaperDetailV2, arguments: {
      'position': index,
      'wallpaperList': wallpaperList,
    })?.then((value) {
      if (value != null && value != className) {
        className = value ?? "";
        getImageList(cname: className, cType: 1);
      }
    });
  }
}
