export function DB(employee_id, callback) {
  var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
  var req = indexedDB.open('mwth'+employee_id, 1)
  var db = null
  var _this = this
  req.onerror = function(e) {

  }
  req.onsuccess = function(e) {
    //拉数据回来存储
    db = e.target.result
    callback(_this)
  }
  req.onupgradeneeded = function(e) {
    var db = e.target.result;
    if (!db.objectStoreNames.contains('message')) {
      var objectStore = db.createObjectStore('message', {
        keyPath: "id",
        autoIncrement: true
      })
      objectStore.createIndex("cate", "cate", {
        unique: false
      })
      objectStore.createIndex("read", "read", {
        unique: false
      })
    }
    req = indexedDB.open('mwth'+employee_id, 1)
    //callback(_this)
  }
  this.save = function (data) {
    var transaction = db.transaction('message', 'readwrite')
    var store = transaction.objectStore('message')
    for(let i in data){
      store.get(data[i].id).onsuccess = function (e) {
        let d = e.target.result
        if(!d){
          store.put(data[i])
        }
      }
    }
  }
  this.select = function (cate, page, page_size) {

  }
  this.read = function (key) {
    var transaction = db.transaction('message', 'readwrite')
    var store = transaction.objectStore('message')
    store.get(key).onsuccess = function (e) {
      let d = e.target.result
      d.read = 1
      store.put(d)
    }
  }
  this.cancel = function (key, cancel_text) {
    var transaction = db.transaction('message', 'readwrite')
    var store = transaction.objectStore('message')
    store.get(key).onsuccess = function (e) {
      let d = e.target.result
      d['cancel'] = 1
      d['cancel_text'] = cancel_text
      store.put(d)
    }
  }
  this.select_all = function (callback) {
    let transaction = db.transaction('message', 'readwrite')
    let store = transaction.objectStore('message')
    let request = store.openCursor();
    let data = {};
    request.onsuccess = function (e) {
      let result = e.target.result;
      if (result && result !== null) {
        if(!data[result.value.cate]){
          data[result.value.cate] = {info:{num:0, new_content: '', code: result.value.cate}, list: []}
        }
        if(result.value.read == 0){
          data[result.value.cate].info.num ++
        }
        data[result.value.cate].list.push(result.value);
        result.continue();
      } else {
        if (callback) {
          for(let i in data){
            data[i].list = data[i].list.sort((a, b) => {
              return b.id - a.id
            })
          }
          callback(data);
        }
      }
    };
  }
}
