import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/selected_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:liftmanager/internal/bbs/model/video_detail.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:liftmanager/utils/utils.dart';
import 'dart:math';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/common/common.dart';
import 'package:flutter/services.dart';
import 'package:orientation/orientation.dart';

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();
    // getVideoDetail();
    Future.delayed(Duration(milliseconds: 100),(){
      getVideoDetail();
    });

    
  }

  bool _hasData = false;
  VideoDetailModel detailObj;
  // var _storageLikeId;
  // var _storageFavId;
  VideoPlayerController _controller;

  Future getVideoDetail() async {
    print("-/-/-/-////////////////////////-----------");
    await NewApiService().getVideoDetail(int.parse(widget.id), 1,
        onSuccess: (res) {
      if (res != null) {
        _hasData = true;
        detailObj = res;
        _controller = VideoPlayerController.network(
                                        Utils.getImagePath(detailObj.url) 
                                        // imgFontUrl + detailObj.url
                                        );
        // player.setDataSource(detailObj.url, autoPlay: false,showCover: true);
        // player.addListener(_fijkValueListener);
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future changeLike(type) async {
    await NewApiService().videoLike(detailObj.id, type, 1, onSuccess: (res) {
      // if (res != null) {
      //   // saveLikeId(res.id,type);

      // }
      String textLike;
      if (type == 2) {
        textLike = "点赞";
      } else if (type == 3) {
        textLike = "收藏";
        initCollect();
      }
      toasts("$textLike成功");
      getVideoDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

  Future cancelLike(type) async {
    // _storageFavId
    // _storageLikeId
    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();
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    // ]);
    // OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    // player.release();
    // player.removeListener(_fijkValueListener);
    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);
    print(12345678);
    if(width > height){
      // SystemChrome.setPreferredOrientations([
      //   DeviceOrientation.portraitUp,
      // ]);
      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.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,
                                allowFullScreen:true,
                                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.red,
                                  handleColor: Colors.blue,
                                  backgroundColor: Colors.grey,
                                  bufferedColor: Colors.lightGreen,
                                ),
                              ),
                            ),

                            
                            
                          )
                      ),
                      Container(
                        width: width,
                        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>[
                            Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                width: width*0.65,
                                child: Text(
                                detailObj.title??"",
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(16)),
                                textAlign: TextAlign.start,
                                maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                              ),
                              ),
                              Text(
                                detailObj.brandName??"",
                                style: TextStyle(
                                    color: Color(0xff666666),
                                    fontSize: ScreenUtil().setSp(14)),
                                textAlign: TextAlign.start,
                              ),
                            ]
                            ),
                            Row(
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${detailObj.likeNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe7cd,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width:15
                                        ),
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${detailObj.browseNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe610,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                            // Text(
                            //     detailObj.likeNum!=null?detailObj.likeNum.toString() + "赞":"0赞",
                            //     style: TextStyle(
                            //         color: Color(0xff999999),
                            //         fontSize: ScreenUtil().setSp(14)),
                            //     textAlign: TextAlign.start,
                            //   ),
                          ]
                        )
                      ),
                      Container(
                        padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            top: ScreenUtil().setWidth(30),
                            bottom: ScreenUtil().setWidth(30)),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(width: 0.5, color: Colours.line),
                          ),
                        ),
                        child: Row(
                          children: <Widget>[
                            Container(
                                child: ClipRRect(
                              borderRadius: BorderRadius.circular(
                                  ScreenUtil().setWidth(18)),
                              child: LoadNetworkImage(
                                detailObj.avatarUrl,
                                // fit: BoxFit.cover,
                                width: ScreenUtil().setWidth(36),
                                height: ScreenUtil().setWidth(36),
                              ),
                            )),
                            Container(
                              padding: EdgeInsets.only(left: 5),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    detailObj.nickname??"",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(14),
                                        color: Color(0xff666666)),
                                  ),
                                  Text(
                                    detailObj.createTime!=null?DateUtils.instance.getFormartData(
                                        timeSamp: detailObj.createTime,
                                        format: "yyyy-MM-dd"):"",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(12),
                                        color: Color(0xffaaaaaa)),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      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(16),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                right: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(90)),
                            child: Text(
                              detailObj.descr??"",
                              style: TextStyle(
                                color: Color(0xff666666),
                                fontSize: ScreenUtil().setSp(14),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ])),
                Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                        width: width,
                        child: Row(children: <Widget>[
                          Container(
                              height: 70,
                              width: width / 2,
                              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(
                                        IconData(
                                            detailObj.isLike == 1
                                                ? 0xe63c
                                                : 0xe608,
                                            fontFamily: "myfont"),
                                        size: 26.0,
                                        color: Color(detailObj.isLike == 1
                                            ? 0xff0388FD
                                            : 0xff333333),
                                      ),
                                      Text(
                                        detailObj.isLike == 1 ? "已点赞" : "点赞",
                                        style: TextStyle(
                                            color: Color(detailObj.isLike == 1
                                                ? 0xff0388FD
                                                : 0xff000000),
                                            fontSize: ScreenUtil().setSp(14)),
                                        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(
                                        IconData(
                                            detailObj.isFavorite == 1
                                                ? 0xe654
                                                : 0xe604,
                                            fontFamily: "myfont"),
                                        size: 26.0,
                                        color: Color(detailObj.isFavorite == 1
                                            ? 0xff0388FD
                                            : 0xff333333),
                                      ),
                                      Text(
                                        detailObj.isFavorite == 1
                                            ? "已收藏"
                                            : "收藏",
                                        style: TextStyle(
                                            color: Color(
                                                detailObj.isFavorite == 1
                                                    ? 0xff0388FD
                                                    : 0xff000000),
                                            fontSize: ScreenUtil().setSp(14)),
                                        textAlign: TextAlign.start,
                                      ),
                                    ])),
                                  )
                                ],
                              )),
                          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: () {
                                if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                        showAlertEvent();
                                      }else {
                                        var nickname;
                                        if(detailObj.nickname!=null){
                                          nickname = Uri.encodeComponent(detailObj.nickname);
                                        }
                                        NavigatorUtils.push(
                                            context, "${BbsRouter.questionPay}?id=${detailObj.id}&type=video&name=$nickname");
                                      }
                                
                              },
                            ),
                          ),
                        ])))
              ],
            )
          : Center(
              child: Text("正在加载..."),
            ),
    );
  }
}
