import 'dart:typed_data';

import 'package:cropperx/cropperx.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/pages/upload/cropper.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

///图像剪裁
class CropperScreen extends FStatefulWidget implements FInteractiveContainer {
  const CropperScreen({this.pageName = "CropperScreen", Key? key})
      : super(key: key);
  @override
  final String pageName;
  @override
  FState<CropperScreen> createState() => _CropperScreenState();
}

class _CropperScreenState extends FState<CropperScreen> {
  final GlobalKey _cropperKey = GlobalKey(debugLabel: 'cropperKey');
  Uint8List? _imageToCrop;
  OverlayType _overlayType = OverlayType.circle;
  int _rotationTurns = 0;

  @override
  FWidget build(BuildContext context) {
    final arg = Get.arguments;
    if (arg != null && arg is Uint8List?) {
      if (_imageToCrop == null && arg!.length > 0) _imageToCrop = arg;
    }

    FWidget page;
    if (kIsMobile) {
      page = _buildMobileCropperScreenPage();
    } else {
      page = _buildDeskCropperScreenPage();
    }
    return page;
  }

  ///手机端图像剪裁
  FWidget _buildMobileCropperScreenPage() {
    return FScaffold(
      backgroundColor: Colors.black,
      body: FSafeArea(
        child: FColumn(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FExpanded(
              child: _buildImagePanel(),
            ),
            FRow(
              children: [
                const FSizedBox(
                  width: 10,
                ),
                FElevatedButton(
                  businessParent: this.widget,
                  name: "back",
                  child: FText(i18nBook.common.back.t),
                  onPressed: () async {
                    Get.back(result: Uint8List(0));
                  },
                ),
                FIconButton(
                  name: "rotationTurns--",
                  businessParent: this.widget,
                  onPressed: () {
                    setState(() => _rotationTurns--);
                  },
                  icon: const FIcon(
                    Icons.rotate_left,
                    color: Colors.white,
                  ),
                ),
                FIconButton(
                  businessParent: this.widget,
                  name: "rotationTurns++",
                  onPressed: () {
                    setState(() => _rotationTurns++);
                  },
                  icon: const FIcon(
                    Icons.rotate_right,
                    color: Colors.white,
                  ),
                ),
                FExpanded(child: const FSizedBox()),
                FElevatedButton(
                  businessParent: this.widget,
                  name: "confirm",
                  child: FText(i18nBook.common.confirm.t),
                  onPressed: () async {
                    final imageBytes = await Cropper.crop(
                      cropperKey: _cropperKey,
                    );

                    if (imageBytes != null) {
                      Get.back(result: imageBytes);
                    }
                  },
                ),
                const FSizedBox(
                  width: 10,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  ///图像显示区域
  FWidget _buildImagePanel() {
    final fCropper = _imageToCrop != null
        ? FCropper(
            zoomScale: 3.0,
            cropperKey: _cropperKey,
            overlayType: _overlayType,
            rotationTurns: _rotationTurns,
            image: FImage.memory(_imageToCrop!),
          )
        : FCropper(
            zoomScale: 3.0,
            cropperKey: _cropperKey,
            overlayType: _overlayType,
            rotationTurns: _rotationTurns,
            image: Image(
              image: AssetImage("assets/images/avatar_man.png"),
            ),
          );
    return fCropper;
  }

  /// 剪裁头像图片区域
  FWidget _buildAvatarCropper() {
    final fCropper = _imageToCrop != null
        ? FCropper(
            zoomScale: 3.0,
            cropperKey: _cropperKey,
            overlayType: _overlayType,
            rotationTurns: _rotationTurns,
            image: FImage.memory(_imageToCrop!),
          )
        : FCropper(
            zoomScale: 3.0,
            cropperKey: _cropperKey,
            overlayType: _overlayType,
            rotationTurns: _rotationTurns,
            image: Image(
              image: AssetImage("assets/images/avatar_man.png"),
            ),
          );
    return fCropper;
  }

  ///PC端图像剪裁
  FWidget _buildDeskCropperScreenPage() {
    return FSimpleDialog(
      backgroundColor: Colors.white,
      title: FText(
        i18nBook.upload.editAvatar.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      children: [
        FContainer(
          margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          width: 360,
          height: 355,
          alignment: Alignment.center,
          child: FColumn(
            children: [
              FSizedBox(
                height: 20,
              ),
              FContainer(
                width: 265,
                height: 265,
                child: FStack(
                  children: [
                    _buildAvatarCropper(),
                  ],
                ),
              ),
              FSizedBox(height: 10),
              _buildOperateButtons(),
              FSizedBox(height: 20),
            ],
          ),
        ),
      ],
      bottomButton: _buildImageCropperBottom(),
    );
  }

  ///图像剪裁器
  FWidget _buildImageCropperBottom() {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FElevatedButton(
            name: "save",
            businessParent: widget,
            child: FContainer(
              width: 65,
              alignment: Alignment.center,
              child: FText(
                i18nBook.common.save.t,
              ),
            ),
            onPressed: () async {
              final imageBytes = await Cropper.crop(
                cropperKey: _cropperKey,
              );

              if (imageBytes != null) {
                Get.back(result: imageBytes);
              }
            },
          ),
          const FSizedBox(
            width: 20,
          ),
          FElevatedButton(
            name: "selectAgain",
            businessParent: this.widget,
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                Colors.white,
              ),
              side: MaterialStateProperty.all(
                BorderSide(
                  color: FTheme.ins.data.colorScheme.buttonSecondary,
                  width: 1,
                ),
              ),
            ),
            child: FText(
              i18nBook.upload.selectAgain.t,
              style: TextStyle(
                color: FTheme.ins.data.colorScheme.primary,
              ),
            ),
            onPressed: () async {
              final xFile =
                  await ImagePicker().pickImage(source: ImageSource.gallery);
              if (xFile != null) {
                final bytes = await xFile.readAsBytes();
                setState(() {
                  print(bytes.length);
                  _imageToCrop = bytes;
                });
              }
            },
          ),
          const FSizedBox(
            width: 20,
          )
        ],
      ),
    );
  }

  ///图像操作IconButton
  FWidget _buildOperateButtons() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        FIconButton(
          businessParent: this.widget,
          name: "rotationTurns--",
          onPressed: () {
            setState(() => _rotationTurns--);
          },
          icon: FIcon(
            Icons.rotate_left,
            color: FTheme.ins.data.colorScheme.primary,
          ),
        ),
        FIconButton(
          businessParent: this.widget,
          name: "rotationTurns++",
          onPressed: () {
            setState(() => _rotationTurns++);
          },
          icon: FIcon(
            Icons.rotate_right,
            color: FTheme.ins.data.colorScheme.primary,
          ),
        ),
      ],
    );
  }
}
