//定义一个名为Cookies的对象
const Cookies = {
  //表示cookie数据在本地存储中的键名
  cookieDataKey: "__cookies__",

  //定义一个set方法，用于设置cookie值，参数包括name、value和expires等属性
  set(name, value, { expires, domain, path, secure, httpOnly } = {}) {
    //获取本地存储中的cookie数据
    let cookies = this._getCookieData();
    //初始化过期时间字符串
    let expiresFormatted = "";

    //如果expires是Date类型，则将其转换为UTC格式的字符串
    if (expires instanceof Date) {
      expiresFormatted = expires.toUTCString();
    } else if (typeof expires === "number") {
      //如果expires是number类型，则计算出过期时间并转换为UTC格式的字符串
      let expiresTime = new Date();
      expiresTime.setTime(expires * 1000);
      expiresFormatted = expiresTime.toUTCString();
    }

    //将新的cookie值添加到cookie对象中
    cookies[name] = {
      value,
      expires: expiresFormatted,
      domain,
      path,
      secure,
      httpOnly
    };

    //将更新后的cookie数据存储到本地存储中
    this._setCookieData(cookies);
  },

  //定义一个get方法，用于获取指定cookie的值
  get(name) {
    //获取本地存储中的cookie数据
    let cookies = this._getCookieData();

    //如果该cookie存在，则获取其值
    // eslint-disable-next-line no-prototype-builtins
    if (cookies.hasOwnProperty(name)) {
      let { value, expires } = cookies[name];

      //如果该cookie已过期，则删除该cookie并返回undefined
      if (expires !== "" && new Date() > new Date(expires)) {
        delete cookies[name];
        this._setCookieData(cookies);
        return undefined;
      }

      //返回该cookie的值
      return value;
    }

    //如果该cookie不存在，则返回undefined
    return undefined;
  },

  //定义一个getAll方法，用于获取所有cookie值
  getAll() {
    return this._getCookieData();
  },

  //定义一个remove方法，用于删除指定cookie
  remove(name) {
    let cookies = this._getCookieData();

    //如果该cookie存在，则删除该cookie
    // eslint-disable-next-line no-prototype-builtins
    if (cookies.hasOwnProperty(name)) {
      delete cookies[name];
      this._setCookieData(cookies);
    }
  },

  //定义一个私有的_getCookieData方法，用于获取本地存储中的cookie数据
  _getCookieData() {
    let cookies = uni.getStorageSync(this.cookieDataKey);
    return cookies ? JSON.parse(cookies) : {};
  },

  //定义一个私有的_setCookieData方法，用于存储更新后的cookie数据到本地存储中
  _setCookieData(cookies) {
    uni.setStorageSync(this.cookieDataKey, JSON.stringify(cookies));
  }
};

//将Cookies对象作为默认导出的模块
export default Cookies;
