import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:save_image/save_image.dart';
import 'package:zhiying_base_widget/pages/favorite_page/preview_page.dart';
import 'package:zhiying_base_widget/template/goods_share_template/goods_share_template.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class FavoritePage extends StatefulWidget {
  @override
  _FavoritePageState createState() => _FavoritePageState();
}

class _FavoritePageState extends State<FavoritePage> {
  GlobalKey _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('收藏夹'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            width: 100,
            height: 200,
            child: Transform.scale(
              scale: 0.2,
              child: GoodsShareTemplate(
                contentKey: _globalKey,
              ),
            ),
          ),
          FlatButton(
            child: Icon(Icons.add),
            onPressed: () async {
              try {
                BuildContext buildContext = _globalKey.currentContext;

                if (null != buildContext) {
                  RenderRepaintBoundary boundary =
                      buildContext.findRenderObject();
                  ui.Image image = await boundary.toImage(pixelRatio: 2.0);
                  // 注意：png是压缩后格式，如果需要图片的原始像素数据，请使用rawRgba
                  ByteData byteData =
                      await image.toByteData(format: ui.ImageByteFormat.png);
                  Uint8List pngBytes = byteData.buffer.asUint8List();

                  if (false) {
                    bool isSaveSuccess =
                        await SaveImage.save(imageBytes: pngBytes);
                    if (isSaveSuccess) {
                      Fluttertoast.showToast(msg: '保存成功');
                    } else {
                      Fluttertoast.showToast(msg: '保存失败');
                    }
                  }

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PreviewPage(
                        image: Image.memory(pngBytes),
                      ),
                    ),
                  );
                }
              } catch (err) {
                Logger.error(err);
              }
            },
          )
        ],
      ),
    );
  }
}
