import 'dart:convert';

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/net/api_service.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/time_format.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/preview_images.dart';
import 'package:orientation/orientation.dart';
import 'package:video_player/video_player.dart';

class RecommendAsk extends StatefulWidget {
  RecommendAsk(this.id, this.type);

  final String id;
  final String type;

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

class RecommendAskState extends State<RecommendAsk> {
  // NewsDetailItem item = NewsDetailItem();

  ScrollController _scrollController = new ScrollController();
  VideoPlayerController _controller;
  @override
  void initState() {
    super.initState();
    // getDetail();
    Future.delayed(Duration(milliseconds: 100), () {
      getDetail();
    });
  }

  bool _hasData = false;
  List<String> listPreview = [];
  var detailObj;
  getDetail() {
    NewApiService().getLiftcaseDetail(int.parse(widget.id), onSuccess: (res) {
      detailObj = res;
      if (_controller == null && detailObj.videoUrl != null) {
        _controller =
            VideoPlayerController.network(Utils.getImagePath(detailObj.videoUrl)
                // imgFontUrl + detailObj.url
                );
      }

      listPreview = [];

      detailObj.imgs.split(",").forEach((element) {
        listPreview.add(Utils.getImagePath(element, isWater: true));
      });
      print("获取详情成功");
      print(JsonEncoder().convert(res));
      _hasData = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  orderReceiving() {
    var obj = {"acceptStatus": 1, "id": detailObj.id};

    NewApiService().orderReceiving(obj, onSuccess: (res) {
      toasts("操作成功");
      if (_controller != null) {
        _controller.pause();
      }
      NavigatorUtils.push(context,
          "${BbsRouter.chatRoom}?id=${detailObj.sessionId}&type=someToOne&toUserId=''");
      _hasData = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  orderRefuze() {
    NewApiService().orderRefuze(detailObj.id, onSuccess: (res) {
      toasts("操作成功");
      if (_controller != null) {
        _controller.pause();
      }
      NavigatorUtils.push(context, BbsRouter.workPlace);
      _hasData = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  getTitle() {
    String str;
    if (widget.type == "1") {
      str = "问诊推荐";
    } else if (widget.type == "2") {
      str = "出诊推荐";
    } else if (widget.type == "3") {
      str = "诊单详情";
    }
    return str;
  }

  @override
  void dispose() {
    if (_controller != null) {
      _controller?.pause();
      _controller?.dispose();
    }
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    // ]);
    OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    if (width > height) {
      // SystemChrome.setPreferredOrientations([
      //   DeviceOrientation.portraitUp,
      // ]);
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    }

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: getTitle(),
      ),
      body: _hasData
          ? Stack(children: <Widget>[
              Container(
                  padding: EdgeInsets.only(
                      bottom: widget.type != "3"
                          ? ScreenUtil().setWidth(70)
                          : ScreenUtil().setWidth(10)),
                  child: ListView(children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        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(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "提问人",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(17)),
                                  textAlign: TextAlign.start,
                                ),
                                Row(
                                  children: <Widget>[
                                    Text(
                                      detailObj.name ?? "",
                                      style: TextStyle(
                                          color: Color(0xff666666),
                                          fontSize: ScreenUtil().setSp(15)),
                                      textAlign: TextAlign.start,
                                    ),
                                    Container(
                                      margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(10),
                                          right: ScreenUtil().setWidth(10),
                                          top: ScreenUtil().setWidth(5)),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(
                                            ScreenUtil().setWidth(25)),
                                      ),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                            ScreenUtil().setWidth(22)),
                                        child: LoadNetworkImage(
                                          detailObj.avatarUrl,
                                          width: ScreenUtil().setWidth(37),
                                          height: ScreenUtil().setWidth(37),
                                          // alignment: Alignment.centerLeft,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ]),
                        ),
                        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(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "电梯品牌",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(17)),
                                  textAlign: TextAlign.start,
                                ),
                                Text(
                                  detailObj.brandName ?? "",
                                  style: TextStyle(
                                      color: Color(0xff666666),
                                      fontSize: ScreenUtil().setSp(15)),
                                  textAlign: TextAlign.start,
                                ),
                              ]),
                        ),
                        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(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "出厂时间",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(17)),
                                  textAlign: TextAlign.start,
                                ),
                                Text(
                                  detailObj.productionDate ?? "",
                                  style: TextStyle(
                                      color: Color(0xff666666),
                                      fontSize: ScreenUtil().setSp(15)),
                                  textAlign: TextAlign.start,
                                ),
                              ]),
                        ),
                        detailObj.dataTable == 2
                            ? 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(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: <Widget>[
                                      Text(
                                        "出诊时间",
                                        style: TextStyle(
                                            fontSize: ScreenUtil().setSp(17)),
                                        textAlign: TextAlign.start,
                                      ),
                                      Text(
                                        detailObj.arrivedTime != null
                                            ? DateUtils.instance.getFormartData(
                                                timeSamp: detailObj.arrivedTime,
                                                format: "yyyy-MM-dd HH:mm")
                                            : "",
                                        style: TextStyle(
                                            color: Color(0xff666666),
                                            fontSize: ScreenUtil().setSp(15)),
                                        textAlign: TextAlign.start,
                                      ),
                                    ]),
                              )
                            : Container(child: null),
                        detailObj.dataTable == 2
                            ? 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(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        "出诊地点",
                                        style: TextStyle(
                                            fontSize: ScreenUtil().setSp(17)),
                                        textAlign: TextAlign.start,
                                      ),
                                      Container(
                                        width: width * 0.7,
                                        child: Text(
                                          detailObj.address != null
                                              ? detailObj.address.split(",")[0]
                                              : "",
                                          style: TextStyle(
                                              color: Color(0xff666666),
                                              fontSize: ScreenUtil().setSp(18)),
                                          textAlign: TextAlign.end,
                                        ),
                                      )
                                    ]),
                              )
                            : Container(child: null),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  top: ScreenUtil().setWidth(10),
                                  bottom: ScreenUtil().setWidth(5)),
                              child: Text(
                                "问题描述",
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(17),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  right: ScreenUtil().setWidth(15),
                                  bottom: ScreenUtil().setWidth(50)),
                              child: Text(
                                detailObj.expression ?? "",
                                style: TextStyle(
                                  color: Color(0xff666666),
                                  fontSize: ScreenUtil().setSp(15),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 6,
                          child: Container(
                              color:
                                  ThemeUtils.getDialogTextFieldColor(context)),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  top: ScreenUtil().setWidth(10),
                                  bottom: ScreenUtil().setWidth(5)),
                              child: Text(
                                "已尝试方法",
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(17),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  right: ScreenUtil().setWidth(15),
                                  bottom: ScreenUtil().setWidth(50)),
                              child: Text(
                                detailObj.usedMethods ?? "",
                                style: TextStyle(
                                  color: Color(0xff666666),
                                  fontSize: ScreenUtil().setSp(15),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        ),
                        detailObj.imgs != null && detailObj.imgs != ""
                            ? SizedBox(
                                height: 6,
                                child: Container(
                                    color: ThemeUtils.getDialogTextFieldColor(
                                        context)),
                              )
                            : Container(child: null),
                        detailObj.imgs != null && detailObj.imgs != ""
                            ? Container(
                                padding: EdgeInsets.all(15),
                                color: ThemeUtils.getTabsBg(context),
                                child: Wrap(
                                    spacing: 20,
                                    runSpacing: 15,
                                    children: List<Widget>.from(detailObj.imgs
                                        .split(",")
                                        .asMap()
                                        .keys
                                        .map((index) {
                                      return GestureDetector(
                                        onTap: () {
                                          Navigator.of(context).push(
                                            new FadeRoute(
                                              page: PhotoViewGalleryScreen(
                                                images: listPreview, //传入图片list
                                                index: index, //传入当前点击的图片的index
                                                // heroTag: img,//传入当前点击的图片的hero tag （可选）
                                              ),
                                            ),
                                          );
                                        },
                                        child: LoadNetworkImage(
                                          detailObj.imgs.split(",")[index],
                                          width: ScreenUtil().setWidth(100),
                                          height: ScreenUtil().setWidth(100),
                                          isWater: true,
                                          // alignment: Alignment.centerLeft,
                                        ),
                                      );
                                    }).toList())))
                            : Container(child: null),
                        detailObj.videoUrl != null && detailObj.videoUrl != ""
                            ? SizedBox(
                                height: 6,
                                child: Container(
                                    color: ThemeUtils.getDialogTextFieldColor(
                                        context)),
                              )
                            : Container(child: null),
                        detailObj.videoUrl != null && detailObj.videoUrl != ""
                            ? Container(
                                padding: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(15),
                                    right: ScreenUtil().setWidth(15),
                                    top: ScreenUtil().setWidth(15)),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(5),
                                  child: new Chewie(
                                    controller: ChewieController(
                                      videoPlayerController:
                                          // VideoPlayerController.network(
                                          //     imgFontUrl + detailObj.url
                                          //     ),
                                          _controller,
                                      aspectRatio: 3 / 2,
                                      autoPlay: false,
                                      looping: true,
                                      showControls: true,
                                      deviceOrientationsAfterFullScreen: [
                                        DeviceOrientation.portraitUp,
                                      ],
                                      // 占位图
                                      // placeholder: Image.network(
                                      //     imgFontUrl+detailObj.cover,
                                      //     fit: BoxFit.contain,

                                      //   ),

                                      // 是否在 UI 构建的时候就加载视频
                                      autoInitialize: true,

                                      // 拖动条样式颜色
                                      materialProgressColors:
                                          new ChewieProgressColors(
                                        playedColor: Colors.red,
                                        handleColor: Colors.blue,
                                        backgroundColor: Colors.grey,
                                        bufferedColor: Colors.lightGreen,
                                      ),
                                    ),
                                  ),
                                ))
                            : Container(child: null),
                      ],
                    ),
                  ])),
              Positioned(
                  bottom: 0,
                  left: 0,
                  child: widget.type != "3"
                      ? Container(
                          width: width,
                          child: Row(children: <Widget>[
                            Container(
                              height: ScreenUtil().setWidth(70),
                              width: width / 2,
                              color: Colors.white,
                              child: FlatButton(
                                // padding: EdgeInsets.all(15.0),
                                child: Text(
                                  "拒绝",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(16)),
                                ),
                                textColor: Color(0xff222222),
                                onPressed: () {
                                  // NavigatorUtils.push(context, BbsRouter.questionPay);
                                  orderRefuze();
                                },
                              ),
                            ),
                            Container(
                              height: ScreenUtil().setWidth(70),
                              width: width / 2,
                              color: Color(0xff0388FD),
                              child: FlatButton(
                                // padding: EdgeInsets.all(15.0),
                                child: Text(
                                  "接单",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(16)),
                                ),
                                textColor: Colors.white,
                                onPressed: () {
                                  // NavigatorUtils.push(context, BbsRouter.questionPay);
                                  orderReceiving();
                                },
                              ),
                            ),
                          ]))
                      : Container(child: null))
            ])
          : Center(
              child: Text("正在加载..."),
            ),
    );
  }
}

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