import 'dart:ui';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:dio/dio.dart';
import 'package:amos_iot_login_tpl/mine/offline/request.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:amos_flutter_ui/message/message_box.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:amos_flutter_ui/message/flutter_toast.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:camera_camera/page/video.dart';

import 'package:amos_flutter_utils/extension/int_extension.dart';
import 'image_button.dart';


class DialogUp extends StatelessWidget {
  final String batchNo;
  final String flag;
  final String category;
  final bool autofocus;

  const DialogUp(this.batchNo,this.flag,this.category, [this.autofocus = false]);
  // DialogUpState createState() => DialogUpState();

  @override
  Widget build(BuildContext context) {
      return DialogUpState(batchNo,flag,category,autofocus);
  }
}

class DialogUpState  extends StatefulWidget {
  final String batchNo;
  final String flag;
  final String category;
  final bool autofocus;
  const DialogUpState(this.batchNo,this.flag,this.category,this.autofocus);

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

class _DialogUpState extends State<DialogUpState> {
   final TextEditingController  _textcontroller = TextEditingController ();


  String init = 'false';
  List<Asset> images = [];
  List<File> imageList = [];
  String theme = 'blue';
   ///照片/视频
   List<ChooseFileInfo> files = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.category!="") {
      _textcontroller.text = "@回复" + widget.category;
    }

  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 20),
      decoration:
      ShapeDecoration(color: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px))),
      width: MediaQuery.of(context).size.width - 10.px,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children:  init == 'false' ? <Widget>[ buildTopBar(context)] : <Widget>[ buildTopBar(context), buildButton(context)],
      ),
    );
  }

  // 头部
  Widget buildTopBar(context) {
    return Container(
      height: 74,
      child: Stack(children: [
        Container(
            width: MediaQuery.of(context).size.width - 60.px,
            padding: EdgeInsets.symmetric(vertical: 10.px),
            decoration: ShapeDecoration(
              // color: const Color(0xFFefeff4),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(5.px), topRight: Radius.circular(5.px),
                        bottomLeft: Radius.circular(5.px)))),
            child:
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.px),
              child:  TextField(
                  autofocus: widget.autofocus,
                  textInputAction: TextInputAction.send,
                  decoration: const InputDecoration(border: InputBorder.none,
                      filled: true,
                      fillColor: Color.fromRGBO(244, 244, 244, 1)),
                  controller: _textcontroller ,
                  inputFormatters: [LengthLimitingTextInputFormatter(40)],
                  onSubmitted: (string) {
                    Map data = {
                      'batchNo':widget.batchNo,
                      'content':string,
                      'fileType': "text"
                    };
                    sendData(data);
                   // Navigator.of(context).pop();
                  }
              ),
            )
        ),
        Align(
            alignment: Alignment.centerRight,
            child: Container(
              padding: const EdgeInsets.only(right: 20),
              child: Button(
                //src: 'assets/icon/icon_close.svg',
                icon:Icons.add_circle_outline,
                //imageSize: 12.px,
                onPressed: () {
                  // Navigator.of(context).pop();
                  // if (cancel != null) {
                  //   cancel();
                  // }
                  if(init == 'true') {
                    setState(() {
                      init = 'false';
                    });
                  } else {
                    setState(() {
                      init = 'true';
                    });
                  }
                },
              ),
            ))
      ]),
    );
  }

  // 头部
  Widget buildButton(context) {
    return Container(
      height: 58,
      child: Stack(children: [
        Align(
          alignment: Alignment.centerLeft,
          child: Container(
            padding: const EdgeInsets.only(left: 20),
            child: InkWell(
                child: const Icon(Icons.image,
                    size: 32,
                    color: Colors.blue),
                onTap:  () async {
                  //Navigator.pop(context);
                  if(widget.flag == "true") {
                    Navigator.pop(context);
                  }
                  showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return buildImageAlertDialog(context);
                      });
                }),
          ),
        ),
        Align(
          alignment: Alignment.centerLeft,
          child: Container(
              padding: const EdgeInsets.only(left: 60, top: 5),
              child: InkWell(
                child: Column(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        //Navigator.pop(context);
                        if(widget.flag == "true") {
                          Navigator.pop(context);
                        }
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return buildVideoAlertDialog(context);
                            });
                      },
                      onLongPress: () {
                        print(2);
                      },
                      child: IconButton(
                        icon: Icon(
                          Icons.camera_alt,
                          size: 32,
                          color: Colors.blue,
                        ),
                      ),
                    )
                  ],
                ),
              )
          ),
        ),
      ]),
    );
  }

   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) {
               submitDocument(video);
             }
           },
         ),
         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) {
               submitDocument(file);
             }
           },
         )
       ],
     );
   }
   AlertDialog buildImageAlertDialog(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 image = await ImagePicker.pickImage(source: ImageSource.gallery);
             if (image != null) {
               // MsgBox.showProgressDialog(context, content: '提交中，请稍后...');
               submitDocument(image);
               // MsgBox.showConfirmDialog(context,(){
               //   setState(() {
               //     files.add(ChooseFileInfo(image, isPhoto: true));
               //   });
               // }, content: '是否提交该图片？');

             }
           },
         ),
         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(() {
             //   //   files.add(ChooseFileInfo(image, isPhoto: true));
             //   // });
             // }
              if (image != null) {
                // MsgBox.showProgressDialog(context, content: '提交中，请稍后...');
                submitDocument(image);
                // MsgBox.showConfirmDialog(context,(){
                //   setState(() {
                //     files.add(ChooseFileInfo(image, isPhoto: true));
                //   });
                // }, content: '是否提交该图片？');

              }
           },
         )
       ],
     );
   }

  ///上传文件
   Future<void> submitDocument(File file) async{
     File path = file;
     var name = file.path.substring(file.path.lastIndexOf('/') + 1, file.path.length);
     String imageType = name.substring(name.lastIndexOf('.') + 1, name.length);
     var image = await MultipartFile.fromFile(
       path.path,
       filename: name,
     );
     FormData formData = FormData.fromMap({'file': image});
     // 文件上传
     var fileUploadResult = await API.fileStorage(formData);
     Map data ={};
     fileUploadResult.forEach((v,k){
       print(';-----------------------');
       print(v);
       print(k);
       String fil = k.toString();
       print(fil.substring(fil.length-5,fil.length-1));
       if ('.jpg,.png,.jpeg,'.contains(fil.substring(fil.length-4,fil.length))) {
         data['fileType'] = 'image';
         data['filePath'] = v;
         data['batchNo'] = widget.batchNo;
       } else {
         data['fileType'] = 'video';
         data['batchNo'] = widget.batchNo;
         data['filePath'] = v;
       }
     });
     sendData(data);
   }


   Future<void> sendData(Map data) async{
    // MsgBox.showProgressDialog(context, content: '提交中，请稍后...');
    var result = await API.replyMessage(data);
    // Get.back();
    if(result != null){
      ToastUtils.showToast('提交成功！');
      _textcontroller.clear();
      if(widget.flag == "true") {
        Navigator.pop(context);
      }
    }else{
      ToastUtils.showToast('响应异常，提交失败！！');
    }
  }
}

/// 选择的文件封装，支持判断格式和播放视频
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});
}