import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/media/image_picker_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_load_image.dart';
import 'image_preview.dart';

/// 九宫格的图片选择与图片展示
class ImageNineGrid extends StatefulWidget {
  final bool isSelectEnable; // 是否能选择
  final List<String> initialImages; // 初始化图片集合
  final int maxImages; // 最多选择的图片
  final double aspectRatio; // 宽高比
  final double spacing; // 横向竖向的间距
  final double borderRadius; //整体边框圆角
  final Function(List<String>) onImagesChanged;

  const ImageNineGrid({
    Key? key,
    this.isSelectEnable = true,
    this.maxImages = 9,
    this.aspectRatio = 1.0,
    this.spacing = 8,
    this.borderRadius = 5.0,
    required this.initialImages,
    required this.onImagesChanged,
  }) : super(key: key);

  @override
  _ImageNineGridState createState() => _ImageNineGridState();
}

class _ImageNineGridState extends State<ImageNineGrid> {
  late List<String> _images;

  @override
  void initState() {
    super.initState();
    _images = List.from(widget.initialImages);
  }

  @override
  void didUpdateWidget(covariant ImageNineGrid oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.initialImages != widget.initialImages) {
      _images = List.from(widget.initialImages);
    }
  }

  // 选择图片
  Future<void> _pickImage() async {
    ImagePickerUtils().show(context, (filePath) {
      if (Utils.isNotEmpty(filePath)) {
        setState(() {
          _images.add(filePath);
        });
        widget.onImagesChanged(_images);
      }
    });
  }

  // 删除图片
  void _removeImage(int index) {
    setState(() {
      _images.removeAt(index);
    });
    widget.onImagesChanged(_images);
  }

  @override
  Widget build(BuildContext context) {
    final gridChildren = List<Widget>.generate(
      _images.length,
      (index) => Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(widget.borderRadius), // 圆角半径
            child: Hero(
              tag: _images[index],
              child: MyLoadImage(
                _images[index],
                width: double.infinity,
                height: double.infinity,
                fit: BoxFit.cover,
              ).onTap(() {
                //预览图片
                ImagePreviewEngine.singleImagePreview(context, _images[index], heroTag: _images[index]);
              }),
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            child: Visibility(
              visible: widget.isSelectEnable,
              child: const MyAssetImage(Assets.baseLibDialogDeleteIcon, width: 24, height: 24).onTap(
                () {
                  if (widget.isSelectEnable) {
                    _removeImage(index);
                  }
                },
              ).padding(top: 5, right: 5, bottom: 5, left: 5),
            ),
          ),
        ],
      ),
    );

    if (widget.isSelectEnable && _images.length < widget.maxImages) {
      gridChildren.add(
        GestureDetector(
          onTap: _pickImage,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF4DCFF6).withOpacity(0.2),
              borderRadius: BorderRadius.circular(widget.borderRadius), // 圆角半径
            ),
            child: const Center(
              child: MyAssetImage(Assets.baseServiceImageAddIcon, width: 20, height: 20),
            ),
          ),
        ),
      );
    }

    return GridView.builder(
      padding: EdgeInsets.zero, // 设置为零，消除任何内边距
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: widget.aspectRatio,
        mainAxisSpacing: widget.spacing,
        crossAxisSpacing: widget.spacing,
      ),
      itemCount: gridChildren.length,
      itemBuilder: (context, index) => gridChildren[index],
    );
  }
}
