/*
 * @author lsy
 * @date   2019-09-09
 **/

import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:gengmei_flutter_plugin/ScanImagePlugn.dart';
import 'package:gengmei_flutter_plugin/gengmei_flutter_plugin.dart';
import 'package:gmalpha_flutter/AlbumModel/bean/DirBean.dart';
import 'package:gmalpha_flutter/AlbumModel/repository/AlbumRepository.dart';
import 'package:gmalpha_flutter/commonModel/GMBase.dart';
import 'package:gmalpha_flutter/commonModel/live/BaseModel.dart';
import 'package:gmalpha_flutter/commonModel/live/LiveData.dart';
import 'package:gmalpha_flutter/commonModel/toast/toast.dart';

const String MainDir = "IsGengmeiAlbumAllImages";
const String MainDirExplain = "全部相片";

class AlbumModel extends BaseModel {
  LiveData<List<ScanImageItem>> albumLive = LiveData();
  LiveData<int> selectSizeLive = LiveData();
  LiveData<List<DirBean>> dirLive = LiveData();
  LiveData<String> titleData = LiveData();

  LiveData<int> backLive = LiveData();

  Map<String, List<ScanImageItem>> _mainValue = Map();
  List<String> _selectList = List();
  List<String> _selectVideoList = List();
  String _nowDirName = MainDir;
  StreamSubscription _listen;
  bool showCamera = true;
  final String provider;

  int _maxCount = 1;

  get selectList => _selectList;

  get maxCount => _maxCount;

  get nowDirName {
    if (_nowDirName == MainDir) {
      return MainDirExplain;
    } else {
      return _nowDirName;
    }
  }

  bool showPop = false;
  List<DirBean> _dirList = List();
  final bool fromNative;
  int maxVideoCount;
  final String fromPage;
  final String iosPushedPage;

  get dirList => _dirList;

  AlbumModel(
      this.provider,
      this.showCamera,
      int maxCount,
      List<String> selectedList,
      this.fromNative,
      int maxVideoCount,
      List<String> videoSelectPath,
      this.fromPage,
      this.iosPushedPage) {
    print("======>>>>>${selectedList}  ${videoSelectPath} <<<<<=====");
    this.maxVideoCount = maxVideoCount;
    this._maxCount = maxCount;
    if (selectedList != null && !selectedList.isEmpty) {
      this._selectList.clear();
      this._selectList.addAll(selectedList);
    }
    if (videoSelectPath != null && !videoSelectPath.isEmpty) {
      this._selectVideoList.clear();
      this._selectVideoList.addAll(videoSelectPath);
    }
  }

  void _onEvent(Object event) {
    var map = (event as Map);
    if (_mainValue == null || _mainValue.length == 0) {
      _mainValue = map;
    } else {
      _mainValue.forEach((k, itemList) {
        var key = map[k];
        if (key != null) {
          for (int i = 0; i < itemList.length; i++) {
            if (key[i] == null) {
              continue;
            }
            itemList[i].path = key[i]["path"];
            itemList[i].realPath = key[i]["realPath"];
          }
        }
      });
    }
    albumLive.notifyView(_mainValue[_nowDirName]);
  }

  void _onError(Object error) {
    print("ERROR $error");
  }

  void initScanImages(BuildContext context) {
    if (Platform.isAndroid) {
      _listen = GengmeiFlutterPlugin.phoneImagesEvent
          .receiveBroadcastStream()
          .listen(_onEvent, onError: _onError);
    }
    AlbumRepository.getInstance().scanPhoneImg().listen((value) {
      if (value != null) {
        _mainValue = value;
        selectSizeLive.notifyView(_selectList.length + _selectVideoList.length);
        value.forEach((key, eachValue) {
          if (eachValue != null && !eachValue.isEmpty) {
            if (key == MainDir) {
              titleData.notifyView(MainDirExplain);
              _dirList.add(DirBean(
                  MainDirExplain, eachValue.length, File(eachValue[0].path)));
              albumLive.notifyView(eachValue);
            } else {
              _dirList
                  .add(DirBean(key, eachValue.length, File(eachValue[0].path)));
            }
          }
        });
      }
    }).onError((error) {
      Toast.show(context, error.toString());
      print(error);
    });
  }

