import 'dart:io';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jcs_airport/view/common/image_swiper_page.dart';
import 'package:camera_camera/camera_camera.dart';
import 'package:video_player/video_player.dart';

/// 参数files为final修饰的引用类型，所以可以直接修改入参的原始数据，不必通过路由的返回值接收选择的图片或视频
class ImagePickerAndRemove extends StatefulWidget {
  final List<ChooseFileInfo> files;
  final bool readOnly;
  final int maxLength;
  final bool hasVideo;
  final bool isPhotoLlbum;

  const ImagePickerAndRemove(this.files, {this.readOnly = false, this.maxLength = 3, this.hasVideo = false, this.isPhotoLlbum = true});

  @override
  _ImagePickerAndRemoveState createState() => _ImagePickerAndRemoveState();
}

class _ImagePickerAndRemoveState extends State<ImagePickerAndRemove> with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
          Row(
              children: widget.files
                  .asMap()
                  .map((index, chooseFileInfo) => MapEntry(
                  index,
                  Stack(
                    children: [
                      InkWell(
                        child: Padding(
                          padding: const EdgeInsets.only(right: 10),
                          child: chooseFileInfo.isVideo
                              ? Container(
                              width: 60,
                              height: 60,
                              child: AspectRatio(
                                  aspectRatio: 1, child: VideoPlayer(chooseFileInfo.videoPlayerController)))
                              : chooseFileInfo.url == null
                              ? Image.file(
                            chooseFileInfo.file,
                            width: 60,
                            height: 60,
                          )
                              : Image.network(
                            chooseFileInfo.url,
                            errorBuilder: (context, error, stackTrace) {
                              return Image.asset(
                                'assets/default_picture.png',
                                width: 50,
                                height: 50,
                              );
                            },
                            width: 60,
                            height: 60,
                          ),
                        ),
                        onTap: () {
                          Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
                            return ImageSwiperPage(widget.files, index: index);
                            //return PlayVideo(chooseFileInfo.file);
                          }));
                        },
                      ),
                      widget.readOnly
                          ? Container()
                          : Positioned(
                        right: 10,
                        top: 1,
                        child: InkWell(
                          child: const Icon(
                            Icons.remove_circle_outline_outlined,
                            color: Colors.red,
                            size: 16,
                          ),
                          onTap: () {
                            setState(() {
                              widget.files.removeAt(index);
                            });
                          },
                        ),
                      )
                    ],
                  )))
                  .values
                  .toList()),
          (widget.readOnly || (widget.files.length == widget.maxLength))
              ? Container()
              : InkWell(
            child: Transform.scale(
              scale: 1.3,
              child: Image.asset(
                'assets/images/photo_add.png',
                width: 70,
                height: 70,
              ),
            ),
            onTap: () async {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return widget.hasVideo
                        ? AlertDialog(
                      title: const Text(
                        '提示',
                        style: TextStyle(fontSize: 15),
                      ),
                      content: const Text(
                        '请选择类型',
                        style: TextStyle(fontSize: 14),
                      ),
                      actions: <Widget>[
                        FlatButton(
                          child: const Text(
                            '照片',
                            style: TextStyle(fontSize: 14),
                          ),
                          onPressed: () async {
                            Navigator.pop(context);
                            showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  return buildImageAlertDialog(context);
                                });
                          },
                        ),
                        FlatButton(
                          child: const Text(
                            '视频',
                            style: TextStyle(fontSize: 14),
                          ),
                          onPressed: () async {
                            Navigator.pop(context);
                            showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  return buildVideoAlertDialog(context);
                                });
                          },
                        )
                      ],
                    )
                        : buildImageAlertDialog(context);
                  });
            },
          ),
        ],
      ),
    );
  }

  AlertDialog buildVideoAlertDialog(BuildContext context) {
    return AlertDialog(
      title: const Text(
        '提示',
        style: TextStyle(fontSize: 15),
      ),
      content: const Text(
        '请选择视频来源',
        style: TextStyle(fontSize: 14),
      ),
      actions: <Widget>[
         FlatButton(
          child: const Text(
            '相册',
            style: TextStyle(fontSize: 14),
          ),
          onPressed: () async {
            Navigator.pop(context);
            var video = await ImagePicker.pickVideo(source: ImageSource.gallery);
            if (video != null) {
              setState(() {
                VideoPlayerController _controller = VideoPlayerController.file(video)..initialize();
                ChewieController _chewieController = ChewieController(
                  videoPlayerController: _controller,
                  autoPlay: true,
                  looping: true,
                );
                widget.files.add(ChooseFileInfo(video,
                    isVideo: true, videoPlayerController: _controller, chewieController: _chewieController));
              });
            }
          },
        ),
        FlatButton(
          child: const Text(
            '拍摄',
            style: TextStyle(fontSize: 14),
          ),
          onPressed: () async {
            Navigator.pop(context);
            File file = await Get.to(Video());
            //var video = await ImagePicker.pickVideo(source: ImageSource.camera);
            //final AssetEntity entity = await CameraPicker.pickFromCamera(context);
            //File video = await entity.file;
            if (file != null) {
              setState(() {
                VideoPlayerController _controller = VideoPlayerController.file(file)..initialize();
                ChewieController _chewieController = ChewieController(
                  videoPlayerController: _controller,
                  autoPlay: true,
                  looping: false,
                );
                widget.files.add(ChooseFileInfo(file,
                    isVideo: true, videoPlayerController: _controller, chewieController: _chewieController));
              });
            }
          },
        )
      ],
    );
  }

  AlertDialog buildImageAlertDialog(BuildContext context) {
    return AlertDialog(
      title: const Text(
        '提示',
        style: TextStyle(fontSize: 15),
      ),
      content: const Text(
        '请选择照片来源',
        style: TextStyle(fontSize: 14),
      ),
      actions: <Widget>[
        widget.isPhotoLlbum? FlatButton(
          child: const Text(
            '相册',
            style: TextStyle(fontSize: 14),
          ),
          onPressed: () async {
            Navigator.pop(context);
            var image = await ImagePicker.pickImage(source: ImageSource.gallery);
            if (image != null) {
                setState(() {
                  widget.files.add(ChooseFileInfo(image, isPhoto: true));
                });
            }
          },
        ):null,
        FlatButton(
          child: const Text(
            '拍照',
            style: TextStyle(fontSize: 14),
          ),
          onPressed: () async {
            Navigator.pop(context);
            var image = await ImagePicker.pickImage(source: ImageSource.camera);
            if (image != null) {
              setState(() {
                widget.files.add(ChooseFileInfo(image, isPhoto: true));
              });
            }
          },
        )
      ],
    );
  }
}

/// 选择的文件封装，支持判断格式和播放视频
class ChooseFileInfo {
  File file;
  String url;
  bool isPhoto;
  bool isVideo;
  VideoPlayerController videoPlayerController;
  ChewieController chewieController;
  String fileName;
  String fileUrl;
  ChooseFileInfo(this.file,
      {this.isPhoto = false, this.isVideo = false, this.videoPlayerController, this.chewieController, this.url,this.fileName,this.fileUrl});
}
