import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
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/http/http_util.dart';
import 'package:wallpaperx/common/http/url.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/config/applovin.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class SearchImageController extends GetxController {
  late final EasyRefreshController refreshController;
  late ScrollController scrollController;
  RxList searchList = [].obs;
  RxInt total = 0.obs;

  TextEditingController searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();

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

  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController(initialScrollOffset: 0.0);
    refreshController = EasyRefreshController(controlFinishLoad: true);
  }

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

  void searchImages({int? imageType}) {
    ApplovinUtil().showAdIfReady();
    if (searchController.text.isNotEmpty) {
      loading(show: true);
      HttpUtil.get(Url.searchImages, (callback) async {
        if (callback != null) {
          dynamic res = json.decode(callback);
          refreshController.finishLoad();
          if (res["images"] != null && res["images"].length > 0) {
            total.value = res["total"];
            List list = List.from(res["images"]);
            searchList.clear();
            searchList.addAll(list.map((e) => ImageModel.fromJson(e)).toList());
          } else {
            toast("The search result is empty");
          }
        }
        dismiss(dismiss: true);
      }, params: {
        "limit": limit,
        "skip": skip,
        "query": searchController.text
      });
    } else {
      LogPrint.d("搜索内容不能为空");
    }
  }

  /// 上拉加载
  void onLoad() {
    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"]);
            searchList.addAll(list.map((e) => ImageModel.fromJson(e)).toList());
          }
        }
      },
      errorCallback: (e) {
        refreshController.finishLoad();
      },
      params: {"limit": limit, "skip": skip, "query": searchController.text},
    );
  }

  /// 点击壁纸
  void toImageDetail(int position, {List? wallpaperList}) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': position,
      'wallpaperList': searchList,
    });
  }

  inputSearchText(tag, {String? text}) {
    if (tag != "") {
      searchController.text = tag;
      searchFocusNode.requestFocus();
    }
  }
}
