import 'package:flutter/material.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/internal/means/page/means_pdf.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/bbs/model/means_model.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/internal/means/presenter/means_list_presenter.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/widgets/preview_images.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'dart:async';
import 'dart:io';

class MeansList extends StatefulWidget {
  MeansList(this.catagoryId, this.dataTable, this.brandId);

  final String catagoryId;
  final String dataTable;
  final String brandId;

  @override
  MeansListState createState() => MeansListState();
}

class MeansListState
    extends BasePageState<MeansList, MeansListPresenterSeconds> {
  BaseListProvider<MeansDetailModel> provider =
      BaseListProvider<MeansDetailModel>();
  int _page = 1;

  ScrollController _scrollController = new ScrollController();

  String pathPDF = "";

  String searchWord = '';

  @override
  void initState() {
    provider.setStateTypeNotNotify(StateType.loading);
    super.initState();
    _onRefresh();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return ChangeNotifierProvider<BaseListProvider<MeansDetailModel>>(
      create: (_) => provider,
      child: Scaffold(
        appBar: SearchAppBar2(
          onPressed: (text) {
            print(text);
            searchWord = text;
            _onRefresh();
          },
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Consumer<BaseListProvider<MeansDetailModel>>(
                  builder: (_, provider, __) {
                    return MyListView(
                      key: Key('means_list'),
                      itemCount: provider.list.length,
                      stateType: provider.stateType,
                      onRefresh: _onRefresh,
                      loadMore: _loadMore,
                      hasMore: provider.hasMore,
                      itemBuilder: (_, 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(0xffFAF7FA),
                                            // padding: EdgeInsets.only(right:10),
                                            child: Icon(
                                              IconData(0xe648,
                                                  fontFamily: "myfont"),
                                              size: 24.0,
                                              color: Color(0xff53C3FA),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          provider.list[index].name ?? '',
                                          textAlign: TextAlign.left,
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(14),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          onTap: () {
                            var fileUrl = provider.list[index].url;
                            if (fileUrl != null && fileUrl != '') {
                              fileUrl = Utils.getImagePath(provider.list[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;
                                        print(f.path);
                                        print("123456789-----");
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) =>
                                                
                                                PDFScreen(f.path, fileUrl,provider.list[index].id.toString()),
                                          ),
                                        );
                                      },
                                    );
                                  },
                                );
                              }
                            } else {
                              toasts("暂无文件");
                            }
                          },
                        );
                      },
                    );
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.getMeansList(
        _page, widget.dataTable, widget.catagoryId, widget.brandId, searchWord: searchWord);
  }

  Future _loadMore() async {
    _page++;
    await presenter.getMeansList(
        _page, widget.dataTable, widget.catagoryId, widget.brandId, searchWord: searchWord);
  }

  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
  MeansListPresenterSeconds createPresenter() {
    return MeansListPresenterSeconds();
  }
}

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,
          ),
        );
}
