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:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:wgshare/utils/my_text.dart';

part 'cached_network_img.g.dart';

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

  return CachedNetworkImage(
    key: useImgRefsh.imageKey.value,
    cacheKey: imageUrl,
    fit: BoxFit.fitWidth,
    width: double.infinity,
    imageUrl: imageUrl,
    imageBuilder: imageBuilder,
    // placeholder: (context, url) => const CircularProgressIndicator(),
    placeholder: (context, url) => Center(child: SpinKitWave(color: Theme.of(context).primaryColor, size: 50.r)),
    errorListener: (e) {
      debugPrint('wgs输出===：图片报错.............$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',
              fit: BoxFit.cover,
            ),
            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()));
  }
}

@hwidget
Widget $photoViewGallery(BuildContext context, {int? initIndex, required List<String> urls}) {
  var useIndex = useState<int>(initIndex != null && initIndex >= 0 ? initIndex : 0);
  var pageController = usePageController();

  useEffect(() {
    if (initIndex != null && initIndex > 0) Future.delayed(Duration.zero, () => pageController.jumpToPage(initIndex));
    return () {};
  }, []);

  return SizedBox(
    width: Get.width / 0.7,
    height: Get.height,
    // child: PhotoView(imageProvider: NetworkImage(url)),
    child: Column(
      children: [
        Expanded(
          child: Stack(
            children: [
              PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                backgroundDecoration: const BoxDecoration(),
                builder: (BuildContext context, int index) {
                  return PhotoViewGalleryPageOptions(
                    imageProvider: NetworkImage(urls[index]),
                    initialScale: PhotoViewComputedScale.contained,
                  );
                },
                itemCount: urls.length,
                pageController: pageController,
                onPageChanged: (i) {
                  useIndex.value = i;
                },
                loadingBuilder: (context, event) {
                  return Center(
                    child: SizedBox(
                      width: 20.r,
                      height: 20.r,
                      child: CircularProgressIndicator(
                        value: event == null ? 0 : (event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 1)),
                      ),
                    ),
                  );
                },
              ),
              Positioned(
                right: 60.w,
                top: 60.h,
                child: IconButton(
                  onPressed: () => Navigator.pop(context),
                  icon: Icon(Icons.close, size: 80.r, color: Colors.white),
                ),
              ),
              Positioned(
                right: 100.w,
                bottom: 0.h,
                child: quickText("${useIndex.value + 1} 张", size: 28.sp, color: Colors.white, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ),
        Container(
          height: 200.h,
          width: double.infinity,
          margin: EdgeInsets.only(bottom: 2.h),
          padding: EdgeInsets.symmetric(horizontal: 200.w),
          alignment: Alignment.center,
          child: ListView.builder(
            itemCount: urls.length,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              return InkWell(
                onTap: () => pageController.jumpToPage(index),
                child: Container(
                  width: 200.w,
                  height: 200.h,
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  decoration: BoxDecoration(
                    border: index == useIndex.value ? Border.all(color: Colors.white, width: 2) : null,
                  ),
                  child: $TheCachedNetworkImage(
                    (_, ImageProvider imageProvider) {
                      return Image(
                        image: imageProvider,
                        fit: BoxFit.fitWidth,
                      );
                    },
                    imageUrl: urls[index],
                  ),
                ),
              );
            },
          ),
        ),
      ],
    ),
  );
}
