class indexedDb {
  constructor(dbName, version, storeName) {
    this.dbName = dbName;
    this.version = version;
    this.storeName = storeName;
    this.indexdbrequest = window.indexedDB.open(dbName, version);
    this.db;
    this.indexdbrequest.onsuccess = this.onsuccess;
    this.indexdbrequest.onerror = this.onerror;
    this.indexdbrequest.onupgradeneeded = this.onupgradeneeded;
  };
  onsuccess =  (event) => {
    this.db = event.target.result; // 数据库对象
  }
  onerror =  (event) => {
    console.log('indexdb error :',event)
  }
  onupgradeneeded =  (event) => {
    // 数据库创建或升级的时候会触发
    this.db = event.target.result; // 数据库对象
    let objectStore;
    if (!this.db.objectStoreNames.contains(this.storeName)) {
      objectStore = this.db.createObjectStore(this.storeName, { keyPath: "id" }); // 创建表
      // objectStore.createIndex('name', 'name', { unique: true }) // 创建索引 可以让你搜索任意字段
    }
  }
  // 添加数据
  addData(data) {
    return new Promise((resolve, reject) => {
      try{
        const req = this.db
                    .transaction([this.storeName], "readwrite") // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
                    .objectStore(this.storeName) // 仓库对象
                    .add(data);
        // 操作成功
        req.onsuccess = function (event) {
            resolve({code: 200, success: true, data: req.result, msg: '数据添加成功!'})
        }
        // 操作失败
        req.onerror = function (event) {
            let data = {code: -1, success: false, data: null, msg: '数据添加失败!'}
            resolve(data)
        }
      }catch(err){
        resolve({code: -1, success: false, data: null, msg: '数据获取失败!'})
      }
    })
  }

  // 根据id获取数据
  getDataByKey(key) {
    return new Promise((resolve, reject) => {
      try{
        const req = this.db
                    .transaction([this.storeName])
                    .objectStore(this.storeName)
                    .get(key);
        // 操作成功
        req.onsuccess = function (event) {
          resolve({code: 200, success: true, data: req.result, msg: '数据获取成功!'})
        }
        // 操作失败
        req.onerror = function (event) {
          resolve({code: -1, success: false, data: null, msg: '数据获取失败!'})
        }
      }catch(err){
        resolve({code: -1, success: false, data: {}, msg: '数据获取失败!'})
      }
    })
  }

  // 根据id修改数据
  updateDBfunction (data) {
    return new Promise((resolve, reject) => {
      try{
        const req = this.db
                    .transaction([this.storeName], 'readwrite')
                    .objectStore(this.storeName)
                    .put(data)
        // 操作成功
        req.onsuccess = function (event) {
          resolve({code: 200, success: true, data: null, msg: '数据更新成功!'})
        }
        // 操作失败
        req.onerror = function (event) {
          resolve({code: -1, success: false, data: null, msg: '数据更新失败!'})
        }
      }catch(err){
        resolve({code: -1, success: false, data: null, msg: '数据获取失败!'})
      }
    })
  }

  // 根据id删除数据
  deleteDB(id) {
    return new Promise((resolve, reject) => {
      try{
      let req = this.db
        .transaction([this.storeName], "readwrite")
        .objectStore(this.storeName)
        .delete(id);
        // 操作成功
        req.onsuccess = function (event) {
            resolve({code: 200, success: true, data: null, msg: '数据删除成功!'})
        }
        // 操作失败
        req.onerror = function (event) {
            let data = {code: -1, success: false, data: null, msg: '数据删除失败!'}
            resolve(data)
        }
      }catch(err){
        resolve({code: -1, success: false, data: null, msg: '数据获取失败!'})
      }
    })
  }
}
const local = {
  get:function(e){
    return localStorage.getItem(e);
  },
  set:function(key,val){
    localStorage.setItem(key,val);
  }
};

const cookie = {
  get:function(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
  },
  set:function(name, value,date = 30) {
    var Days = date; // 设置有效期
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  },
  del: function delCookie(name) { 
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  },
};

export default {
  get:function(name,type = 1,conf = {dbname:'dbname',version:1,table:'cookies'}) {
    switch(type){
      case 1:
      return cookie.get(name);
      case 2:
      return local.get(name);
      case 3:
        return new Promise((resolve, reject) => {
        const db = new indexedDb(conf.dbname,conf.version,conf.table);
        setTimeout(async ()=>{
          const res = await db.getDataByKey(name);
          resolve(res.data && res.data.data ? res.data.data : null); 
        },50);
      });
    }
  },
  set:function(name, value,type = 1,conf = {dbname:'dbname',version:1,table:'cookies'}) {
    switch(type){
      case 1:
      return cookie.set(name,value);
      case 2:
      return local.set(name,value);
      case 3:
        return new Promise(async (resolve, reject) => {
        const db = await new indexedDb(conf.dbname,conf.version,conf.table);
        setTimeout(async ()=>{
          const res = await db.getDataByKey(name);
          if(res.data){
            const updata = await db.updateDBfunction({data:value,'id':name});
            resolve(updata.data);
          }else{
            const adddata = await db.addData({data:value,'id':name});
            resolve(adddata.data);
          }
        },500);
      });
    }
  },
}