import 'dart:async';
import 'dart:math';

import 'package:chewie/chewie.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/bbs/model/video_detail.dart';
import 'package:liftmanager/internal/bbs/page/tab/question/question_pay.dart';
import 'package:liftmanager/internal/wode/wode_router.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/fast_notification.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:orientation/orientation.dart';
import 'package:video_player/video_player.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:liftmanager/internal/bbs/model/expert_model.dart'
    as ExportModel;

class VideoDetail extends StatefulWidget {
  VideoDetail(this.id);

  final String id;

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

class VideoDetailState extends State<VideoDetail> {
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 100), () {
      getVideoDetail();
    });
  }

  bool _hasData = false;
  VideoDetailModel detailObj;
  VideoPlayerController _controller;
  bool showBuyVipAd = false;
  bool allowFullScreen = false;

  void getUserInfo(Function(ExportModel.Records userInfo) onCompletion) {
    NewApiService().getExpertDetail(flustars.SpUtil.getString(Constant.userId),
        onSuccess: (res) {
      if (onCompletion != null) {
        onCompletion(res);
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getVideoDetail() async {
    await NewApiService().getVideoDetail(int.parse(widget.id), 1,
        onSuccess: (res) {
      if (res != null) {
        _hasData = true;
        detailObj = res;
        if (_controller == null) {
          _controller =
              VideoPlayerController.network(Utils.getImagePath(detailObj.url));

          var callback = () {
            if (_controller.value.isPlaying &&
                _controller.value.position >= Duration(minutes: 3)) {
              _controller.pause();
              setState(() {
                showBuyVipAd = true;
              });
            }
          };

          _controller.addListener(callback);

          getUserInfo((userInfo) {
            if (userInfo.vipFlag == 2) {
              if (_controller != null) {
                _controller.removeListener(callback);
              }
              setState(() {
                showBuyVipAd = false;
                allowFullScreen = true;
              });
            }
          });
        }

        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future changeLike(type) async {
    await NewApiService().videoLike(detailObj.id, type, 1, onSuccess: (res) {
      String textLike;
      if (type == 2) {
        textLike = "点赞";
      } else if (type == 3) {
        textLike = "收藏";
        initCollect();
      }
      toasts("$textLike成功");
      getVideoDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  showAlertEvent() {
    showAlert(
      context,
      "提示",
      "确定登录？",
      "确定",
      () {
        if (_controller != null) {
          _controller.pause();
        }
        NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
      },
      txt2: "取消",
      onPre2: () {
        NavigatorUtils.goBack(context);
      },
    );
  }

  Future cancelLike(type) async {
    var idChiose;
    String textLike;
    if (type == 2) {
      idChiose = detailObj.likeId;
      textLike = "点赞";
    } else if (type == 3) {
      idChiose = detailObj.favoriteId;
      textLike = "收藏";
    }
    await NewApiService().videoLikeCancel(idChiose, onSuccess: (res) {
      toasts("取消$textLike成功");
      if (type == 3) {
        initCollect();
      }
      getVideoDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  initCollect() {
    String collectInit = randomInt(1111, 9999).toString() +
        DateTime.now().millisecondsSinceEpoch.toString();
    FastNotification.push("collectAction", collectInit);
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  void dispose() {
    _controller?.pause();
    _controller?.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    print(width);
    print(height);
    if (width > height) {
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    }

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "电梯学堂",
      ),
      body: _hasData
          ? Stack(
              children: <Widget>[
                Container(
                  child: ListView(
                    children: <Widget>[
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                              padding: EdgeInsets.symmetric(horizontal: 10),
                              child: Stack(
                                children: [
                                  Chewie(
                                    controller: ChewieController(
                                      videoPlayerController: _controller,
                                      aspectRatio: 3 / 2,
                                      allowFullScreen: allowFullScreen,
                                      autoPlay: false,
                                      looping: true,
                                      // startAt: Duration(seconds: 1,minutes: 1),
                                      showControls: true,
                                      deviceOrientationsAfterFullScreen: [
                                        DeviceOrientation.portraitUp
                                      ],
                                      // 占位图
                                      // placeholder: Image.network(
                                      //     imgFontUrl+detailObj.cover,
                                      //     fit: BoxFit.contain,

                                      //   ),

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

                                      // 拖动条样式颜色
                                      materialProgressColors:
                                          new ChewieProgressColors(
                                        playedColor: Colors.blue,
                                        handleColor: Colors.blue,
                                        backgroundColor: Colors.transparent,
                                        bufferedColor: Colors.grey,
                                      ),
                                    ),
                                  ),
                                  if (showBuyVipAd)
                                    Container(
                                      width: width,
                                      height: 270,
                                      decoration: BoxDecoration(
                                        color: Color.fromARGB(200, 0, 0, 0),
                                        borderRadius: BorderRadius.circular(4),
                                      ),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '您的试看时间已用完，升级会员查看完整视频吧~',
                                            style: TextStyle(
                                              fontSize: 13,
                                              color: Color(0xffffffff),
                                            ),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          ),
                                          Stack(
                                            overflow: Overflow.visible,
                                            children: [
                                              GestureDetector(
                                                onTap: () {
                                                  NavigatorUtils.push(context,
                                                      '${WodeRouter.vip}?id=');
                                                },
                                                child: Container(
                                                  width: 50,
                                                  height: 50,
                                                  decoration: BoxDecoration(
                                                    gradient: LinearGradient(
                                                        colors: [
                                                          Color(0xffE6C8A0),
                                                          Color(0xffDCB885)
                                                        ]),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            25),
                                                  ),
                                                  child: Icon(
                                                    Iconfont.huiyuan101,
                                                    color: Colors.white,
                                                  ),
                                                ),
                                              ),
                                              Positioned(
                                                top: 0,
                                                left: 30,
                                                child: Container(
                                                  padding: EdgeInsets.all(2),
                                                  color: Color(0xffF95046),
                                                  child: Text(
                                                    '最低仅需40元/月',
                                                    style: TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 9),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: 10,
                                          ),
                                          Text(
                                            '成为会员无限看',
                                            style: TextStyle(
                                              fontSize: 13,
                                              color: Color(0xffffffff),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                ],
                              )),
                          Container(
                            width: width,
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            decoration: BoxDecoration(
                              border: Border(
                                bottom:
                                    BorderSide(width: 0.5, color: Colours.line),
                              ),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                SizedBox(
                                  height: 10,
                                ),
                                Container(
                                  width: width * 0.65,
                                  child: Text(
                                    detailObj.title ?? "",
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Color(0xff333333),
                                    ),
                                    textAlign: TextAlign.start,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                SizedBox(height: 10),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Container(
                                      padding: EdgeInsets.all(3),
                                      decoration: BoxDecoration(
                                        color: Color(0x33448EFA),
                                        borderRadius: BorderRadius.circular(3),
                                      ),
                                      child: Text(
                                        detailObj.brandName ?? "",
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: 11,
                                          color: Color(0xff5888FF),
                                        ),
                                      ),
                                    ),
                                    Text(
                                      "${detailObj.browseNum ?? "0"}浏览·${detailObj.likeNum ?? "0"}赞",
                                      style: TextStyle(
                                        color: Color(0xffcccccc),
                                        fontSize: 11,
                                      ),
                                      textAlign: TextAlign.start,
                                    ),
                                  ],
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                              ],
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 10, vertical: 10),
                            decoration: BoxDecoration(
                              border: Border(
                                bottom:
                                    BorderSide(width: 0.5, color: Colours.line),
                              ),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: <Widget>[
                                    Container(
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(16),
                                        child: LoadNetworkImage(
                                          detailObj.avatarUrl,
                                          // fit: BoxFit.cover,
                                          width: 32,
                                          height: 32,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    Text(
                                      detailObj.nickname ?? "",
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xff555A64)),
                                    ),
                                  ],
                                ),
                                SizedBox(
                                  height: 20,
                                ),
                                Text(
                                  '${detailObj.createTime != null ? DateUtils.instance.getFormartData(timeSamp: detailObj.createTime, format: "yyyy-MM-dd") : ""} 发布',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Color(0xff989898),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                decoration: BoxDecoration(
                                  border: Border(
                                    left: BorderSide(
                                        width: 2, color: Colors.blue),
                                  ),
                                ),
                                child: Text(
                                  "视频简介",
                                  style: TextStyle(
                                    fontSize: 15,
                                    color: Color(0xff333333),
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                child: Text(
                                  detailObj.descr ?? "",
                                  style: TextStyle(
                                    color: Color(0xff333333),
                                    fontSize: 13,
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                        width: width,
                        color: Colors.white,
                        child: Row(children: <Widget>[
                          Container(
                              height: 60,
                              width: width * .35,
                              color: Colors.white,
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(10),
                                  right: ScreenUtil().setWidth(10),
                                  top: ScreenUtil().setWidth(10)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: <Widget>[
                                  GestureDetector(
                                    onTap: () {
                                      if (FlutterStars.SpUtil.getString(
                                              Constant.userId) ==
                                          "-1") {
                                        showAlertEvent();
                                      } else {
                                        if (detailObj.isLike == 1) {
                                          cancelLike(2);
                                        } else {
                                          changeLike(2);
                                        }
                                      }
                                    },
                                    child: Container(
                                        child: Column(children: <Widget>[
                                      Icon(
                                        // : 0xe608,
                                        detailObj.isLike == 1
                                            ? Iconfont.dianzan
                                            : Iconfont.dianzan35,
                                        size: 20.0,
                                        color: detailObj.isLike == 1
                                            ? Color(0xff5589FF)
                                            : Color(0xff555A64),
                                      ),
                                      Text(
                                        detailObj.isLike == 1 ? "已点赞" : "点赞",
                                        style: TextStyle(
                                          color: Color(detailObj.isLike == 1
                                              ? 0xff5589FF
                                              : 0xff555A64),
                                          fontSize: 12,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                    ])),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      if (FlutterStars.SpUtil.getString(
                                              Constant.userId) ==
                                          "-1") {
                                        showAlertEvent();
                                      } else {
                                        if (detailObj.isFavorite == 1) {
                                          cancelLike(3);
                                        } else {
                                          changeLike(3);
                                        }
                                      }
                                    },
                                    child: Container(
                                        child: Column(children: <Widget>[
                                      Icon(
                                        //  : 0xe604,
                                        detailObj.isFavorite == 1
                                            ? const IconData(0xe62a,
                                                fontFamily: "Iconfont")
                                            : const IconData(0xe6b7,
                                                fontFamily: "Iconfont"),
                                        size: 20.0,
                                        color: Color(detailObj.isFavorite == 1
                                            ? 0xff5589FF
                                            : 0xff555A64),
                                      ),
                                      Text(
                                        detailObj.isFavorite == 1
                                            ? "已收藏"
                                            : "收藏",
                                        style: TextStyle(
                                          color: Color(detailObj.isFavorite == 1
                                              ? 0xff5589FF
                                              : 0xff555A64),
                                          fontSize: 12,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                    ])),
                                  )
                                ],
                              )),
                          Container(
                            width: width * 0.65,
                            height: 45,
                            padding: EdgeInsets.only(right: 10),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(40),
                              child: FlatButton(
                                color: Color(0xff5589FF),
                                child: Text(
                                  "打赏",
                                  style: TextStyle(
                                    fontSize: 16,
                                  ),
                                ),
                                textColor: Colors.white,
                                onPressed: () {
                                  if (FlutterStars.SpUtil.getString(
                                          Constant.userId) ==
                                      "-1") {
                                    showAlertEvent();
                                  } else {
                                    var nickname;
                                    if (detailObj.nickname != null) {
                                      nickname = Uri.encodeComponent(
                                          detailObj.nickname);
                                    }
                                    if (_controller != null) {
                                      _controller.pause();
                                    }

                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => QuestionPay(
                                                  detailObj.id.toString(),
                                                  "video",
                                                  detailObj.nickname,
                                                  detailObj.avatarUrl,
                                                  expert: detailObj.userId,
                                                )));

                                    // NavigatorUtils.push(context,
                                    //     "${BbsRouter.questionPay}?id=${detailObj.id}&videoModel-${detailObj.toJson()}&type=video&name=$nickname");
                                  }
                                },
                              ),
                            ),
                          ),
                        ])))
              ],
            )
          : Center(
              child: Text("正在加载..."),
            ),
    );
  }
}
