import 'dart:convert';

import '../funcs.dart';

class FilePrefixInfo {
  String name;
  String idCard;
  String mobile;
  int time;
  String area;
  String wifi;
  String userId;

  FilePrefixInfo({
    this.name = "",
    this.idCard = "",
    this.mobile = "",
    this.time = 0,
    this.area = "",
    this.wifi = "",
    this.userId = "",
  });

  ///编码
  String encode() {
    try {
      //内容可能太多了,导致录像时崩溃,所以去掉一些不重要的内容
      Map<String, dynamic> map = {
        "a": name,
        "b": idCard,
        //"c": mobile,
        //"d": time,
        "e": area,
        "f": wifi,
        "g": userId,
      };
      String str = jsonEncode(map);
      //base64里有/,会被认为是文件夹,所以用-替换掉
      str = aesEncrypt(str).replaceAll("/", "-");
      logd("编码文件前缀信息=$str");
      return str;
    } catch (e) {
      loge("编码文件前缀信息异常", error: e);
    }
    return "";
  }

  ///解码
  bool decode(String str) {
    if (str.isEmpty) {
      return false;
    }
    try {
      //base64里有/,会被认为是文件夹,所以用-替换掉
      str = str.replaceAll("-", "/");
      String decode = aesDecrypt(str);
      logd("decode=$decode");
      if (decode.isEmpty) {
        return false;
      }
      Map<String, dynamic> json = jsonDecode(decode);
      //兼容旧的key
      if (json.containsKey("name")) {
        name = json["name"];
      }
      if (json.containsKey("idCard")) {
        idCard = json["idCard"];
      }
      if (json.containsKey("mobile")) {
        mobile = json["mobile"];
      }
      if (json.containsKey("time")) {
        time = json["time"];
      }
      if (json.containsKey("area")) {
        area = json["area"];
      }
      if (json.containsKey("wifi")) {
        wifi = json["wifi"];
      }
      if (json.containsKey("userId")) {
        userId = json["userId"];
      }
      //使用新的key
      if (json.containsKey("a")) {
        name = json["a"];
      }
      if (json.containsKey("b")) {
        idCard = json["b"];
      }
      if (json.containsKey("c")) {
        mobile = json["c"];
      }
      if (json.containsKey("d")) {
        time = json["d"];
      }
      if (json.containsKey("e")) {
        area = json["e"];
      }
      if (json.containsKey("f")) {
        wifi = json["f"];
      }
      if (json.containsKey("g")) {
        userId = json["g"];
      }
      return true;
    } catch (e) {
      loge("解码文件前缀信息异常", error: e);
    }
    return false;
  }
}
