/*
 * @Author: WuXiangNan
 * @Date: 2021-07-05 14:43:18
 * @LastEditors: WuXiangNan
 * @LastEditTime: 2021-07-21 11:43:31
 * @Description: 
 */

import 'dart:math';

import 'package:flutter/material.dart';

/// 水印样式
/// rowCount: 当前屏幕宽度中 展示多少列水印
/// columnCount: 当前屏幕高度中，展示多少行水印
/// watermark: 水印展示的文字
/// textStyle: 文字的样式
class WisDisableScreenshotsWatarmark extends StatelessWidget {
  final int rowCount;
  final int columnCount;
  final String text;
  final TextStyle textStyle;

  const WisDisableScreenshotsWatarmark({
    Key? key,
    required this.rowCount,
    required this.columnCount,
    required this.text,
    required this.textStyle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      child: Container(
          child: Column(
        mainAxisSize: MainAxisSize.min,
        children: creatColumnWidgets(),
      )),
    );
  }

  List<Widget> creatRowWdiges() {
    List<Widget> list = [];
    for (var i = 0; i < rowCount; i++) {
      final widget = Expanded(
          child: Container(
              child: Transform.rotate(
                  angle: -pi / 5, child: Text(text, style: textStyle))));
      list.add(widget);
    }
    return list;
  }

  List<Widget> creatColumnWidgets() {
    List<Widget> list = [];
    for (var i = 0; i < columnCount; i++) {
      final widget = Expanded(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: creatRowWdiges(),
        ),
      );
      list.add(widget);
    }
    return list;
  }
}

/// 水印工具类 单例 instance
/// 使用方式：
///
/// 获取实例: WisWatarMarkInstance instance = WisWatarMarkInstance();
/// 添加水印: instance.addWatermark(context, "320321199708134818");
/// 删除水印: instance.removeWatermark();
///
class WisWatarMarkInstance {
  static WisWatarMarkInstance? _instance;
  factory WisWatarMarkInstance() {
    if (_instance == null) {
      _instance = WisWatarMarkInstance.private();
    }
    return _instance!;
  }

  WisWatarMarkInstance.private();

  OverlayEntry? _overlayEntry;

  void addWatermark(BuildContext context, String watermark,
      {int rowCount = 4, int columnCount = 8, TextStyle? textStyle}) async {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
    }
    OverlayState overlayState = Overlay.of(context);
    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
          child: Container(
        padding: EdgeInsets.only(top: 60),
        child: WisDisableScreenshotsWatarmark(
          rowCount: rowCount,
          columnCount: columnCount,
          text: watermark,
          textStyle: textStyle ??
              const TextStyle(
                  color: Color(0x3DBEBEBE),
                  fontSize: 14,
                  decoration: TextDecoration.none),
        ),
      )),
    );
    overlayState.insert(_overlayEntry!);
  }

  void removeWatermark() async {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
      _overlayEntry = null;
    }
  }
}