  void changDir() {}

  @override
  void dispose() {
    if (_listen != null) {
      _listen.cancel();
    }
    selectSizeLive.dispost();
    backLive.dispost();
    albumLive.dispost();
    dirLive.dispost();
    titleData.dispost();
    GengmeiFlutterPlugin.quitPage();
  }

  bool isSelect(int index) {
    bool haveIt = false;
    if (_selectList.isEmpty) {
      return false;
    }
    _selectList.forEach((value) {
      if (Platform.isAndroid) {
        if (value == albumLive.data[index].realPath) {
          haveIt = true;
        }
      } else {
        if (value == albumLive.data[index].path) {
          haveIt = true;
        }
      }
    });

    return haveIt;
  }

  bool isSelectVideo(int index) {
    bool haveIt = false;
    if (_selectVideoList.isEmpty) {
      return false;
    }
    _selectVideoList.forEach((value) {
      if (Platform.isAndroid) {
        if (value == albumLive.data[index].realPath) {
          haveIt = true;
        }
      } else {
        if (value == albumLive.data[index].path) {
          haveIt = true;
        }
      }
    });
    return haveIt;
  }

  bool isFullSelect() {
    return _selectList.length == _maxCount;
  }

  bool isFullSelectVideo() {
    return _selectVideoList.length == maxVideoCount;
  }

  bool isVideo(int index) {
    return albumLive.data[index].isVideo;
  }

  void clickItem(BuildContext context, int index) {
    String path;
    if (Platform.isAndroid) {
      path = albumLive.data[index].realPath;
    } else {
      path = albumLive.data[index].path;
    }
    if (maxVideoCount > 0 && albumLive.data[index].isVideo) {
      if (!_selectVideoList.contains(path)) {
        if (_selectVideoList.length >= maxVideoCount) {
          Toast.show(context, "最多选择${maxVideoCount}个视频");
          return;
        }
        _selectVideoList.add(path);
      } else {
        _selectVideoList.remove(path);
      }
    } else {
      if (!_selectList.contains(path)) {
        if (_selectList.length >= _maxCount) {
          Toast.show(context, "最多选择${_maxCount}张图片");
          return;
        }
        _selectList.add(path);
      } else {
        _selectList.remove(path);
      }
    }
    albumLive.notifyView(albumLive.data);
    selectSizeLive.notifyView(_selectList.length + _selectVideoList.length);
  }

  void onNext(BuildContext context) {
    if (_selectList.isEmpty && _selectVideoList.isEmpty) {
      Navigator.pop(context, null);
    } else {
      if (fromNative) {
        if (Platform.isAndroid) {
          albumResult({"image": _selectList, "video": _selectVideoList});
        } else {
          iosAlbum(_selectList, context, (image) {
            iosAlbum(_selectVideoList, context, (video) {
              var newImages = List<String>();
              for (String item in _selectList) {
                for (Map real in image) {
                  var map = Map<String, String>.from(real);
                  if (map["path"] == item) {
                    newImages.add(map["realImagePath"]);
                    break;
                  }
                }
              }
              var newVideos = List<String>();
              for (String item in _selectVideoList) {
                for (Map real in video) {
                  var map = Map<String, String>.from(real);
                  if (map["path"] == item) {
                    newVideos.add(map["realVideoPath"]);
                    break;
                  }
                }
              }
              print("IM ${newImages} $image   VIDEI ${newVideos} ${video}");
              Navigator.pop(context);
              albumResult({
                "image": _selectList,
                "image_real": newImages,
                "video": _selectVideoList,
                "video_real": newVideos,
                "iosPushedPage": iosPushedPage
              });
            });
          });
        }
      } else {
        if (Platform.isAndroid) {
          Navigator.pop(context, _selectList);
        } else {
          iosAlbum(_selectList, context, (value) {
            print(value);
            List<String> resultList = new List();
            resultList.add(Map<String, String>.from(value[0])["realImagePath"]);
            Navigator.pop(context, resultList);
          });
        }
      }
    }
  }

