import 'package:flutter_full_pdf_viewer/flutter_full_pdf_viewer.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/popup_window.dart';
import 'package:path_provider/path_provider.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/net/api_service.dart';

// class MeansPDF extends StatefulWidget {
//   @override
//   MeansPDFState createState() => new MeansPDFState();
// }

// class MeansPDFState extends State<MeansPDF> {
//   String pathPDF = "";

//   @override
//   void initState() {
//     super.initState();
//     createFileOfPdfUrl().then((f) {
//       setState(() {
//         pathPDF = f.path;
//         print(pathPDF);
//       });
//     });
//   }

//   Future<File> createFileOfPdfUrl() async {
//     final url = "http://africau.edu/images/default/sample.pdf";
//     final filename = url.substring(url.lastIndexOf("/") + 1);
//     var request = await HttpClient().getUrl(Uri.parse(url));
//     var response = await request.close();
//     var bytes = await consolidateHttpClientResponseBytes(response);
//     String dir = (await getApplicationDocumentsDirectory()).path;
//     File file = new File('$dir/$filename');
//     await file.writeAsBytes(bytes);
//     return file;
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       child: PDFScreen(pathPDF)
//     )
//     ;
//   }
//   // Widget build(BuildContext context) {
//   //   return Scaffold(
//   //     appBar: AppBar(title: const Text('Plugin example app')),
//   //     body: Center(
//   //       child: RaisedButton(
//   //         child: Text("Open PDF"),
//   //         onPressed: () => Navigator.push(
//   //           context,
//   //           MaterialPageRoute(builder: (context) => PDFScreen(pathPDF)),
//   //         ),
//   //       ),
//   //     ),
//   //   );
//   // }
// }

class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  String fileUrl = "";
  String id = "";

  PDFScreen(this.pathPDF, this.fileUrl, this.id);

  GlobalKey _addKey = GlobalKey();

  getUpdateDownLoadNum() {
    // showLoading(context);
    NewApiService().getUpdateDownLoadNum(id, onSuccess: (res) {},
        onError: (code, msg) {
      // dismissLoading(context);
      toasts(msg);
    });
  }

  getViewNum() {
    // showLoading(context);
    NewApiService().getLiftFilesDetail(id, onSuccess: (res) {},
        onError: (code, msg) {
      // dismissLoading(context);
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    print(pathPDF);
    print(fileUrl);
    print(id);
    if (id != null && id != "null") {
      getViewNum();
    }
    Future<String> _findLocalPath() async {
      //这里根据平台获取当前安装目录
      final directory = Theme.of(context).platform == TargetPlatform.android
          ? await getExternalStorageDirectory()
          : await getApplicationDocumentsDirectory();
      return directory.path;
    }

    return PDFViewerScaffold(
        appBar: MyAppBar(
          centerTitle: fileUrl != null && fileUrl != "null" ? '电梯资料库' : "文件详情",
          // actions: [
          //   IconButton(
          //       key: _addKey,
          //       icon: Icon(Iconfont.gengduo),
          //       onPressed: () {
          //         _showAddMenu(context);
          //       })
          // ],
          // actions: <Widget>[
          //   fileUrl!=null&&fileUrl!="null"? FlatButton(
          //     child: Text("下载"),
          //     textColor: Colours.dark_text,
          //     highlightColor: Colors.transparent,
          //     onPressed: () async {
          //       String _localPath = (await _findLocalPath()) + '/Download/';
          //       var pos = fileUrl.lastIndexOf("/");
          //       if (pos == -1) {
          //         pos = fileUrl.lastIndexOf("\\");
          //       }
          //       var filename = fileUrl.substring(pos + 1);
          //       Response responce =
          //           await Dio().download(fileUrl, _localPath + filename);
          //       if (responce.statusCode == 200) {
          //         // Scaffold.of(context).showSnackBar(SnackBar(content: Text("下载成功")));
          //         getUpdateDownLoadNum();
          //         toasts("下载成功");
          //       } else {
          //         // Scaffold.of(context).showSnackBar(SnackBar(content: Text("下载失败")));
          //         toasts("下载失败");
          //       }
          //     },
          //   ):Container(child:null,)
          // ],
        ),
        path: pathPDF);
  }

  _showAddMenu(BuildContext context) {
    final RenderBox button = _addKey.currentContext.findRenderObject();
    final RenderBox overlay = Overlay.of(context).context.findRenderObject();
    var a = button.localToGlobal(
        Offset(button.size.width - 8.0, button.size.height - 12.0),
        ancestor: overlay);
    var b = button.localToGlobal(button.size.bottomLeft(Offset(0, -12.0)),
        ancestor: overlay);
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(a, b),
      Offset.zero & overlay.size,
    );
    final Color backgroundColor = ThemeUtils.getBackgroundColor(context);
    final Color _iconColor = ThemeUtils.getIconColor(context);
    showPopupWindow(
      context: context,
      fullWidth: false,
      isShowBg: true,
      position: position,
      elevation: 2,
      child: GestureDetector(
        onTap: () => NavigatorUtils.goBack(context),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 12.0),
              child: LoadAssetImage(
                "icon_jt",
                width: 8.0,
                height: 4.0,
              ),
            ),
            SizedBox(
              width: 120.0,
              height: 40.0,
              child: FlatButton.icon(
                  textColor: Theme.of(context).textTheme.body1.color,
                  onPressed: () {
                    Navigator.pop(context);
                    // NavigatorUtils.pushResult(
                    //     context, '${TeamRouter.teamCreatePage}', (res) {
                    //   _onRefresh();
                    // });
                  },
                  color: backgroundColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8.0),
                        topRight: Radius.circular(8.0)),
                  ),
                  icon: LoadAssetImage(
                    "wode/icon_team_add",
                    width: 16.0,
                    height: 16.0,
                    color: _iconColor,
                  ),
                  label: const Text("创建团队")),
            ),
            Divider(),
            SizedBox(
              width: 120.0,
              height: 40.0,
              child: FlatButton.icon(
                  textColor: Theme.of(context).textTheme.body1.color,
                  color: backgroundColor,
                  onPressed: () {
                    Navigator.pop(context);
                    // NavigatorUtils.push(
                    //     context, '${TeamRouter.teamSearchPage}');
                  },
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(8.0),
                        bottomRight: Radius.circular(8.0)),
                  ),
                  icon: LoadAssetImage(
                    "wode/icon_team_add",
                    width: 16.0,
                    height: 16.0,
                    color: _iconColor,
                  ),
                  label: const Text("加入团队")),
            ),
          ],
        ),
      ),
    );
  }
}
