import 'dart:ui';
import 'dart:typed_data';
import 'dart:async';
import 'dart:ui' as ui;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker_saver/image_picker_saver.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wanna_battle/widget/Dialog.dart';
import '../redux/AppState.dart';
import '../model/UserInfo.dart';
import '../widget/LinearButton.dart';
import '../net/HttpManager.dart';
import '../styles/totast.dart';
import '../net/Result.dart';
import '../model/ChannelInfo.dart';

class MyCode extends StatefulWidget {
  @override
  MyCodeState createState() => MyCodeState();
}

class MyCodeState extends State<MyCode> {
  ChannelInfo channelInfo = null;
  num race = 10;

  GlobalKey globalKey = new GlobalKey();

  // 截图boundary，并且返回图片的二进制数据。
  Future<Uint8List> _capturePng() async {
    RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    // 注意：png是压缩后格式，如果需要图片的原始像素数据，请使用rawRgba
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    return pngBytes;
  }

  Future<String> _capturePath(String name) async {
    Directory documentsDirectory = await getExternalStorageDirectory();
    String path = documentsDirectory.path + name;
    return path;
  }

  Future<void> getChannelInfo() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('channelInfo/getOne', data: {'id': StoreProvider.of<AppState>(context).state.userInfo.channel});
    Toast.hide();
    if (res.success && res.data != null) {
      setState(() {
        channelInfo = ChannelInfo.fromJson(res.data);
      });
    }

    Result res2 = await HttpManager.get('systemVariable/get', data: {'name': "ticketPrice"});
    if (res2.success) {
      setState(() {
        race = double.parse( res2.data);
      });
    }
  }

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

    Future.delayed(Duration.zero, () => getChannelInfo());
  }

  @override
  Widget build(BuildContext context) {
    AppBar appbar = AppBar(title: Text('我的推广码'), centerTitle: true);
    double _height = MediaQuery.of(context).size.height - MediaQueryData.fromWindow(window).padding.top - appbar.preferredSize.height;

    return StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          String qrstr = HttpManager.baseUrl + "share?userId=${userInfo.id}&channel=${userInfo.channel}";
          // final cryptor = new PlatformStringCryptor();
          return WillPopScope(
              onWillPop: () {
                Navigator.of(context).pop();
                Toast.hide();
              },
              child: Scaffold(
                  appBar: appbar,
                  body: Container(
                    color: Color(0xFF2B2B42),
                    height: double.infinity,
                    width: double.infinity,
                    child: SingleChildScrollView(
                      child: Container(
                        height: _height - 60,
                        constraints: BoxConstraints(minHeight: 543),
                        margin: EdgeInsets.symmetric(vertical: 30, horizontal: 30),
                        color: Color(0xFF363759),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            RepaintBoundary(
                              key: globalKey,
                              child: Container(
                                width: 256,
                                color: Color(0xFF363759),
                                child: Column(
                                  children: <Widget>[
                                    Container(height: 36),
                                    Image.asset('images/text_yonghuduan.png'),
                                    Container(
                                      height: 7,
                                    ),
                                    Text('扫描二维码加入 ${userInfo.nickname.length <= 5 ? userInfo.nickname : userInfo.nickname.substring(0, 4) + "..."} 的电竞团队',
                                        style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 14, fontWeight: FontWeight.w600)),
                                    Container(height: 25),
                                    Container(
                                      width: 150,
                                      height: 150,
                                      color: Colors.white,
                                      // padding: EdgeInsets.all(7),
                                      child: QrImage(
                                        data: qrstr,
                                        size: 150.0,
                                      ),
                                    ),
                                    Container(
                                      height: 10,
                                    ),
                                    Text(
                                      '扫一扫下载APP',
                                      style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                                    ),
                                    Container(
                                      height: 30,
                                    )
                                  ],
                                ),
                              ),
                            ),

                            // Text(
                            //   channelInfo != null ? '一级队员：每购买一张就会获得${1 * 10 * channelInfo.ratio}' : '',
                            //   style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                            // ),
                            // Text(
                            //   channelInfo != null ? '二级队员：每购买一张就会获得${1 * 10 * channelInfo.ratio2}' : '',
                            //   style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                            // ),
                            Container(
                              // margin: EdgeInsets.only(top: 30),
                              width: 180,
                              child: LinearButton(
                                btntext: '立刻邀请',
                                btnHeight: 44.0,
                                colorList: [Color(0xFFD4504B), Color(0xFFD4504B)],
                                onTapHomeMenu: () async {
                                  var permission = PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
                                  await PermissionHandler().requestPermissions(<PermissionGroup>[
                                    PermissionGroup.storage, // 在这里添加需要的权限
                                  ]);
                                  // MyDialog.showDialog(context, '手动截图立即分享二维码给小伙伴吧！');
                                  Uint8List val = await _capturePng();
                                  print(val);
                                  final result = await ImagePickerSaver.saveFile(fileData: val);
                                  print(result);
                                  // Toast.show(context, '保存成功', 1500, 'success');
                                  MyDialog.showDialog(context, '分享二维码保存成功，请在照片图库中找到并分享给其他人吧。');
                                },
                              ),
                            ),
                            Container(
                              height: 13,
                            ),
                            InkWell(
                              onTap: () {
                                if (channelInfo == null) {
                                  MyDialog.showDialog(context, '用户渠道信息为空，暂不能参与活动');
                                } else {
                                  Navigator.of(context).push(PageRouteBuilder(
                                      opaque: false,
                                      transitionDuration: Duration(milliseconds: 300),
                                      transitionsBuilder:
                                          (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
                                        return FadeTransition(
                                          opacity: CurvedAnimation(parent: animation, curve: Curves.linear),
                                          child: child,
                                        );
                                      },
                                      pageBuilder: (BuildContext context, _, __) {
                                        return Rule(race * channelInfo.ratio / 100, race * channelInfo.ratio2 / 100);
                                      }));
                                }
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    '查看推广奖励规则',
                                    style: TextStyle(color: Theme.of(context).primaryColor),
                                  ),
                                  Image.asset('images/icon_inter_hongse.png')
                                ],
                              ),
                            ),

                            Expanded(
                              flex: 1,
                              child: Container(),
                            ),
                            Image.asset('images/img_0000.png'),
                          ],
                        ),
                      ),
                    ),
                  )));
        });
  }
}

