import { watch } from "vue";

export const getLocal = <T>(key: string, def: T): T => {
  let result: T = def;
  try {
    const str = localStorage.getItem(key);
    if (str) {
      result = JSON.parse(str);
    }
  } catch {
    result = def || localStorage.getItem(key);
  }
  return result;
};

export const changSaveLocal = <T>(key: string, get: () => T) => {
  watch(get, () => {
    if(key == 'token'){
      localStorage.setItem(key, get());
    }else{
      localStorage.setItem(key, JSON.stringify(get()));
    }
  }, {
    deep: true,
  });
};

export const getCookieToken = <T>(name: string) => {
    const cookies = document.cookie.split(';'); // 将Cookie拆分为数组
    for (let i = 0; i < cookies.length; i++) {
        const pair = cookies[i].trim().split('='); // 拆分键和值
        if (pair[0] === name) {
            return pair[1]; // 返回token值
        }
    }
    return null; // 未找到返回null
};
