import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/components/appbar.dart';
import 'index.dart';
import 'widgets/widgets.dart';

// import 'package:video_player/video_player.dart';

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<IdCardScanController>(
      init: IdCardScanController(),
      builder: (_) {
        return Scaffold(
          appBar: VAppBar(
            titleText: "身份证识别",
          ),
          body: SafeArea(
            child: Obx(
              () => controller.state.isCameraReady
                  ? _buildCameraArea()
                  : const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                      ),
                    ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildCameraArea() {
    return Row(
      children: [
        // const IdCardInfo(),
        Expanded(
          child: ClipRRect(
            child: LayoutBuilder(builder: (context, constraints) {
              return Stack(
                children: <Widget>[
                  OverflowBox(
                    maxHeight: constraints.maxHeight,
                    maxWidth: 2000,
                    child: Container(
                      color: Colors.black,
                      child: Center(
                        child: _cameraPreviewWidget(),
                      ),
                    ),
                  ),
                  const Center(
                    child: CameraForIdCard(),
                  ),
                  const ImageDetectingDialog(),
                ],
              );
            }),
          ),
        ),
      ],
    );
  }

  /// 相机预览
  Widget _cameraPreviewWidget() {
    final CameraController? cameraController = controller.kCameraController;
    if (cameraController == null || !cameraController.value.isInitialized) {
      /// 旋转loading
      return const Center(
        child: CircularProgressIndicator(),
      );
    } else {
      return Listener(
        onPointerDown: (_) => controller.pointers++,
        onPointerUp: (_) => controller.pointers--,
        child: CameraPreview(
          cameraController,
          child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onScaleStart: controller.handleScaleStart,
                onScaleUpdate: controller.handleScaleUpdate,
                onTapDown: (TapDownDetails details) =>
                    controller.onViewFinderTap(details, constraints),
                child: Container(),
              );
            },
          ),
        ),
      );
    }
  }
}