class Rule extends Dialog {
  Rule(this.ratio, this.ratio2);
  double ratio;
  double ratio2;
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xCC000000),
        body: Container(
          child: SizedBox.expand(
            child: UnconstrainedBox(
              child: Container(
                width: 280,
                // padding: EdgeInsets.symmetric(horizontal: 20, vertical: 25),
                decoration: BoxDecoration(color: Color(0xFF15151D), border: Border.all(width: 1, color: Theme.of(context).primaryColor)),
                child: Stack(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 25),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text('推广奖励规则', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w600)),
                          Container(
                            height: 20,
                          ),
                          Text('1、扫描该二维码下载APP的用户成为您的一级成员，可以在“我的团队”中查看 ', style: TextStyle(color: Colors.white, fontSize: 14)),
                          Container(
                            height: 20,
                          ),
                          Text('2、团队一级成员在APP中每购买一张参赛券，您就可以获得${ratio}个积分 ', style: TextStyle(color: Colors.white, fontSize: 14)),
                          Container(
                            height: 20,
                          ),
                          Text('3、团队二级成员在APP中每购买一张参赛券，您就可以获得${ratio2}个积分 ', style: TextStyle(color: Colors.white, fontSize: 14)),
                          Container(
                            height: 35,
                          ),
                          Container(
                              width: double.infinity,
                              child: LinearButton(
                                btntext: '确认',
                                btnHeight: 36.0,
                                onTapHomeMenu: () {
                                  Navigator.of(context).pop();
                                },
                              )),
                          Container(
                            height: 5,
                          )
                        ],
                      ),
                    ),
                    Positioned(
                      top: 0,
                      left: 0,
                      child: Image.asset(
                        'images/tancuang_shang.png',
                        // width: 131,
                      ),
                    ),
                    Positioned(
                      bottom: 0,
                      right: 4,
                      child: Image.asset(
                        'images/tancuang_xia.png',
                        // width: 148,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      onWillPop: () {
        return Future.value(false);
      },
    );
  }
}
