//JSON数据写入文件、从文件中读取
import 'dart:convert';
import 'dart:io';

import 'package:intl/intl.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

//控制字段处理数据类
class ItemData {
  ItemData({
    this.fieldName,
    this.fieldText,
    this.fieldVisible,
    this.fieldModifiable,
    this.fieldUrlVisible,
  }) {}
  String fieldName = '';
  String fieldText = '';
  bool fieldVisible = true;
  bool fieldUrlVisible = true;
  bool fieldModifiable = true;
}

//ftpdir	字符串	必须			上传目录,为checkid记录的抓拍时间，格式为4位年+2位月+2位日，如：20210208
//timeStamp可以是int类型或String类型的时间戳（秒）
String getFtpdir_YYYYMMDD(var timeStamp, {String sep = ''}) {
  int timeStampSecond;
  if (timeStamp is String) {
    timeStampSecond = int.parse(timeStamp);
  } else {
    timeStampSecond = timeStamp;
  }

  //将拿到的时间戳转化为日期
  DateTime _dateTime = DateTime.fromMillisecondsSinceEpoch(timeStampSecond * 1000, isUtc: true);
  print('_dateTime = $_dateTime');
  //_dateTime_now = 2021-02-08 20:31:31.235300
  print('formattedDateYYYY_MM_DD_KK_MM = ${DateFormat('yyyy-MM-dd – kk:mm').format(_dateTime)}');
  //formattedDateYYYY_MM_DD_KK_MM = 2021-01-31 – 06:49
  String formattedDateYYYYMMDD = DateFormat('yyyy${sep}MM${sep}dd').format(_dateTime);
  print('formattedDateYYYYMMDD = ${formattedDateYYYYMMDD}');
  //formattedDateYYYYMMDD = 20210131

  return formattedDateYYYYMMDD;
}

// 获得前 31 天的日期起点和终点：['2021-03-18', '2021-04-17']
List getLast31DateString() {
  var _nowTime = DateTime.now();
  String _nowDate_YYYY_MM_DD = DateFormat('yyyy-MM-dd').format(_nowTime);
  //print('_nowDate_YYYY_MM_DD = ${_nowDate_YYYY_MM_DD}');

  var _startTime = _nowTime.add(new Duration(days: -31));
  String _startDate_YYYY_MM_DD = DateFormat('yyyy-MM-dd').format(_startTime);
  print('_startDate_YYYY_MM_DD = ${_startDate_YYYY_MM_DD}');

  var _endTime = _nowTime.add(new Duration(days: -1));
  String _endDate_YYYY_MM_DD = DateFormat('yyyy-MM-dd').format(_endTime);
  print('_endDate_YYYY_MM_DD = ${_endDate_YYYY_MM_DD}');

  return [_startDate_YYYY_MM_DD, _endDate_YYYY_MM_DD];
}

///获取昨天的结束时间的秒时间戳
int getEndDayOfYesterdayStamp() {
  var nowTime = DateTime.now();
  var yesterday = nowTime.add(new Duration(days: -1));
  var day = new DateTime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59);
  //return day.microsecondsSinceEpoch;  //微妙时间戳
  //return day.millisecondsSinceEpoch;  //毫秒时间戳
  return day.millisecondsSinceEpoch ~/ 1000; //秒时间戳，加 ~ 为取整
}

///判断字符串时间是否是今日时间
bool isToday(String strTime) {
  //5.字符串转DateTime，DateTime.parse('2019-11-08') 或者 DateTime.parse('2019-11-08 12:30:05')
  DateTime _dateTime = DateTime.parse(strTime);
  //return day.microsecondsSinceEpoch;  //微妙时间戳
  //return day.millisecondsSinceEpoch;  //毫秒时间戳
  int _secondTiem = _dateTime.millisecondsSinceEpoch ~/ 1000; //秒时间戳，加 ~ 为取整

  return _secondTiem > getEndDayOfYesterdayStamp();
}

///从字符串时间获取秒时间戳
int getStampFromString(String strTime) {
  //5.字符串转DateTime，DateTime.parse('2019-11-08') 或者 DateTime.parse('2019-11-08 12:30:05')
  var _dateTime = DateTime.parse(strTime);
  //return day.microsecondsSinceEpoch;  //微妙时间戳
  //return day.millisecondsSinceEpoch;  //毫秒时间戳
  return _dateTime.millisecondsSinceEpoch ~/ 1000; //秒时间戳，加 ~ 为取整
}

///获取字符串时间 Ntime （HH:MM）中时间的秒数
int getSecondsOfNtime(String Ntime) {
  List list = Ntime.split(':');
  int seconds = (int.parse(list[0]) * 60 + int.parse(list[1])) * 60;

  return seconds; //秒时间戳，加 ~ 为取整
}

//mantissa尾数
String getDate(var timeStamp, {bool mantissa = false}) {
//String getDate(int timeStamp, {bool mantissa = false}) {
  if (timeStamp == null) {
    return "null";
  }

  if (timeStamp is String) {
    return timeStamp;
  }
  //接口获得的时间戳是以秒为单位的
  //flutter 时间戳转换 差8小时。可能是因为默认时区的问题，导致并不是北京时间。（我猜的。。。）
  // 【解决办法】  // 在utc上直接加上8小时（28800秒）。
  //var strtime = DateTime.fromMillisecondsSinceEpoch((timeStamp + 28800) * 1000); //将拿到的时间戳转化为日期
  //Android Studio ADV默认是Use network-provided time zone，时区是GTM+00:00
  //需要指定时区为China-Shanghai，China Time(GMT+08:00)
  var strtime = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000, isUtc: true); //将拿到的时间戳转化为日期
  String date = strtime.toLocal().toString();
  //print('date = $date');
  if (!mantissa) {
    //去除末尾小数
    date = date.substring(0, date.lastIndexOf('.'));
  }
  //print('date = $date');  //date = 2021-05-29 13:52:40
  return date;
}

writeJSON(String jsonContent, String fileName) async {
  File file = await getTheFile(fileName);
  await file.writeAsString(jsonEncode(jsonContent));
}

Future<String> readJSON(String fileName) async {
  return jsonDecode(await (await getTheFile(fileName)).readAsString());
}

Future<File> getTheFile(String fileName) async {
  String strExt = path.extension(fileName).toLowerCase().trim();
  if (0 != strExt.compareTo('.json')) {
    fileName += '.json';
  }

  //在指定位置创建"json"目录
  //final dirPath = await getExternalStorageDirectory();
  final dirPath = await getApplicationDocumentsDirectory();
  var dirJson = Directory(dirPath.path + "/" + "json");
  try {
    bool exists = await dirJson.exists();
    if (!exists) {
      await dirJson.create();
    }
  } catch (e) {
    print(e);
  }

  // /data/data/com.flutter.hyzp_ybqx/app_flutter/json/listMessagesInbox02.json
  // /data/data/com.flutter.hyzp_ybqx/app_flutter/json/listContacts02.json
  return File('${(await getApplicationDocumentsDirectory()).path}/json/$fileName');
}

//以下为测试学习之用
// Future<File> get getFile async {
//   File('${(await getApplicationDocumentsDirectory()).path}/json/listContacts.json');
// }
// writeJSON(String jsonContent) async {
//   //You can write data like this:
//   //await (await getFile).writeAsString(jsonEncode(jsonContent));
//   //该句等同于
//   File file = await getFile;
//   await file.writeAsString(jsonEncode(jsonContent));
// }
//
// readJSON() async {
//   //从文件中读取，下次您可能想读取更改的数据。你可以这样做：
//   String decodedContent = jsonDecode(await (await getFile).readAsString());
// }
