import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/bbs/model/control_model.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/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 ControlDetail extends StatefulWidget {
  ControlDetail(this.id);

  final String id;

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

class ControlDetailState extends State<ControlDetail> {
  ScrollController _scrollController = new ScrollController();

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

  @override
  void initState() {
    super.initState();
    this.getControlDetail();
  }

  bool _hasData = false;
  Records detailObj;

  getControlDetail() {
    NewApiService().getControlDetail(widget.id, onSuccess: (res) {
      detailObj = res;
      print("获取详情成功");
      print(res);
      _hasData = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

    return Scaffold(
        appBar: MyAppBar(
          centerTitle: "控制系统资料",
        ),
        body: _hasData
            ? Container(
                child:
                    ListView(controller: _scrollController, children: <Widget>[
                  SectionHeader(
                    title: '控制系统简介',
                  ),
                  Container(
                    height: ScreenUtil().setWidth(130),
                    padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(15),
                        right: ScreenUtil().setWidth(15),
                        bottom: ScreenUtil().setWidth(30),
                        top: ScreenUtil().setWidth(30)),
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(55),
                            height: ScreenUtil().setWidth(55),
                            color: Colors.red,
                            child: LoadNetworkImage(
                              detailObj.logo,
                              fit: BoxFit.cover,
                              // alignment: Alignment.centerLeft,
                            ),
                          ),
                          SizedBox(width: ScreenUtil().setWidth(20)),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  detailObj.name ?? '',
                                  style: TextStyle(
                                    color: Color(0xff000000),
                                    fontSize: 15,
                                  ),
                                  textAlign: TextAlign.start,
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                Text(
                                  detailObj.descr ?? '',
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 3,
                                  style: TextStyle(
                                      color: Color(0xff999999), fontSize: 12),
                                  textAlign: TextAlign.start,
                                ),
                              ],
                            ),
                          )
                        ]),
                  ),
                  Container(
                    height: 5,
                    color: Color(0xffFAF7FA),
                  ),
                  SectionHeader(
                    title: '文件列表',
                  ),
                  Container(child: WorkFile(fileList: detailObj.listFile))
                ]),
              )
            : Center(
                child: Text("正在加载..."),
              ));
  }
}

class WorkFile extends StatelessWidget {
  WorkFile({Key key, this.fileList}) : super(key: key);
  List<dynamic> fileList = [];

  List<Widget> listWidget(context) => fileList.map((item) {
        return InkWell(
          child: Container(
            padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15),
                top: ScreenUtil().setWidth(10),
                bottom: ScreenUtil().setWidth(10)),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 0.5, color: Colours.line),
              ),
            ),
            child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(right: 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(
                      item.name ?? '',
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0xff555A64),
                      ),
                    ),
                  ),
                ]),
          ),
          onTap: () {
            var fileUrl = item.url;
            if (fileUrl != null && fileUrl != '') {
              fileUrl = Utils.getImagePath(item.url);
              print(fileUrl);
              if (Utils.getFileType(fileUrl) == 'image') {
                Navigator.of(context).push(new FadeRoute(
                    page: PhotoViewGalleryScreen(
                  images: [fileUrl], //传入图片list
                  index: 0, //传入当前点击的图片的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, item.id.toString())),
                  );
                  // });
                });
              }
            } else {
              toasts("暂无文件");
            }
          },
        );
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(children: listWidget(context)),
    );
  }

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

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