import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/internal/means/means_router.dart';
import 'package:liftmanager/internal/means/page/means_pdf.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/preview_images.dart';
import 'package:path_provider/path_provider.dart';

class MeansPage extends StatefulWidget {
  String index = "1";

  @override
  State<StatefulWidget> createState() {
    return MeansPageState();
  }
}

class MeansPageState extends State<MeansPage>
    with AutomaticKeepAliveClientMixin {
  // NewsDetailItem item = NewsDetailItem();
  ScrollController _scrollController = new ScrollController();
  String pathPDF = "";

  @override
  void initState() {
    super.initState();
    getBrandList();
    getControlList();
    getGuanList();
  }

  List<dynamic> brandListPage;

  Future getBrandList() async {
    await NewApiService().getBrandListPage(1, 8, onSuccess: (res) {
      brandListPage = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  List<dynamic> controlListPage;
  List<dynamic> guanList;

  Future getControlList() async {
    await NewApiService().getControlListPage(1, 8, topFlag: 1,
        onSuccess: (res) {
      controlListPage = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getGuanList() async {
    await NewApiService().getMeansList(1, 3, 1, null, null, searchWord: "",
        onSuccess: (res) {
      guanList = res.records;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future<File> createFileOfPdfUrl(url) async {
    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
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

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

  // getNewsDetail() {
  //   ApiService().newsDetail(widget.id, onSuccess: (res) {
  //     item = res;
  //     setState(() {});
  //   }, onError: (code, msg) {
  //     toasts(msg);
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(centerTitle: "资料库", isBack: true),
        body: Container(
            child: Stack(
          children: <Widget>[
            Container(
              child: ListView(controller: _scrollController, children: <Widget>[
                SectionHeader(
                  title: '官方文件',
                  onTap: () {
                    NavigatorUtils.push(context,
                        "${MeansRouter.meansList}?catagoryId=&dataTable=1&brandId=");
                  },
                  showMore: true,
                ),
                guanList != null && guanList != []
                    ? Container(
                        child: Column(
                          children: guanList.asMap().keys.map((index) {
                            return GestureDetector(
                              child: Container(
                                padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  right: ScreenUtil().setWidth(15),
                                  top: ScreenUtil().setHeight(10),
                                  bottom: ScreenUtil().setHeight(10),
                                ),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                        width: 0.5, color: Colours.line),
                                  ),
                                ),
                                child: Column(
                                  children: <Widget>[
                                    Container(
                                      padding: EdgeInsets.only(
                                          bottom: ScreenUtil().setHeight(5)),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Container(
                                            padding: EdgeInsets.only(
                                                right:
                                                    ScreenUtil().setWidth(10)),
                                            child: ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(
                                                      ScreenUtil()
                                                          .setWidth(18)),
                                              child: Container(
                                                width:
                                                    ScreenUtil().setWidth(36),
                                                height:
                                                    ScreenUtil().setWidth(36),
                                                color: Color(0xffF7FAFF),
                                                // padding: EdgeInsets.only(right:10),
                                                child: Icon(
                                                  Iconfont.wenjian,
                                                  size: 24.0,
                                                  color: Color(0xff5589FF),
                                                ),
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            child: Text(
                                              guanList[index].name ?? '',
                                              textAlign: TextAlign.left,
                                              style: TextStyle(
                                                color: Color(0xff555A64),
                                                fontSize:
                                                    ScreenUtil().setSp(14),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                var fileUrl = guanList[index].url;
                                if (fileUrl != null && fileUrl != '') {
                                  fileUrl =
                                      Utils.getImagePath(guanList[index].url);

                                  print(fileUrl);
                                  if (Utils.getFileType(fileUrl) == 'image') {
                                    Navigator.of(context).push(
                                      new FadeRoute(
                                        page: PhotoViewGalleryScreen(
                                          images: [fileUrl], //传入图片list
                                          index: index, //传入当前点击的图片的index
                                          // heroTag: img,//传入当前点击的图片的hero tag （可选）
                                        ),
                                      ),
                                    );
                                  } else if (Utils.getFileType(fileUrl) ==
                                      'pdf') {
                                    createFileOfPdfUrl(fileUrl).then(
                                      (f) {
                                        setState(
                                          () {
                                            pathPDF = f.path;
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder: (context) => PDFScreen(
                                                    f.path,
                                                    fileUrl,
                                                    guanList[index]
                                                        .id
                                                        .toString()),
                                              ),
                                            );
                                          },
                                        );
                                      },
                                    );
                                  }
                                } else {
                                  toasts("暂无文件");
                                }
                              },
                            );
                          }).toList(),
                        ),
                      )
                    : loadCircle(),
                Container(
                  height: ScreenUtil().setWidth(5),
                  color: ThemeUtils.getDialogTextFieldColor(context),
                ),
                SectionHeader(
                  title: '电梯品牌',
                  onTap: () {
                    NavigatorUtils.push(context, MeansRouter.brandList);
                  },
                  showMore: true,
                ),
                brandListPage != null && brandListPage != []
                    ? Brand(
                        initList: brandListPage,
                        fun: (id) {
                          NavigatorUtils.push(
                              context, "${MeansRouter.brandDetail}?id=$id");
                        })
                    : loadCircle(),
                Container(
                  height: ScreenUtil().setWidth(5),
                  color: ThemeUtils.getDialogTextFieldColor(context),
                ),
                SectionHeader(
                  title: '控制系统',
                  onTap: () {
                    NavigatorUtils.push(context, MeansRouter.controlList);
                  },
                  showMore: true,
                ),
                controlListPage != null && controlListPage != []
                    ? Brand(
                        initList: controlListPage,
                        fun: (id) {
                          NavigatorUtils.push(
                              context, "${MeansRouter.controlDetail}?id=$id");
                        })
                    : loadCircle()
              ]),
            ),
          ],
        )));
  }

  Widget loadCircle() {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      color: ThemeUtils.getTabsBg(context),
      child: Center(
        child: SpinKitFadingCircle(
          color: Colors.blueAccent,
          size: 30.0,
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class Brand extends StatelessWidget {
  const Brand({Key key, this.initList, this.fun}) : super(key: key);
  final Function fun;
  final List<dynamic> initList;

  List<Widget> brandList(context) => initList.map((item) {
        double width = MediaQuery.of(context).size.width;
        return Container(
          // color:Colors.yellow,
          child: FlatButton(
            padding: EdgeInsets.all(0),
            highlightColor: Colors.white,
            splashColor: Colors.white,
            child: Container(
              width: width / 4,
              height: ScreenUtil().setWidth(100),
              // color: Colors.red,
              padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(10),
                  right: ScreenUtil().setWidth(10),
                  top: ScreenUtil().setWidth(10)),
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      child: LoadNetworkImageAlt(
                        item.logo,
                        width: ScreenUtil().setWidth(50),
                        height: ScreenUtil().setWidth(50),
                        // alignment: Alignment.centerLeft,
                      ),
                    ),
                    SizedBox(height: 10,),
                    Container(
                      child: Text(
                        item.name ?? "",
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 12),
                        textAlign: TextAlign.start,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ]),
            ),
            onPressed: () {
              fun(item.id);
            },
          ),
        );
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: 5),
        child: Wrap(
          // spacing: 16,
          alignment: WrapAlignment.start,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: brandList(context),
        ));
  }
}

class FadeRoute extends PageRouteBuilder {
  final Widget page;

  FadeRoute({this.page})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              page,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
}
