/*
 * @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/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<List<DirBean>> dirLive = LiveData();
  LiveData<String> titleData = LiveData();

  Map<String, List<ScanImageItem>> _mainValue = Map();
  List<String> _selectList = List();
  String _nowDirName = MainDir;
  StreamSubscription _listen;
  bool showCamera = true;
  int _maxCount = 1;

  get selectList => _selectList;

  get maxCount => _maxCount;

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

  bool showPop = false;
  bool isAndroid = Platform.isAndroid;
  List<DirBean> _dirList = List();

  get dirList => _dirList;

  AlbumModel(this.showCamera, int maxCount, List<String> selectedList) {
    this._maxCount = maxCount;
    if (selectedList != null && !selectedList.isEmpty) {
      this._selectList.clear();
      this._selectList.addAll(selectedList);
    }
  }

  void _onEvent(Object event) {
    var map = (event as Map);
//    var list = map[_nowDirName];
    _mainValue.forEach((k, itemList) {
      for (int i = 0; i < itemList.length; i++) {
        if (map[k] == null || map[k][i] == null) {
          continue;
        }
        var newPath = map[k][i]["path"] as String;
        if ((itemList[i].path == null || itemList[i].path.isEmpty) &&
            newPath != null) {
          itemList[i].path = newPath;
        }
      }
    });
//    var recordList=_mainValue[_nowDirName];
//    List<ScanImageItem> tempList = new List();
//    if (list != null && !list.isEmpty) {
////      for (int i = 0; i < albumLive.data.length; i++) {
////        if (list[i]["path"] != null) {
////          albumLive.data[i].path = list[i]["path"];
////        }
////      }
//      for (var item in list) {
//        ScanImageItem scanImageItem = new ScanImageItem();
//        scanImageItem.path = item["path"];
//        scanImageItem.size = item["size"];
//        scanImageItem.realPath = item["realPath"];
//        tempList.add(scanImageItem);
//      }
//    }
//    print("EVENTTTT  !! ${tempList.length}   ${tempList}");
    albumLive.notifyView(_mainValue[_nowDirName]);
  }

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

  void initScanImages(BuildContext context) {
    if (isAndroid) {
      _listen = GengmeiFlutterPlugin.phoneImagesEvent
          .receiveBroadcastStream()
          .listen(_onEvent, onError: _onError);
    }
    AlbumRepository.getInstance().scanPhoneImg().listen((value) {
      if (value != null) {
        _mainValue = value;
        value.forEach((key, eachValue) {
          print("VALUE!!!  $eachValue");
          if (eachValue != null && !eachValue.isEmpty) {
            if (key == MainDir) {
//              albumLive.notifyView(eachValue);
              titleData.notifyView(MainDirExplain);
              _dirList.add(DirBean(
                  MainDirExplain, eachValue.length, File(eachValue[0].path)));
            } 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();
    }
    albumLive.dispost();
    dirLive.dispost();
    titleData.dispost();
  }

  select(int index) {}

  bool isSelect(int index) {
    bool haveIt = false;
    if (_selectList.isEmpty) {
      return false;
    }
    _selectList.forEach((value) {
      if (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;
  }

  void clickItem(BuildContext context, int index) {
    String path;
    if (isAndroid) {
      path = albumLive.data[index].realPath;
    } else {
      path = albumLive.data[index].path;
    }

    if (!_selectList.contains(path)) {
      if (_selectList.length >= _maxCount) {
        Toast.show(context, "最多选择${_maxCount}张图片");
        return;
      }
      _selectList.add(path);
    } else {
      _selectList.remove(path);
    }
    albumLive.notifyView(albumLive.data);
  }

  void onNext(BuildContext context) {
    if (_selectList.isEmpty) {
      Navigator.pop(context, "");
    } else {
      Navigator.pop(context, _selectList[0]);
    }
  }

  void nativeCamera(BuildContext context) {
    if (_selectList.length == maxCount) {
      Toast.show(context, "最多选择${_maxCount}张图片");
      return;
    }
    AlbumRepository.getInstance().nativeCamera().listen((data) {
      print("DATTTTTT  ${data}");
      if (data == null || data.isEmpty || data == "") {
        Toast.show(context, "没有拍摄照片");
      } else {
        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(null);
    } 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;
    dirLive.notifyView(null);
    showPop = false;
    albumLive.notifyView(_mainValue[dirName]);
  }
}
