// ignore_for_file: deprecated_member_use

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';

/// 图片加载工具类
class ImageWaterMarkUtils {
  ///拿到图片的字节数组
  static Future<ui.Image> loadImageByFile(String path) async {
    var list = await File(path).readAsBytes();
    return loadImageByUint8List(list);
  }

  ///通过[Uint8List]获取图片
  static Future<ui.Image> loadImageByUint8List(Uint8List list) async {
    ui.Codec codec = await ui.instantiateImageCodec(list);
    ui.FrameInfo frame = await codec.getNextFrame();
    return frame.image;
  }

  ///图片加文字
  static imageAddWaterMark(String imagePath, String content) async {
    double imageWidth, imageHeight;

    ///拿到Canvas
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);

    final tasks = [loadImageByFile(imagePath), getTemporaryDirectory()];
    final results = await Future.wait(tasks);

    ///拿到Image对象
    ui.Image? image = results[0] as ui.Image?;

    imageWidth = image!.width.toDouble();
    imageHeight = image.height.toDouble();
    canvas.drawImage(image, const Offset(0, 0), Paint());

    /// 1.生成 ParagraphStyle，可设置文本的基本信息
    final paragraphStyle = ui.ParagraphStyle();

    /// 2.根据 ParagraphStyle 生成 ParagraphBuilder
    final paragraphBuilder = ui.ParagraphBuilder(paragraphStyle);

    ///屏幕宽高
    final screenWidth = window.physicalSize.width;

    ///计算不同尺寸图片上面显示文字的大小
    var fontSize = 42 * imageWidth / screenWidth;

    /// 3.添加样式和文字
    paragraphBuilder
      ..pushStyle(ui.TextStyle(color: Colors.black, fontSize: fontSize))
      ..addText(content);

    /// 4.通过 build 取到 Paragraph
    final paragraph = paragraphBuilder.build();

    /// 5.根据宽高进行布局layout
    paragraph.layout(ui.ParagraphConstraints(width: imageWidth - 30));

    var imageParagraphHeight = imageHeight - paragraph.height;

    Rect rectBg = Rect.fromLTWH(
        10, imageParagraphHeight - 40, imageWidth - 20, paragraph.height + 30);
    Paint paint = Paint()
      ..color = Colors.white38
      ..strokeCap = StrokeCap.round
      ..isAntiAlias = true
      ..filterQuality = FilterQuality.medium
      ..style = PaintingStyle.fill;

    var rrect = RRect.fromRectAndRadius(rectBg, const Radius.circular(10.0));

    canvas.drawRRect(rrect, paint);
    canvas.restore();

    /// 6.绘制
    canvas.drawParagraph(paragraph, Offset(20, imageParagraphHeight - 30));

    ui.Picture picture = recorder.endRecording();

    final img = await picture.toImage(imageWidth.toInt(), imageHeight.toInt());
    final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);

    /// 图片压缩， 不然iOS端照片会很大， 传不上去
    var uint8list = await FlutterImageCompress.compressWithList(
        pngBytes!.buffer.asUint8List(),
        minWidth: 1280,
        minHeight: 720,
        quality: 40);

    Directory? directory = results[1] as Directory?;

    final Directory imageDirectory =
        await Directory('${directory!.path}/image/').create(recursive: true);
    File file = File(
        '${imageDirectory.path}watermark${DateTime.now().millisecondsSinceEpoch}.png');
    await file.writeAsBytes(uint8list);
    return file;
  }

  /// 压缩图片
  static Future<String> compressAndGetFile(File imgFile, quality) async {
    /// 获取应用文档目录路径
    final directory = await getApplicationDocumentsDirectory();
    String path = '${directory.path}/watermarked_image.jpg';
    print(path);
    XFile? file = await FlutterImageCompress.compressAndGetFile(
        imgFile.absolute.path, path,
        minWidth: 1280, minHeight: 720, quality: quality ?? 30);
    return file!.path;
  }

  /// 压缩图片
  static compressWithFile(File file, quality) async {
    Uint8List? uint8list = await FlutterImageCompress.compressWithFile(
        file.absolute.path,
        minWidth: 1280,
        minHeight: 720,
        quality: quality ?? 30);
    return uint8list;
  }

  /// 将图片文件转为Base64编码字符串
  static String imageToBase64(String imagePath) {
    var imageFile = File(imagePath);
    List<int> imageBytes = imageFile.readAsBytesSync();
    return base64Encode(imageBytes);
  }
}

