import 'dart:math';

import 'package:auto_route/src/route/page_route_info.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:plugin_basic/modules/global_web_page.dart';
import 'package:plugin_basic/modules/preview_photo_page.dart';
import 'package:plugin_basic/router/basic_page_router.dart';
import 'package:plugin_platform/engine/image/image_preview.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/goto_page.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';

class UserEvaluateCardItem extends StatelessWidget {
  final String? useInSence;  // 默认evaluateList 页面   可选值cleanDetailPage
  final String? id;
  final String name;
  final String avator;
  final String time;
  final double? score;
  final String content;
  final List<dynamic>? imageUrls;
  int? rowMaxImageNum;
  int? contentTextMaxLines;
  bool? isPreviewImage;

  UserEvaluateCardItem({
    Key? key,
    this.useInSence = 'evaluateList',
    this.id,
    required this.name,
    required this.avator,
    required this.time,
    this.score = 5.0,
    required this.content,
    this.imageUrls,
    this.rowMaxImageNum = 3,
    this.contentTextMaxLines = 3,
    this.isPreviewImage = true,
  }) : super(key: key);


  @override
  Widget build(BuildContext context) {
    List imageUrlsList = [];
    if(imageUrls != null && imageUrls!.isNotEmpty){
      // dart 取出 imageUrls 里面的前 rowMaxImageNum 张图片
      imageUrlsList = imageUrls!.take(rowMaxImageNum!).toList();
    }
    int totalImageCount = imageUrls!.length;
    int otherImageCount = imageUrls!.length - rowMaxImageNum!;
    int rowActualImageCount = imageUrls!.length > rowMaxImageNum! ? rowMaxImageNum! : imageUrls!.length;


    double avatorWidth = useInSence == 'evaluateList'? 45: 35;
    double avatorHeight = useInSence == 'evaluateList'? 45: 35;
    double nameFontSize = useInSence == 'evaluateList'? 18: 15;
    double starSize = useInSence == 'evaluateList'? 13.5: 12;
    double timeFontSize = useInSence == 'evaluateList'? 13: 10;
    double contentFontSize = useInSence == 'evaluateList'? 15: 11;
    double imageHeight = useInSence == 'evaluateList'? 87: 70;
    return Container(
      child: Column(
        children: [
          Container(
            width: double.infinity,
            // color: Colors.blue,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.max,
              children: [
                MyLoadImage(
                  avator,
                  width: avatorWidth,
                  height: avatorHeight,
                  isCircle: true,
                  fit: BoxFit.cover,
                ).onTap(() {
                  // 点击头像
                }),
                Expanded(
                  child: Container(
                    // color: Colors.yellow,
                    margin: const EdgeInsets.only(left: 5),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        MyTextView(
                          name,
                          isFontMedium: true,
                          fontSize: nameFontSize,
                          textColor: context.appColors.textBlack,
                          maxLines: 1,
                          isTextEllipsis: true,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            // 评分显示
                            Wrap(
                              crossAxisAlignment: WrapCrossAlignment.center,
                              spacing: 5,
                              children: [
                                AnimatedRatingStars(
                                  initialRating: score!,
                                  onChanged: (rating) {
                                  },
                                  readOnly: true,
                                  displayRatingValue: true, // Display the rating value
                                  interactiveTooltips: true, // Allow toggling half-star state
                                  customFilledIcon: Icons.star,
                                  customHalfFilledIcon: Icons.star_half,
                                  customEmptyIcon: Icons.star_border,
                                  filledColor: ColorUtils.string2Color("#FF0000"),
                                  starSize: starSize,
                                  animationDuration: const Duration(milliseconds: 0),
                                  animationCurve: Curves.easeInOut,
                                ),
                                MyTextView(
                                  '${score!}',
                                  isFontMedium: true,
                                  fontSize: 12,
                                  textColor: ColorUtils.string2Color('#767676'),
                                  maxLines: 1,
                                  isTextEllipsis: true,
                                ),
                              ],
                            ),
                            MyTextView(
                              time,
                              isFontRegular: true,
                              fontSize: timeFontSize,
                              textColor: ColorUtils.string2Color('#767676'),
                              maxLines: 1,
                              isTextEllipsis: true,
                              marginLeft: 5,
                            ).expanded(),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12,),
          Container(
              width: double.infinity,
              // color: Colors.red,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    MyTextView(
                      content,
                      textColor: context.appColors.textBlack,
                      fontSize: contentFontSize,
                      maxLines: contentTextMaxLines,
                      textAlign: TextAlign.left,
                      isTextEllipsis: true,
                    ),
                    const SizedBox(height: 12),
                    // 图片
                    LayoutBuilder(
                        builder: (BuildContext context, BoxConstraints constraints) {
                          final maxHeight = constraints.maxHeight;
                          final minHeight = constraints.minHeight;
                          final maxWidth = constraints.maxWidth;
                          // Log.d("---maxHeight-----$maxHeight-- $minHeight  $maxWidth--");
                          return _buildImageSection(
                              context,
                              isPreviewImage!,
                              maxWidth,
                              imageUrlsList,
                              imageUrls,
                              totalImageCount,
                              otherImageCount,
                              rowMaxImageNum!,
                              imageHeight
                          );
                        }
                    )
                  ]
              )
          ),
        ],
      ),
    );
  }


  Widget _buildImageSection(BuildContext context,bool isPreviewImage, double maxWidth, List? imageUrls,List? totalImageUrls, int totalImageCount, int otherImageCount, int rowMaxImageNum, double imageHeight) {
    if (imageUrls != null && imageUrls!.isNotEmpty) {
      final imageCount = imageUrls.length;
      return SizedBox(
          width: maxWidth,
          height: imageHeight,
          child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: List.generate(
                imageUrls.length,
                    (index) => Container(
                    height: imageHeight,
                    width: (totalImageCount < rowMaxImageNum)? maxWidth/rowMaxImageNum - 16 : maxWidth/imageCount - 16,
                    margin: EdgeInsets.only(right: (index!=imageCount-1) ? 16 : 0 ),
                    color: ColorUtils.string2Color("#F2F3F6"),
                    child:Stack(
                        children: [
                          Hero(
                            tag: imageUrls[index],
                            child: MyLoadImage(
                              imageUrls[index],
                              height: 87,
                              // width: maxWidth/imageCount - 16,
                              width: (totalImageCount < rowMaxImageNum)? maxWidth/rowMaxImageNum - 16 : maxWidth/imageCount - 16,
                              fit: BoxFit.cover,
                              // fit:BoxFit.fitWidth,
                              cornerRadius: 5,
                              onClick: (){
                                if(isPreviewImage){
                                  // 点击图片预览
                                  // 过滤掉非字符串类型的元素
                                  List<String> filteredImages = totalImageUrls?.whereType<String>().toList() ?? [];
                                  // PreviewPhotoPage.startInstance(context: context, images: filteredImages, position: index);
                                  // context.appRouter.push(PreviewPhotoPageRoute(images: filteredImages, position: index));
                                  // ImagePreviewEngine.multipleImagePreview(
                                  //     context,
                                  //     filteredImages,
                                  //     heroes: List.generate(filteredImages.length, (index) => filteredImages[index]),
                                  //     onLongPressAction: (url) {}
                                  // );
                                  GotoPage.pushPageByFade(
                                    context: context,
                                    targetPage:
                                    PreviewPhotoPage(images: filteredImages, position: index),
                                  );
                                }
                              },
                            ),
                          ),
                          otherImageCount > 0 && index == imageCount-1 ?
                          Positioned(
                            bottom: 0,
                            right: 0,
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                              color: context.appColors.textBlack.withOpacity(0.5),
                              child: MyTextView(
                                "+$otherImageCount",
                                textColor: Colors.white,
                                fontSize: 12,
                              ),
                            ),
                          ): const SizedBox.shrink(),
                        ]
                    )
                ),
              )
          )
      );
    } else {
      return const SizedBox.shrink();
    }
  }
}