import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/components/view_state_widget.dart';
import 'package:wallpaperx/common/http/http_util.dart';
import 'package:wallpaperx/common/http/url.dart';
import 'package:wallpaperx/config/applovin.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/res/values/strings.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class CategoryController extends GetxController {
  late ScrollController scrollController;
  late ViewState viewState;
  RxMap categoryData = {}.obs;
  RxString title = ''.obs;

  @override
  void onInit() {
    super.onInit();
    Map<String, dynamic> arguments = Get.arguments ?? {};
    title.value = arguments['title'] ?? appName;
    scrollController = ScrollController();
    getData();
  }

  @override
  void onClose() {
    ApplovinUtil().showAdIfReady();
    scrollController.dispose();
    super.onClose();
  }

  void getData({bool? show = true}) {
    loading(show: show ?? false);
    HttpUtil.get(Url.byCategory, (callback) async {
      if (callback != null) {
        dynamic res = json.decode(callback);
        if (res["images"] != null) {
          categoryData.value = res["images"];
        }
      }
      dismiss(dismiss: true);
    }, params: {
      "category": title,
    });
  }

  /// 进入分类详情页面
  void toCategoryItem(title, {String? jumpType}) {
    Get.toNamed(AppPages.categoryItem, arguments: title);
  }

  /// 点击壁纸
  void toImageDetail(
    int position,
    List<ImageModel> wallpaperList, {
    String? jumpType,
  }) {
    RxList rxList = RxList.from(wallpaperList);
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': position,
      'wallpaperList': rxList,
    });
  }
}
