import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';

part 'cached_network_img.g.dart';

@hwidget
Widget $theCachedNetworkImage(ImageWidgetBuilder imageBuilder, {required String imageUrl, double? imgWidth}) {
  UseCachedImgRefresh useImgRefsh = UseCachedImgRefresh.use();

  return CachedNetworkImage(
    key: useImgRefsh.imageKey.value,
    cacheKey: imageUrl,
    fit: BoxFit.fitWidth,
    width: imgWidth ?? double.infinity,
    imageUrl: imageUrl,
    imageBuilder: imageBuilder,
    placeholder: (context, url) => Center(child: SpinKitWave(color: Theme.of(context).primaryColor, size: 50.r)),
    errorListener: (e) {
      // print('图片报错.............$e');
    },
    errorWidget: (context, url, error) {
      return GestureDetector(
        onTap: () => (useImgRefsh.imageKey.value = UniqueKey()),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset('assets/images/test_paper_loading_failed.png'),
            quickText('加载失败，点击重试', color: const Color.fromRGBO(148, 163, 182, 1), size: 12.sp),
          ],
        ),
      );
    },
  );
}

// CachedNetworkImage 重新加载图片
class UseCachedImgRefresh {
  ValueNotifier<int> refreshNumber;
  ValueNotifier<Key> imageKey;

  UseCachedImgRefresh._({required this.refreshNumber, required this.imageKey});

  // 工厂构造函数
  factory UseCachedImgRefresh.use() {
    return UseCachedImgRefresh._(refreshNumber: useState(0), imageKey: useState(UniqueKey()));
  }
}
