import 'dart:convert' show json;
import 'dart:convert';
import 'dart:io';

import 'package:image/image.dart' as img;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

///获取维保路径
localPath() async {
  try {
    var appDocDir = await getApplicationDocumentsDirectory();
    Directory dir = Directory(appDocDir.path + "/maintenance");
    if (!dir.existsSync()) {
      dir.createSync();
    }
    print("缓存路径：${dir.path}");
    return dir.path;
  } catch (err) {
    print(err);
  }
}
///json文件
localFile(path, name) async {
  return new File('$path/$name.json');
}

/// 读取 json 数据
Future<Map<String, dynamic>>readJSON(name) async {
  try {
    final file = await localFile(await localPath(), name);
    String str = await file.readAsString();
    return json.decode(str);
  } catch (err) {
    print(err);
  }
}

/// 写入 json 数据
Future<bool> writeJSON(name, obj) async {
  try {
    final file = await localFile(await localPath(), name);
    await file.writeAsString(json.encode(obj));
    return true;

//    return file.writeAsString(json.encode(obj));
  } catch (err) {
    return false;
  }
}

///删除名为name的json文件
deleteJSON(name) async {
  try {
    final file = await localFile(await localPath(), name);
    return file.deleteSync();
  } catch (err) {
    print(err);
  }
}
///清除所有json文件
clearJSON()async {
  try {
    Directory path = Directory(await localPath());
    List files = path.listSync();
    for(var i=0;i<files.length;i++){
      File file = files[i];
      file.deleteSync();
    }
    return true;
  } catch (err) {
    print(err);
  }
}

///image保存临时文件夹下
saveCacheImageFile( imageByte,name,{fileName="signImg"}) async{
  final image = img.decodeImage(imageByte);
  Directory appDocDir = await getApplicationDocumentsDirectory();
  Directory tempDir = await getTemporaryDirectory();
  String tempPath = tempDir.path; // 临时文件夹
  Directory dir = Directory(tempPath + "/$fileName");
  if (!dir.existsSync()) {
    dir.createSync();
  }
//  String appDocPath = appDocDir.path; // 应用文件夹

  final imageFile = File(path.join(dir.path, '${name}.png')); // 保存在应用文件夹内
  await imageFile.writeAsBytes(img.encodePng(image)); // 需要使用与图片格式对应的encode方法
  return imageFile.path;
}

Future<int> getCacheSize() async{
  int size = 0;
  Directory tempDir = await getTemporaryDirectory();
  String tempPath = tempDir.parent.path; // 临时文件夹
  Directory dir = Directory(tempPath + "/app_flutter/maintenance");
  print(dir);
  if(!dir.existsSync())return 0;
  List<FileSystemEntity> list = dir.listSync();
  for(int i=0;i<list.length;i++){
    size += File(list[i].path).lengthSync();
  }
  return size;
}

clearCache() async{
  Directory tempDir = await getTemporaryDirectory();
  String tempPath = tempDir.parent.path; // 临时文件夹
  Directory dir = Directory(tempPath + "/app_flutter/maintenance");
  List<FileSystemEntity> list = dir.listSync();
  for(int i=0;i<list.length;i++){
    File(list[i].path).deleteSync();
  }
}