import 'dart:io';
import 'dart:convert';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/request.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jcs_airport/view/task/task_execution.dart';
import 'package:jcs_airport/view/task/utils/widget_behavior.dart';
import 'package:path_provider/path_provider.dart' as path_provider;

import '../../workBench/realTimeMonitoring/monitorVideo/video_page.dart';

class DynamicUpload extends StatefulWidget {
  final Map<String, dynamic> formData;
  final Map<String, dynamic> visualParams;
  final Map<String, dynamic> formValidator;
  final bool editable;

  const DynamicUpload({
    this.formData,
    this.visualParams,
    this.formValidator,
    this.editable,
  });

  @override
  State<StatefulWidget> createState() => _DynamicUploadState();
}

class _DynamicUploadState extends State<DynamicUpload> {
  List<File> files = [];
  Map<String, String> fileMap = {};
  String imagePrefix = '';

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((imagePrefix) {
      if (imagePrefix != null && imagePrefix.isNotEmpty) {
        setState(() {
          this.imagePrefix =
              imagePrefix.endsWith('/') ? imagePrefix : imagePrefix + '/';
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isHidden(widget.visualParams)) {
      return Container();
    }
    if (isReadonly(widget.visualParams)) {
      return Container(
        padding: const EdgeInsets.only(left: 15, right: 15, top: 5),
        child: Column(
          children: [
            Container(
                child: Text(widget.visualParams['label'] + ':'),
                alignment: Alignment.centerLeft),
          ],
        ),
      );
    }
    return Row(
      children: <Widget>[
        Container(
          height: 95,
          padding: EdgeInsets.only(top: 15.0),
          child: Text(
            widget.visualParams != null && widget.formValidator != null
                ? (widget.formValidator[widget.visualParams['fieldKey']] != null
                        ? widget.formValidator[widget.visualParams['fieldKey']]
                            ['required']
                        : false)
                    ? '*'
                    : ''
                : '',
            textAlign: TextAlign.left,
            //文字放大倍数
            textScaleFactor: 1.0,
            //文本最多显示几行
            maxLines: 1,
            style: TextStyle(color: Colors.red),
          ),
        ),
        Expanded(
          child: Container(
            padding: const EdgeInsets.only(left: 15, right: 15, top: 5),
            child: Column(
              children: [
                Container(
                    child: Text(widget.visualParams['label'] + ':'),
                    alignment: Alignment.centerLeft),
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: getImagesWidget(context, files),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  List<Widget> getImagesWidget(BuildContext context, List<File> imageList) {
    List<Widget> widgets = [];
    if (!widget.editable) {
      List<dynamic> imagePaths = [];

      if(widget.formData[widget.visualParams['fieldKey']] is String) {
        String uploadImagePropsString =
        widget.formData[widget.visualParams['fieldKey']];
        // json数组字符串解析
        if (uploadImagePropsString != null &&
            uploadImagePropsString.isNotEmpty &&
            uploadImagePropsString.startsWith('[') &&
            uploadImagePropsString.endsWith(']')) {
          List<dynamic> uploadImageProps = json.decode(uploadImagePropsString);
          imagePaths = uploadImageProps
              .map((uploadImageProp) => uploadImageProp['url'])
              .toList();
        }
      } else {
        if(!(widget.formData[widget.visualParams['fieldKey']] == null)) {
          List<dynamic> uploadImageProps = widget.formData[widget.visualParams['fieldKey']];
          imagePaths = uploadImageProps
              .map((uploadImageProp) => uploadImageProp['url'])
              .toList();
        }
      }
      // json数组字符串解析
      if (imagePaths.length > 0) {
        imagePaths.forEach((path) {
          path = removePrefix(path);
          List<String> vars = path.split('.');
          String fileType = '.' + vars[vars.length - 1];
          var pathurl = imagePrefix != '' ? imagePrefix + path : null;

          widgets.add(Stack(
            children: <Widget>[
              Container(
                  width: 110,
                  height: 70,
                  margin: const EdgeInsets.only(top: 15, left: 5),
                  child: GestureDetector(
                      child: fileType == '.jpg' || fileType == '.png'
                          ? pathurl != null
                              ? Image.network(pathurl)
                              : null
                          : PlayMonitorVideo(
                              url: pathurl,
                            ),
                      onDoubleTap: () {
                        if (fileType == '.jpg' || fileType == '.png') {
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                            return ImageView(Image.network(pathurl));
                          }));
                        } else {
                          // 视频
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                            return PlayMonitorVideo(
                              url: pathurl,
                            );
                          }));
                        }
                      },
                      onTap: () {
                        if (fileType == '.jpg' || fileType == '.png') {
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                            return ImageView(Image.network(pathurl));
                          }));
                        } else {
                          // // 视频
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                            return PlayMonitorVideo(
                              url: pathurl,
                            );
                          }));
                        }
                      })),
            ],
          ));
        });
      }
    }

    if (widget.editable) {
      imageList.forEach((image) {
        widgets.add(Stack(
          children: <Widget>[
            Container(
              width: 110,
              height: 70,
              margin: const EdgeInsets.only(top: 15, left: 5),
              child: GestureDetector(
                child:
                    image.path.substring(image.path.lastIndexOf('.')) == '.jpg'
                        ? Image.file(image)
                        : VideoViewSmallPage(image),
                onTap: () {
                  String fileType =
                      image.path.substring(image.path.lastIndexOf('.'));
                  if (fileType == '.jpg') {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) {
                      return ImageView(
                          Image.file(image, repeat: ImageRepeat.repeat));
                    }));
                  } else {
                    // 视频
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) {
                      return VideoViewPage(image);
                    }));
                  }
                },
              ),
            ),
            Positioned(
                right: 0.0,
                top: 0.0,
                left: 100,
                child: InkWell(
                    child: Icon(Icons.cancel,
                        color: Theme.of(context).disabledColor),
                    onTap: () {
                      setState(() {
                        imageList.remove(image);
                        fileMap.remove(image.path);
                        widget.formData[widget.visualParams['fieldKey']] =
                            urlsToUploadPropsString(
                                getPurePaths(fileMap.values.join(',')));
                      });
                    })),
          ],
        ));
      });
    }

    // 拍照按钮
    if (widget.editable && imageList.length < 3) {
      widgets.add(Container(
          width: 110,
          height: 70,
          margin: const EdgeInsets.only(top: 15, left: 10, bottom: 10),
          alignment: Alignment.bottomCenter,
          child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
                border: Border.all(color: Colors.grey[200], width: 0.5),
                // 边色与边宽度
                color: Colors.grey[200]),
            padding: const EdgeInsets.only(top: 10),
            child: Column(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    ImagePicker.pickImage(source: ImageSource.camera).then((c) {
                      if (c != null) {
                        setState(() {
                          imageList.insert(0, c);
                        });
                        uploadFile(c);
                      }
                    });
                  },
                  onLongPress: () {
                    ImagePicker.pickVideo(source: ImageSource.camera).then((f) {
                      if (f != null) {
                        setState(() {
                          imageList.insert(0, f);
                        });
                        uploadFile(f);
                      }
                    });
                  },
                  child: IconButton(
                    icon: Icon(
                      Icons.camera_alt,
                      size: 28,
                      color: GetConfig.getColor('blue'),
                    ),
                    onPressed: () {
                      ImagePicker.pickImage(source: ImageSource.camera)
                          .then((c) {
                        if (c != null) {
                          setState(() {
                            imageList.insert(0, c);
                          });
                        }
                        uploadFile(c);
                      });
                    },
                  ),
                )
              ],
            ),
          )));
    }
    return widgets;
  }

  Future<void> uploadFile(File file) async {
    if (file == null) {
      return;
    }
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '上传中...');
      File compressedFile = file;
      if (file.path.endsWith('.jpg')) {
        compressedFile = await imageCompressAndGetFile(file);
      }
      String name =
          file.path.substring(file.path.lastIndexOf('/') + 1, file.path.length);
      var image =
          await MultipartFile.fromFile(compressedFile.path, filename: name);
      var formData = FormData.fromMap({'files': image});
      // 使用 dio 上传图片
      var response = await HttpRequest.uploadImage(data: formData);

      Navigator.pop(context);

      String url = '';
      if (response['status'] == 200) {
        url = response['result']['url'];
      } else {
        TaskExecution.popUpMsg('文件上传失败！');
        return;
      }
      if (url == '') {
        TaskExecution.popUpMsg('文件上传失败！');
        return;
      }

      // 记录上传的文件
      fileMap[file.path] = url;
      List<dynamic>  list = [];
      List<dynamic> imageJson = widget.formData[widget.visualParams['fieldKey']];
      if (imageJson != null) {
        list = getImageUploadProps(imageJson, url);
      } else {
        list.add(urlToUploadProps(url));
      }

      setState(() {
        widget.formData[widget.visualParams['fieldKey']] = list;
      });
    });
  }

  /// 压缩图片
  Future<File> imageCompressAndGetFile(File file) async {
    if (file.lengthSync() < 200 * 1024) {
      return file;
    }
    var quality = 100;
    if (file.lengthSync() > 4 * 1024 * 1024) {
      quality = 50;
    } else if (file.lengthSync() > 2 * 1024 * 1024) {
      quality = 60;
    } else if (file.lengthSync() > 1 * 1024 * 1024) {
      quality = 70;
    } else if (file.lengthSync() > 0.5 * 1024 * 1024) {
      quality = 80;
    } else if (file.lengthSync() > 0.25 * 1024 * 1024) {
      quality = 90;
    }
    var dir = await path_provider.getTemporaryDirectory();
    var targetPath = dir.absolute.path +
        '/' +
        DateTime.now().millisecondsSinceEpoch.toString() +
        '.jpg';

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      minWidth: 600,
      quality: quality,
      rotate: 0,
    );

    return result;
  }

  String getPurePaths(String paths) {
    return paths
        .split(',')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty)
        .toSet()
        .join(',');
  }

  List<dynamic> getImageUploadProps(List<dynamic> uploadProps, String url) {
    if (url == null || url == '') {
      return [];
    } else {
      url = addPrefix(url);
      uploadProps.add(urlToUploadProps(url));
      return uploadProps;
    }
  }

  String urlsToUploadPropsString(String urls) {
    return json
        .encode(urls.split(',').map((e) => urlToUploadProps(e)).toList());
  }

  Map<String, String> urlToUploadProps(String url) {
    url = addPrefix(url);
    url = url.endsWith(',') ? url.substring(0, url.length - 1) : url;
    List<String> parts = url.split('/');
    String fileName = parts[parts.length - 1];
    String fileKey = fileName;
    if (fileName.contains('.')) {
      fileKey = fileName.substring(0, fileName.lastIndexOf('.'));
    }
    return {'uid': fileKey, 'url': url, 'name': fileName, 'status': 'done'};
  }

  // 添加url前缀：为了与后端业务保持一致，具体看业务变化
  String addPrefix(String url) {
    url = url.startsWith('/') ? url.substring(1) : url;
    return url.startsWith('/yeejoin/') ? url : '/yeejoin/' + url;
  }

  String removePrefix(String url) {
    return url.startsWith('/yeejoin/') ? url.substring(9) : url;
  }
}
