import 'dart:async';
import 'dart:convert';
import 'dart:io';
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:flutter_spinkit/flutter_spinkit.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/bbs/model/video_detail.dart';
import 'package:liftmanager/internal/bbs/page/brand_page.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'package:liftmanager/utils/oss_upload.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/selected_video_change.dart';
import 'package:video_player/video_player.dart';

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

  final String id;

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

class VideoUploadState extends State<VideoUpload> {
  String brandName = "品牌";
  int brandIdss;

  String selectedBrandName = '';
  bool showBrandSelectionPanel = false;

  VideoDetailModel detailObj;
  VideoPlayerController _controller;
  VideoPlayerController _controllerFile;
  ChewieController _chewieController;
  String videoUrl;
  String str;
  String imagesUrl;
  double percent = 0.0;

  // 焦点控制
  FocusNode _focusNode1 = new FocusNode();
  GlobalKey _formKey = new GlobalKey<FormState>();
  TextEditingController _titleController = new TextEditingController();
  TextEditingController _descController = new TextEditingController();

  @override
  void initState() {
    super.initState();
    print(widget.id);

    if (widget.id != null && widget.id != "") {
      NewApiService().getVideoDetail(int.parse(widget.id), 1, onSuccess: (res) {
        if (res != null) {
          detailObj = res;

          LogUtil.d(jsonEncode(res));

          setState(() {
            videoUrl = null;
            videoUrl = res.url;
            _titleController.text = res.title;
            _descController.text = res.descr;
            brandIdss = res.brandId;
            selectedBrandName = res.brandName;
          });
        }
      }, onError: (code, msg) {
        toasts(msg);
      });
    }
  }