  void iosAlbum(List<String> list, BuildContext context, Function fun) {
    GengmeiFlutterPlugin.ios_album_path(list).then((value) {
      if (value != null) {
        fun(List<Map>.from(value));
      }
    }).catchError((error) {
      print(error);
    });
  }

  void iosAlbumGetImagePath(String path, int index) {}

  void nativeCamera(BuildContext context) {
    if (_selectList.length == maxCount) {
      Toast.show(context, "最多选择${_maxCount}张图片");
      return;
    }
    AlbumRepository.getInstance().nativeCamera(provider).listen((data) {
      if (data == null) {
        Toast.show(context, "没有拍摄照片");
      } else {
        ScanImageItem item = new ScanImageItem();
        item.realPath = data["realPath"] as String;
        item.path = data["path"] as String;
        item.isVideo = false;
        String foldName = data["folderName"] as String;
        var list = _mainValue[foldName];
        if (list == null) {
          _mainValue[foldName] = new List();
          _mainValue[foldName].add(item);
        } else {
          list.insert(0, item);
        }
        _mainValue[MainDir].insert(0, item);
        _selectList.add(item.realPath);
        bool haveIt = false;
        _dirList.forEach((it) {
          if (it.dirName == foldName) {
            haveIt = true;
            it.picCount++;
          }
        });
        if (!haveIt) {
          _dirList.add(new DirBean(foldName, 1, File(item.path)));
        }
        dirLive.notifyView(_dirList);
        albumLive.notifyView(_mainValue[_nowDirName]);
        selectSizeLive.notifyView(_selectList.length + _selectVideoList.length);
//        Navigator.pop(context, data);
//        _selectList.add(data);
        //TODO
      }
    }).onError((error) {
      Toast.show(context, error);
      print(error);
    });
  }

  void AiCamera(BuildContext context) {
    if (_selectList.length == maxCount) {
      Toast.show(context, "最多选择${_maxCount}张图片");
      return;
    }
    AlbumRepository.getInstance().aiCamera().listen((data) {
      if (data == null || data.isEmpty || data == "") {
        Toast.show(context, "没有拍摄照片");
      } else {
        Navigator.pop(context, data);
//        _selectList.add(data);
        //TODO
      }
    }).onError((error) {});
  }

  File getDirPic(int index) {
    return File(_mainValue[_dirList[index]][0].path);
  }

  void changPopState() {
    if (showPop) {
      showPop = false;
      dirLive.notifyView(_dirList);
    } else {
      showPop = true;
      dirLive.notifyView(_dirList);
    }
    titleData.notifyView(nowDirName);
  }

  void selectDir(int index) {
    String dirName = _dirList[index].dirName;
    titleData.notifyView(dirName);
    if (dirName == MainDirExplain) {
      dirName = MainDir;
    }
    _nowDirName = dirName;
    changPopState();
    showPop = false;
    albumLive.notifyView(_mainValue[dirName]);
  }

  void backAnim(double dy) {
    if (dy < 0.2) {
      backLive.notifyView(null);
      return;
    }
    String alp = "${(dy.abs() * (99)).toInt()}";
    if (alp.length == 1) {
      alp = "0$alp";
    }
    String colorString = "0x${alp}000000";
    print(colorString);
    backLive.notifyView(int.parse(colorString));
  }

  String getFormatTime(String during) {
    if (during == null) {
      return "";
    } else {
      if (Platform.isIOS) {
        return during;
      }
      try {
        var parse = int.parse(during);
        String min;
        int minn;
        if (parse > 60 * 1000) {
          min = "00";
          minn = 0;
        } else {
          minn = (parse / (60 * 1000)).floor();
          min = "${minn}";
        }
        String second = "${((parse - minn * (60 * 1000)) / 1000).floor()}";

        if (min.length == 1) {
          min = "0$min";
        }
        if (second.length == 1) {
          second = "0$second";
        }
        if (min.length > 2) {
          min = "99";
        }
        return "$min:$second";
      } catch (e) {
        print(e);
        return "";
      }
    }
  }
}
