import 'dart:io';

import 'package:eitc_erm_dental_flutter/entity/file_prefix_info.dart';

import '../funcs.dart';

///历史条目
class HistoryItemInfo {
  ///路径
  final String path;

  ///名称
  String name = "";

  ///类型,0图片,1视频
  final int type;

  ///时间
  int time = 0;

  bool isValid = false;

  ///前缀信息
  FilePrefixInfo? prefixInfo;

  ///是否是选择模式
  bool _isSelectMode = false;

  ///是否已被选择
  bool isSelected = false;

  HistoryItemInfo(this.path, this.type) {
    try {
      int index = path.lastIndexOf("/");
      String fileName = path.substring(index + 1);
      if (fileName.isEmpty) {
        isValid = false;
        return;
      }
      fileName = fileName.replaceAll(
          type == 0
              ? RegExp(r".jpg")
              : RegExp(Platform.isIOS ? r".mov" : r".avi"),
          "");
      if (fileName.isEmpty) {
        isValid = false;
        return;
      }
      List<String> strs = fileName.split(RegExp(r"_"));
      String timeStr = strs.last;
      DateTime date;
      //20240913115441.mov
      //目前ios的视频时间戳不是用的毫秒值
      if (Platform.isIOS && type == 1) {
        date = DateTime(
            int.parse(timeStr.substring(0, 4)),
            int.parse(timeStr.substring(4, 6)),
            int.parse(timeStr.substring(6, 8)),
            int.parse(timeStr.substring(8, 10)),
            int.parse(timeStr.substring(10, 12)),
            int.parse(timeStr.substring(12)));
        time = date.millisecondsSinceEpoch;
      } else {
        time = int.parse(timeStr);
        date = DateTime.fromMillisecondsSinceEpoch(time);
      }
      String year = "${date.year}";
      String month = "${date.month}".padLeft(2, "0");
      String day = "${date.day}".padLeft(2, "0");
      String hour = "${date.hour}".padLeft(2, "0");
      String minute = "${date.minute}".padLeft(2, "0");
      String second = "${date.second}".padLeft(2, "0");
      name = "$year/$month/$day $hour:$minute:$second";
      if (strs.length == 2) {
        String encode = strs[0];
        prefixInfo = FilePrefixInfo();
        isValid = prefixInfo!.decode(encode);
      }
    } catch (e) {
      isValid = false;
      loge("解析历史条目数据异常", error: e);
    }
  }

  ///是否选择模式
  bool get isSelectMode => _isSelectMode;

  ///是否选择模式
  set isSelectMode(bool value) {
    _isSelectMode = value;
    isSelected = false;
  }

  ///文件URI,如果path为空就返回null
  Uri? get fileUri => path.isEmpty ? null : Uri.file(path);
}
