import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../common/routers/index.dart';
import 'index.dart';
import 'widgets/hw_painter.dart';

class HandwritingPage extends GetView<HandwritingController> {
  const HandwritingPage({Key? key}) : super(key: key);

  /// 打开手写板
  static Future<dynamic> startWriting() async {
    return await Get.toNamed(O2OARoutes.commonHandwriting);
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Container(
        color: Colors.white,
        constraints: const BoxConstraints.expand(),
        child: Stack(children: [
          _painterView(context),
          _closeBtn(),
          _saveBtn(context),
          _clearBtn()
        ]));
  }

  /// 手写板画布
  Widget _painterView(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (detail) {
        RenderObject? referenceBox = context.findRenderObject();
        if (referenceBox != null && referenceBox is RenderBox) {
          Offset localPosition =
              referenceBox.globalToLocal(detail.globalPosition);
          controller.paintByData(localPosition);
        }
      },
      onPanEnd: (detail) => controller.paintByData(null),
      child: Obx(() {
        final points = controller.state.points.toList();
        return CustomPaint(
          size: MediaQuery.of(context).size,
          painter: HWPainter(points),
        );
      }),
    );
  }

  /// 清空画布按钮
  Widget _clearBtn() {
    return Positioned(
      right: 16,
      bottom: 16,
      child: IconButton(
        icon: const Icon(
          Icons.refresh,
          size: 32,
          color: Colors.black,
        ),
        onPressed: () => controller.refreshPainter(),
      ),
    );
  }

  /// 保存按钮
  Widget _saveBtn(BuildContext context) {
    return Positioned(
      right: 16,
      top: 16,
      child: TextButton(
        child: Text('save'.tr),
        onPressed: ()=> controller.savePainterToImage(MediaQuery.of(context).size),
      ),
    );
  }

  /// 关闭按钮
  Widget _closeBtn() {
    return Positioned(
      left: 16,
      top: 16,
      child: IconButton(
        icon: const Icon(
          Icons.close,
          size: 32,
          color: Colors.black,
        ),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HandwritingController>(
      builder: (_) {
        return Scaffold(
          body: SafeArea(
            child: _buildView(context),
          ),
        );
      },
    );
  }
}
