import 'dart:typed_data';

import 'package:cropperx/cropperx.dart';
import 'package:dio/dio.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/architecture/states/states.dart';
import 'package:flyinsono/pages/upload/cropper.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

/// 电子签名图片剪裁
class SignaturePanel extends FStatefulWidget implements FInteractiveContainer {
  const SignaturePanel({this.pageName = "SignaturePanel", Key? key})
      : super(key: key);
  @override
  final String pageName;
  @override
  FState<SignaturePanel> createState() => _SignaturePanelState();
}

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

  /// 获取初始化的签名图片
  Future<void> setSignature() async {
    final response = await Dio().get(
      Store.user.signature,
      options: Options(
        responseType: ResponseType.bytes,
      ),
    );
    final arg = response.data;
    if (arg != null && Store.user.signature.isNotEmpty && arg is Uint8List?) {
      if (_imageToCrop == null && arg!.length > 0) _imageToCrop = arg;
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FFutureBuilder(
      future: setSignature(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return _buildSignaturePanelScreenPage();
      },
    );
  }

  /// 剪裁图片区域
  FWidget _buildSignaturePanelCropper() {
    final fCropper;
    if (_imageToCrop != null) {
      fCropper = FCropper(
        zoomScale: 3.0,
        aspectRatio: 3.25,
        cropperKey: _cropperKey,
        overlayType: _overlayType,
        rotationTurns: _rotationTurns,
        image: FImage.memory(_imageToCrop!),
      );
    } else {
      fCropper = FInkWell(
        onTap: () {
          _changeImage();
        },
        child: FContainer(
          decoration: BoxDecoration(
            color: Colors.grey[350],
            borderRadius: BorderRadius.all(
              Radius.circular(
                4,
              ),
            ),
          ),
          child: FCenter(
            child: FIcon(
              Icons.add,
              color: Colors.white,
            ),
          ),
        ),
      );
    }

    return fCropper;
  }

  ///PC端图像剪裁
  FWidget _buildSignaturePanelScreenPage() {
    return FSimpleDialog(
      backgroundColor: Colors.white,
      title: FText(
        i18nBook.setting.electronicSignature.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: 200,
          alignment: Alignment.center,
          child: FColumn(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FSizedBox(
                height: 20,
              ),
              FContainer(
                width: 260,
                height: 80,
                child: FStack(
                  children: [
                    _buildSignaturePanelCropper(),
                  ],
                ),
              ),
              FSizedBox(height: 10),
              _buildOperateButtons(),
            ],
          ),
        ),
      ],
      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(
              /// TODO:[Gavin] 多语言-UI-整合
              width: i18nBook.isCurrentChinese ? 65 : 100,
              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: FContainer(
              /// TODO:[Gavin] 多语言-UI-整合
              width: i18nBook.isCurrentChinese
                  ? 65
                  : i18nBook.isCurrentRussian
                      ? 110
                      : 100,
              alignment: Alignment.center,
              child: FText(
                i18nBook.upload.selectAgain.t,
                style: TextStyle(
                  color: FTheme.ins.data.colorScheme.primary,
                ),
              ),
            ),
            onPressed: () {
              _changeImage();
            },
          ),
        ],
      ),
    );
  }

  ///图像操作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,
          ),
        ),
      ],
    );
  }

  void _changeImage() async {
    final xFile = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (xFile != null) {
      final bytes = await xFile.readAsBytes();
      setState(() {
        _imageToCrop = bytes;
      });
    }
  }
}
