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

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/date_extension.dart';

import '../../../common/utils/index.dart';
import 'index.dart';
import 'widgets/hw_painter.dart';
import 'widgets/hw_painter_data.dart';

class HandwritingController extends GetxController {
  HandwritingController();

  final state = HandwritingState();
  final defaultPaintColor = Colors.black; //默认的画笔颜色
  final defaultPaintStokeWidth = 2.0; //默认的画笔宽度
  //TODO 画笔大小，颜色

  @override
  void onReady() {
    _setLandscape(); // 手写板 默认横屏
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    _setPortrait();
    super.onClose();
  }

  /// 手写
  void paintByData(Offset? offset) {
    HWPainterData? data;
    if (offset != null) {
      data = HWPainterData(offset, defaultPaintColor, defaultPaintStokeWidth);
    }
    state.points.add(data);
  }

  /// 清空画布
  void refreshPainter() {
    state.points.clear();
  }

  /// 保存图片
  /// 并返回图片路径到 result 中
  Future<void> savePainterToImage(Size size) async {
    if (state.points.isEmpty) {
      Loading.showError("common_handwriting_msg_error_null_data".tr);
      return;
    }
    Loading.show();
     //画板保存成图片
    var image = await _rendered(size);
    var pngBytes = await image.toByteData(format: ui.ImageByteFormat.png);
    if (pngBytes == null) {
      Loading.showError("common_handwriting_msg_error_null_data".tr);
      return;
    }
    //图片临时存储
    final timeString = 'handwriting_${DateTime.now().millisecondsSinceEpoch}';
    var dir = await O2FilePathUtil.getTempFolderWithUrl(timeString);
    if (dir == null || dir.isEmpty) {
      OLogger.e('本地文件目录生成失败！ url: $timeString');
      Loading.showError('下载失败！');
      return;
    }
    String filePath = '$dir/$timeString.png';
    File file = File(filePath);
    file.writeAsBytesSync(pngBytes.buffer.asInt8List());
    Loading.dismiss();
    // 返回文件路径
    Get.back(result: filePath);
  }

  /// 画布内容 渲染到 Image 中
  Future<ui.Image> _rendered(Size size) async {
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);
    HWPainter painter = HWPainter(state.points);
    painter.paint(canvas, size);
    var image = await recorder
        .endRecording()
        .toImage(size.width.floor(), size.height.floor());
    return image;
  }

  // 设置横屏
  _setLandscape() {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
    if (Platform.isAndroid) {
      ///关闭状态栏，与底部虚拟操作按钮
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    }
  }

  // 设置竖屏
  _setPortrait() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    if (Platform.isAndroid) {
      ///显示状态栏，与底部虚拟操作按钮
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
          overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    }
  }
}