  upLoadFileOnce(path) {
    showLoading(context, "正在上传...");
    NewApiService().upload(path, onSuccess: (res) {
      // imagesUrl.add(res.path);
      dismissLoading(context);
      setState(() {
        // videoUrl = [];
        // imagesUrl = [];
        // videoUrl.add(res.pathUrl);
        // imagesUrl.add(res.coverUrl);
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

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

  List<dynamic> brandList;

  Future getBrandList() async {
    await NewApiService().getBrandListType(null, onSuccess: (res) {
      if (res != null) {
        brandList = res;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  ///选择视频
  void selectPicker() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
              title: Text("选择方式"),
              children: ["拍照", '从手机相册选择'].map((String value) {
                print("$value");
                return SimpleDialogOption(
                  child: Text(
                    "${value}",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                  ),
                  onPressed: () {
                    _getImage(value == '拍照' ? 1 : 0);
                    Navigator.of(context).pop();
                  },
                );
              }).toList());
        });
  }

  void _getImage(int key) async {
    print(key);
    try {
      await ImagePicker.pickVideo(
        source: key == 1 ? ImageSource.camera : ImageSource.gallery,
      ).then((File f) async {
        if (f != null) {
          _controllerFile = VideoPlayerController.file(f);
          _controllerFile.initialize().then((val) {
            _controllerFile.setLooping(true);
            int seconds = _controllerFile.value.duration.inSeconds;
            print("视频时长：$seconds");
            int fileSize = f.lengthSync(); //单位B
            print("视频大小：${fileSize}");
            print("视频大小：${f.path}");
            if (seconds <= 300) {
              _uploadImage(f.path);
              // upLoadFileOnce(_imageFile.path);
              // setState(() {});
            } else {
              toasts("视频时长不能大于5分钟！");
            }
          }).catchError((error) {
            print(error);
            print("error");
            toasts("上传失败,不支持此格式");
          });
        }
      });
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  void _uploadImage(filePath) async {
    showPercent(context, () {
      dismissLoading(context);
      toasts("上传失败");
    }, () {
      if (videoUrl == null && str != null) {
        setState(() {
          videoUrl = str;
          settingVideoVC();
          print("videoUrl:" + videoUrl);
          dismissLoading(context);
          toasts("上传成功");
        });
      }
    });
    String uploadName = OssUtil.instance.getImageUploadName(filePath);
    await NewApiService.uploadImage(context, uploadName, filePath).then((data) {
      if (data.statusCode == 200) {
        str = NewApiUrl.URL_UPLOAD_IMAGE_OSS + "/" + uploadName;
        print("str:" + str);
        print(videoUrl);
        if (str != null) {
          Map obj = {"uploadName": uploadName, "success": true};
          FastNotification.push("percent", obj);
        }
      } else {
        Map obj = {"uploadName": uploadName, "success": false};
        FastNotification.push("percent", obj);
      }
    }).catchError((data) {
      Map obj = {"uploadName": uploadName, "success": false};
      FastNotification.push("percent", obj);
    });
  }

  FocusNode focusNode1 = new FocusNode();

  settingVideoVC() {
    _controller?.pause();
    _controller?.dispose();
    _chewieController?.dispose();

    _controller = VideoPlayerController.network(Utils.getImagePath(videoUrl));
    _chewieController = ChewieController(
      videoPlayerController: _controller,
      aspectRatio: 3 / 2,
      allowFullScreen: false,
      isLive: true,
      autoPlay: false,
      looping: true,
      // startAt: Duration(seconds: 1,minutes: 1),
      showControls: true,
      deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
      // 是否在 UI 构建的时候就加载视频
      autoInitialize: true,

      // 拖动条样式颜色
      materialProgressColors: new ChewieProgressColors(
        playedColor: Colors.red,
        handleColor: Colors.blue,
        backgroundColor: Colors.grey,
        bufferedColor: Colors.lightGreen,
      ),
    );
  }

  @override
  void dispose() {
    _controller?.pause();
    _controller?.dispose();
    _chewieController?.dispose();
    // TODO: implement dispose
    super.dispose();
  }

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

    // 监听FocusNode
    _focusNode1.addListener(() {
      // _focusNode1.hasFocus 是否聚焦
      print(_focusNode1.hasFocus);
    });

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "上传视频",
      ),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(focusNode1);
        },
        child: Stack(
          children: <Widget>[
            Container(
                child: ListView(children: <Widget>[
              Form(
                key: _formKey, //设置globalKey，用于后面获取FormState
                child: Column(
                  children: <Widget>[
                    ChioseThisRight(
                        label: "电梯品牌",
                        value: selectedBrandName,
                        fun: () {
                          setState(() {
                            showBrandSelectionPanel = true;
                          });
                          getBrandList();
                        }),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin:
                              EdgeInsets.only(top: ScreenUtil().setWidth(13)),
                          height: 13,
                          width: 2,
                          color: Color(0xff5589FF),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                              left: ScreenUtil().setWidth(13),
                              top: ScreenUtil().setWidth(10),
                              bottom: ScreenUtil().setWidth(5)),
                          child: Text(
                            "视频标题",
                            style: TextStyle(
                              color: Color(0xff222222),
                              // fontSize:ScreenUtil().setSp(14),
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                    Container(
                      height: 80,
                      padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(15),
                          right: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(20)),
                      child: TextFormField(
                          // autofocus: true,
                          maxLength: 50,
                          cursorColor: Color(0xffcccccc),
                          controller: _titleController,
                          maxLines: 5,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(0),

                            hintText: '请输入你上传视频的标题',
                            hintStyle: TextStyle(color: Color(0xffcccccc)),
                            focusedBorder: InputBorder.none,
                            border: InputBorder.none,
                            // filled: true, // 背景色
                            // fillColor: Colors.cyan.withAlpha(35),
                            // icon: Icon(Icons.person)
                          ),

                          // 校验
                          validator: (val) {
                            return val.trim().length > 0 ? null : "不能为空";
                          }),
                    ),
                    Divider(),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin:
                              EdgeInsets.only(top: ScreenUtil().setWidth(13)),
                          height: 13,
                          width: 2,
                          color: Color(0xff5589FF),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                              left: ScreenUtil().setWidth(13),
                              top: ScreenUtil().setWidth(10),
                              bottom: ScreenUtil().setWidth(5)),
                          child: Text(
                            "视频简介",
                            style: TextStyle(
                              color: Color(0xff222222),
                              // fontSize:ScreenUtil().setSp(14),
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                    Container(
                      height: 120,
                      padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(15),
                          right: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(20)),
                      child: TextFormField(
                          // autofocus: true,
                          maxLength: 500,
                          cursorColor: Color(0xffcccccc),
                          controller: _descController,
                          maxLines: 5,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(0),

                            hintText: '请输入您上传视频的简介',
                            hintStyle: TextStyle(color: Color(0xffcccccc)),
                            focusedBorder: InputBorder.none,
                            border: InputBorder.none,
                            // filled: true, // 背景色
                            // fillColor: Colors.cyan.withAlpha(35),
                            // icon: Icon(Icons.person)
                          ),

                          // 校验
                          validator: (val) {
                            return val.trim().length > 0 ? null : "不能为空";
                          }),
                    ),
                    Divider(),
                    SizedBox(
                      height: 20,
                    ),
                    Container(
                        color: ThemeUtils.getTabsBg(context),
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Stack(
                              children: <Widget>[
                                Container(
                                  height: 150,
                                  width: 150,
                                  child: SelectedVideo(
                                    image: videoUrl,
                                    videoPlay: videoPlay(),
                                    onTap: () {
                                      if (videoUrl == null) {
                                        selectPicker();
                                      }
                                    },
                                  ),
                                ),
                                (videoUrl != null)
                                    ? Positioned(
                                        top: 0,
                                        right: 0,
                                        child: GestureDetector(
                                          onTap: () {
                                            // print(index);

                                            // imagesUrl = null;
                                            setState(() {
                                              videoUrl = null;
                                              str = null;
                                              _controller.pause();
                                              // player.reset();
                                            });
                                          },
                                          child: Icon(
                                            const IconData(0xe651,
                                                fontFamily: "Iconfont"),
                                            size: 24.0,
                                            color: Color(0xff999999),
                                          ),
                                        ))
                                    : Container()
                              ],
                            ),
                            Container(
                              padding: EdgeInsets.only(left: 10),
                              child: Text(
                                "(建议时长<3分钟，大小<50M)",
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(13),
                                    color: Color(0xffCCCCCC)),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        )),
                    SizedBox(
                      height: ScreenUtil().setWidth(80),
                    ),
                  ],
                ),
              )
            ])),
            Positioned(
                bottom: 0,
                left: 0,
                child: Container(
                  width: width,
                  padding: EdgeInsets.only(
                      top: ScreenUtil().setWidth(15),
                      bottom: ScreenUtil().setWidth(15),
                      left: ScreenUtil().setWidth(25),
                      right: ScreenUtil().setWidth(25)),
                  color: ThemeUtils.getDialogTextFieldColor(context),
                  child: Container(
                    height: ScreenUtil().setWidth(44),
                    decoration: BoxDecoration(
                      color: Colours.blue_app_main,
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(22)),
                      // gradient: const LinearGradient(
                      //     colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
                    ),
                    child: FlatButton(
                      // padding: EdgeInsets.all(15.0),
                      child: Text("确认上传"),
                      textColor: Colors.white,
                      onPressed: () {
                        if (brandIdss == null) {
                          toasts("请选择品牌");
                          return;
                        }
                        if (videoUrl == null) {
                          toasts("请上传视频");
                          return;
                        }
                        // String videos = videoUrl.join(",");
                        // String images = imagesUrl.join(",");
                        if ((_formKey.currentState as FormState).validate()) {
                          showLoading(context, "正在提交...");
                          if (widget.id != null && widget.id != "") {
                            dynamic objEdit = {
                              "brandId": brandIdss,
                              "title": _titleController.text,
                              "descr": _descController.text,
                              "url": videoUrl,
                              // "cover": images,
                              "checkFlag": 2,
                              "statuz": 1,
                              "platformFlag": 1,
                              "userId": FlutterStars.SpUtil.getString(
                                  Constant.userId),
                              "id": detailObj.id
                            };
                            NewApiService().editVideo(objEdit,
                                onSuccess: (res) {
                              dismissLoading(context);
                              toasts("修改成功");
                              String initThisMyVideo =
                                  randomInt(1111, 9999).toString() +
                                      DateTime.now()
                                          .millisecondsSinceEpoch
                                          .toString();
                              FastNotification.push(
                                  "initMyVideo", initThisMyVideo);
                              if (_controller != null) {
                                _controller.pause();
                              }
                              Navigator.of(context)..pop()..pop();
                            }, onError: (code, msg) {
                              dismissLoading(context);
                              toasts(msg);
                            });
                          } else {
                            dynamic obj = {
                              "brandId": brandIdss,
                              "title": _titleController.text,
                              "descr": _descController.text,
                              "url": videoUrl,
                              // "cover": images,
                              "checkFlag": 2,
                              "statuz": 1,
                              "platformFlag": 1,
                              "userId":
                                  FlutterStars.SpUtil.getString(Constant.userId)
                            };
                            NewApiService().addVideo(obj, onSuccess: (res) {
                              dismissLoading(context);
                              toasts("提交成功");
                              String initThisMyVideo =
                                  randomInt(1111, 9999).toString() +
                                      DateTime.now()
                                          .millisecondsSinceEpoch
                                          .toString();
                              FastNotification.push(
                                  "initMyVideo", initThisMyVideo);
                              if (_controller != null) {
                                _controller.pause();
                              }
                              Navigator.pop(context);
                            }, onError: (code, msg) {
                              dismissLoading(context);
                              toasts(msg);
                            });
                          }
                        }
                      },
                    ),
                  ),
                )),
            if (showBrandSelectionPanel)
              Positioned(
                top: 0,
                left: 0,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      showBrandSelectionPanel = false;
                    });
                  },
                  child: Container(
                    width: width,
                    height: height,
                    color: Color.fromRGBO(0, 0, 0, 0.5),
                  ),
                ),
              ),
            if (showBrandSelectionPanel)
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: width * 0.8,
                  height: height,
                  color: Colors.white,
                  child: brandList == null
                      ? loadCircle()
                      : BrandSelectionPanel(
                          brandList: brandList,
                          onTapBrand: (records) {
                            setState(() {
                              selectedBrandName = records.name;
                              brandIdss = records.id;
                              showBrandSelectionPanel = false;
                            });
                          },
                        ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget loadCircle() {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      color: ThemeUtils.getTabsBg(context),
      child: Center(
        child: SpinKitFadingCircle(
          color: Colors.blueAccent,
          size: 30.0,
        ),
      ),
    );
  }