// class ImageUtils {
//   //图片加文字水印
//   static addImageWaterMark(String imagePath, String textStr) async {
//     int imageWidth, imageHeight;
//     //拿到Canvas
//     ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
//     //画布
//     Canvas canvas = Canvas(pictureRecorder);
//     //拿到Image对象
//     ui.Image image = await loadImageByFile(imagePath);
//     //图片、
//
//     imageWidth = image.width;
//     imageHeight = image.height;
//     //把image放到画板上
//     canvas.drawImage(image, const Offset(0, 0), Paint());
//     //屏幕宽高
//     final screenWidth = window.physicalSize.width;
// //    final screenHeight = window.physicalSize.height;
//     //计算不同尺寸图片上面显示文字的大小
//     var fontSize = 42 * imageWidth / screenWidth;
//
//     ///水印文字
//     TextPainter textPainter = TextPainter(
//       text: TextSpan(
//         text: textStr,
//         style: TextStyle(
//           color: Colors.black,
//           fontSize: fontSize,
//           fontWeight: FontWeight.normal,
//         ),
//       ),
//       textAlign: TextAlign.left,
//       textDirection: TextDirection.ltr,
//     );
//     textPainter.layout();
//     //图片宽度-文字的宽度 计算文字在图片右边的位置
//     var widthRightLocation = imageWidth - textPainter.width - 30;
//     //图片高度-文字的高度 计算文字在图片底部的位置
//     var widthBottomLocation = imageHeight - textPainter.height - 50;
//     //白色透明背景四周距离文字的间距
//     var bgSidedSpacing = 30;
//     final rect = Rect.fromLTWH(
//         widthRightLocation,
//         widthBottomLocation,
//         textPainter.width + bgSidedSpacing,
//         textPainter.height + bgSidedSpacing);
//
//     ///水印白色透明背景
//     final paint = Paint()
//       ..color = Colors.white30
//       ..blendMode = BlendMode.srcOver;
//
//     ///将水印背景画到画板上
//     canvas.drawRect(rect, paint);
//
//     ///将水印文字画到画板上
//     textPainter.paint(
//         canvas,
//         Offset(widthRightLocation + (bgSidedSpacing / 2),
//             widthBottomLocation + (bgSidedSpacing / 2)));
//
//     canvas.restore();
//     ui.Picture picture = pictureRecorder.endRecording();
//     final img = await picture.toImage(imageWidth.toInt(), imageHeight.toInt());
//     // final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
//     final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
//
//     final Directory directory = await getTemporaryDirectory();
//     final Directory imageDirectory =
//         await Directory('${directory.path}/image/').create(recursive: true);
//     String targetPath = imageDirectory.path;
//
//     print(targetPath);
//
//     File file = File(
//         '${targetPath}watermark${DateTime.now().millisecondsSinceEpoch}.png');
//     print(file.path);
//     file.writeAsBytesSync(pngBytes!.buffer.asInt8List());
//
//     /// 图片压缩， 不然iOS端照片会很大， 传不上去
//     var uint8list = await compressWithFile(file, 70);
//     file.writeAsBytesSync(uint8list as List<int>);
//     return file;
//   }
//
//   //拿到图片的字节数组
//   static Future<ui.Image> loadImageByFile(String path) async {
//     var list = await File(path).readAsBytes();
//     return loadImageByUint8List(list);
//   }
//
// //通过[Uint8List]获取图片
//   static Future<ui.Image> loadImageByUint8List(Uint8List list) async {
//     ui.Codec codec = await ui.instantiateImageCodec(list);
//     ui.FrameInfo frame = await codec.getNextFrame();
//     return frame.image;
//   }
//
//   /// 将图片文件转为Base64编码字符串
//   static String imageToBase64(String imagePath) {
//     var imageFile = File(imagePath);
//     List<int> imageBytes = imageFile.readAsBytesSync();
//     return base64Encode(imageBytes);
//   }
//
//   /// 压缩图片
//   static Future<String> compressAndGetFile(File imgFile) async {
//     /// 获取应用文档目录路径
//     final directory = await getApplicationDocumentsDirectory();
//     String path = '${directory.path}/watermarked_image.jpg';
//
//     XFile? file = await FlutterImageCompress.compressAndGetFile(
//       imgFile.absolute.path,
//       path,
//       minWidth: 900,
//       minHeight: 600,
//       quality: 30,
//     );
//     return file!.path;
//   }
//
//   /// 压缩图片
//   static compressWithFile(File file, quality) async {
//     Uint8List? uint8list = await FlutterImageCompress.compressWithFile(
//         file.absolute.path,
//         quality: quality ?? 95);
//     return uint8list;
//   }
// }
