import 'dart:async';
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: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/common/utils/shared_util.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/page/home/home_controller.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class RecommendController extends GetxController {
  static RecommendController get to => Get.find<RecommendController>();
  late final EasyRefreshController refreshController;
  late ScrollController scrollController;

  HomeController homeController = Get.find<HomeController>();

  Rx<ViewState> viewState = ViewState.loading.obs;
  RxList banners = [].obs;
  RxList images = [].obs;
  RxInt index = 0.obs;

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

  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController();
    refreshController = EasyRefreshController(controlFinishLoad: true);
    getImages(showLoading: false);
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }

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

  /// PageView页面改变回调
  void onIndexChanged(int index) {
    this.index.value = index;
    update(["discover_background"]);
  }

  void getImages({bool? showLoading}) {
    List<String> tags = UPCache.getInstance().getStringList("labelSettingList");
    HttpUtil.get(
      Url.getImages,
      (callback) async {
        if (callback != null) {
          dynamic res = json.decode(callback);
          refreshController.finishLoad();
          if (res["images"] != null) {
            List list = List.from(res["images"]);
            images.addAll(list.map((e) => ImageModel.fromJson(e)).toList());
            list = (list..shuffle()).take(5).toList();
            banners.addAll(list.map((e) => ImageModel.fromJson(e)).toList());
            viewState = ViewState.normal.obs;
            update(["discover_background"]);
          } else {
            viewState = ViewState.empty.obs;
          }
          _stopTimer();
        }
      },
      showLoading: showLoading,
      errorCallback: (e) {
        _timer ??= Timer.periodic(const Duration(seconds: 2), (Timer t) {
          getImages(showLoading: false);
        });
      },
      params: {"limit": limit, "skip": skip, "tags": tags.join(",")},
    );
  }

  /// 上拉加载
  void onLoad() {
    skip += limit;
    List<String> tags = UPCache.getInstance().getStringList("labelSettingList");
    HttpUtil.get(
      Url.getImages,
      (callback) async {
        if (callback != null) {
          dynamic res = json.decode(callback);
          refreshController.finishLoad();
          if (res["images"] != null) {
            List list = List.from(res["images"]);
            images.addAll(list.map((e) => ImageModel.fromJson(e)).toList());
          }
        }
      },
      showLoading: false,
      errorCallback: (e) {
        refreshController.finishLoad();
      },
      params: {"limit": limit, "skip": skip, "tags": tags.join(",")},
    );
  }

  /// 点击壁纸
  void swiperToImageDetail({String? position}) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': index.value,
      'wallpaperList': banners,
    });
  }

  /// 点击壁纸
  void gridToImageDetail(int index, {String? position}) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': index,
      'wallpaperList': images,
    });
  }

  /// 跳转搜索
  void toSearch() {
    Get.toNamed(AppPages.searchImage);
  }
}