  Widget videoPlay() {
    if (_controller == null) return Container();
    return Container(
        child: ClipRRect(
      borderRadius: BorderRadius.circular(5),
      child: new Chewie(controller: _chewieController),
    ));
  }
}

class ChioseThisRight extends StatelessWidget {
  ChioseThisRight({
    Key key,
    this.value,
    this.label,
    this.fun,
    this.labelText = '请选择',
    this.labelTextColor = const Color(0xffcccccc),
  }) : super(key: key);
  String value;
  String label;
  Function fun;
  String labelText;
  Color labelTextColor;

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return InkWell(
      onTap: () {
        fun();
      },
      child: Container(
        padding: EdgeInsets.only(
            top: ScreenUtil().setWidth(15), bottom: ScreenUtil().setWidth(15)),
        margin: EdgeInsets.only(left: ScreenUtil().setWidth(15)),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 0.5, color: Colours.line),
          ),
        ),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                label,
                style: TextStyle(
                  color: Color(0xff222222),
                  // fontSize: ScreenUtil().setSp(14)
                ),
                textAlign: TextAlign.start,
              ),
              value.isEmpty
                  ? Container(
                      child: Row(children: <Widget>[
                        Text(
                          labelText,
                          style: TextStyle(
                            color: labelTextColor,
                            // fontSize: ScreenUtil().setSp(14)
                          ),
                          textAlign: TextAlign.start,
                        ),
                        Container(
                          padding: EdgeInsets.only(top: 3),
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            size: 20.0,
                            color: labelTextColor,
                          ),
                        ),
                        SizedBox(width: 10)
                      ]),
                    )
                  : Container(
                      padding:
                          EdgeInsets.only(right: ScreenUtil().setWidth(15)),
                      child: Row(children: <Widget>[
                        Text(
                          value,
                          style: TextStyle(
                              color: labelTextColor,
                              fontSize: ScreenUtil().setSp(14)),
                          textAlign: TextAlign.start,
                        ),
                        Container(
                          padding: EdgeInsets.only(top: 3),
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            size: 20.0,
                            color: labelTextColor,
                          ),
                        ),
                        // SizedBox(width: 10)
                      ]),
                    ),
            ]),
      ),
    );
  }
}
