import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard/resource/assets.gen.dart';
import 'package:lottie/lottie.dart';

import '../../../../data/bean/upload_info.dart';
import '../../../../resource/colors.gen.dart';
import '../../../../resource/string.gen.dart';
import '../../../../utils/prefix_util.dart';
import '../../../../utils/upload/file_data_source_util.dart';
import '../../../../utils/upload/upload_state.dart';
import '../../../../widget/rotate_image.dart';

/// 点击了条目时回调
typedef OnClickItemCallback = void Function(UploadInfo uploadInfo);

/// 点击了删除按钮时回调
typedef OnClickDeleteCallback = void Function(UploadInfo uploadInfo);

/// 上传项组件，有3种状态，上传成功、上传中、上传失败
class UploadItemWidget extends StatelessWidget {
  /// 图片的上传信息
  final UploadInfo imageUploadInfo;

  /// 是否有删除按钮
  final bool hasDeleteBtn;

  /// 上传失败时的遮罩组件
  final Widget? uploadFailMaskWidget;

  /// 点击条目时回调
  final OnClickItemCallback onClickItemCallback;

  /// 点击删除时回调
  final OnClickDeleteCallback? onClickDeleteCallback;

  const UploadItemWidget({
    super.key,
    required this.imageUploadInfo,
    this.hasDeleteBtn = false,
    this.uploadFailMaskWidget,
    required this.onClickItemCallback,
    this.onClickDeleteCallback,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        onClickItemCallback(imageUploadInfo);
      },
      child: Container(
        // decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.5.r)),
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 图片
            ClipRRect(
              // 图片裁切成圆角
              borderRadius: BorderRadius.circular(12.5.r),
              child: _buildImage(),
            ),
            // 上传状态的遮罩层
            _buildMaskByUploadStatus(
              UploadState.fromString(imageUploadInfo.uploadState ?? ""),
            ),
            // 删除按钮
            Visibility(
              visible: hasDeleteBtn,
              child: Positioned(right: 3.w, top: 3.w, child: _buildDeleteBtn()),
            ),
          ],
        ),
      ),
    );
  }

  /// 图片
  Widget _buildImage() {
    String src = FileDataSourceUtil.getFileDataSourceSrc(imageUploadInfo);
    // 网络图片
    if (PrefixUtil.isRemoteImage(src)) {
      return CachedNetworkImage(
        imageUrl: src,
        // 宽高铺满父组件
        height: double.infinity,
        width: double.infinity,
        fit: BoxFit.cover,
        // 关闭淡入动画
        fadeInDuration: Duration.zero,
        // 关闭淡出动画
        fadeOutDuration: Duration.zero,
      );
    } else {
      // 本地图片
      return Image.file(
        File(src),
        height: double.infinity,
        width: double.infinity,
        fit: BoxFit.cover,
      );
    }
  }

  /// 根据状态，构建遮罩
  Widget _buildMaskByUploadStatus(UploadState? uploadState) {
    if (uploadState == null) {
      return SizedBox();
    }
    switch (uploadState) {
      case UploadState.success:
        // 上传成功，不显示遮罩
        return SizedBox();
      case UploadState.uploading:
        // 上传中
        return UploadingMaskWidget();
      case UploadState.fail:
        // 上传失败
        return uploadFailMaskWidget != null
            ? uploadFailMaskWidget!
            : UploadFailMaskWidget();
    }
  }

  /// 删除按钮
  Widget _buildDeleteBtn() {
    // InkWell，扩大点击范围
    return InkWell(
      // 去掉水波纹颜色
      splashColor: ColorName.transparent,
      onTap: () {
        // 执行删除
        if (onClickDeleteCallback != null) {
          onClickDeleteCallback!(imageUploadInfo);
        }
      },
      child: Container(
        padding: EdgeInsets.all(3.w),
        child: Assets.images.iconUploadDelete.image(height: 20.w, width: 20.w),
      ),
    );
  }
}

/// 上传中状态的遮罩
class UploadingMaskWidget extends StatelessWidget {
  const UploadingMaskWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      // 宽度和高度，都撑满父组件
      width: double.maxFinite,
      height: double.maxFinite,
      // 圆角背景
      decoration: BoxDecoration(
        color: ColorName.black50,
        borderRadius: BorderRadius.circular(12.5.r),
      ),
      child: Column(
        // 图标和文字都居中
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 加载中的图标
          Lottie.asset(
            Assets.anim.animUploadLoading,
            repeat: true,
            width: 34.w,
            height: 34.w,
          ),
          // 间距
          SizedBox(height: 4.h),
          // 文字
          Text(
            StringName.intimacyAnalyseUploading,
            style: TextStyle(
              color: ColorName.white,
              fontSize: 12.sp,
              fontWeight: FontWeight.w700,
            ),
          ),
        ],
      ),
    );
  }
}

/// 上传失败状态的遮罩
class UploadFailMaskWidget extends StatelessWidget {
  final Widget? iconWidget;

  final Widget? spaceWidget;

  final Widget? textWidget;

  const UploadFailMaskWidget({
    super.key,
    this.iconWidget,
    this.spaceWidget,
    this.textWidget,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      // 宽度和高度，都撑满父组件
      width: double.maxFinite,
      height: double.maxFinite,
      // 圆角背景
      decoration: BoxDecoration(
        color: ColorName.black50,
        borderRadius: BorderRadius.circular(12.5.r),
      ),
      child: Column(
        // 图标和文字都居中
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 图标
          iconWidget != null
              ? iconWidget!
              : Assets.images.iconUploadFail.image(width: 26.w, height: 26.w),
          // 间距
          spaceWidget != null ? spaceWidget! : SizedBox(height: 6.h),
          // 文字
          textWidget != null
              ? textWidget!
              : Text(
                StringName.intimacyAnalyseUploadFail,
                style: TextStyle(
                  color: ColorName.white,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w700,
                ),
              ),
        ],
      ),
    );
  }
}
