/*
 * @Author: XianKaiQun
 * @Date: 2020-09-09 16:52:06
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-08-08 11:21:03
 * @Description: 
 */
import 'dart:async';
import 'dart:io';

import 'package:app_package/app_package.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:image/image.dart' as imageLib;

class PrivateEditStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateEditStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
    path = routingArgs['path'];
  }

  ///资源路径
  String? path;

  ///资源来源
  WImageSource? get source => routingArgs['source'];

  File get file => File(path!);

  ///图片选择
  Future<void> picker() async {
    final res = await WAssetPickerUtil.image(maxCount: 1, source: source!);
    if (res.length != 0) {
      path = res[0].file!.path;
      notifyListeners();
    }
  }

  final editorKey = GlobalKey<ExtendedImageEditorState>();

  ///裁剪裁剪裁剪
  Future<List<int>> cropImage() async {
    final state = editorKey.currentState!;
    final cropRect = state.getCropRect();
    final data = state.rawImageData;
    imageLib.Image src =
        await compute(imageLib.decodeImage, data) as imageLib.Image;
    final editAction = state.editAction!;
    if (editAction.needCrop) {
      src = imageLib.copyCrop(
        src,
        cropRect!.left.toInt(),
        cropRect.top.toInt(),
        cropRect.width.toInt(),
        cropRect.height.toInt(),
      );
    }
    if (editAction.needFlip) {
      late imageLib.Flip mode;
      if (editAction.flipY && editAction.flipY) {
        mode = imageLib.Flip.both;
      } else if (editAction.flipY) {
        mode = imageLib.Flip.horizontal;
      } else if (editAction.flipY) {
        mode = imageLib.Flip.vertical;
      }
      src = imageLib.flip(src, mode);
    }
    if (editAction.hasEditAction) {
      src = imageLib.copyRotate(src, editAction.rotateDegrees);
    }
    return imageLib.encodePng(src);
  }

  ///上传并关闭路由（回调已上传的图片id）
  Future<void> upload() async {
    WLoadingUtil.show();
    var bytes = await cropImage();
    try {
      final res = await GlobalApi.postUploadImageFormByte(bytes as Uint8List);
      if (res?.data != null) {
        WNavUtil.instance!.pop(res?.data);
      }
    } finally {
      WLoadingUtil.hide();
    }
  }
}
