/*
 * @Author: 念一
 * @Date: 2021-05-19 11:18:48
 * @LastEditTime: 2022-05-11 18:58:50
 * @LastEditors: nian_yi nianyi@dtstack.com
 * @Description: 收集用户操作行为（埋点）中间阶段，本地物理存储
 * @FilePath: /easyvadmin/src/scripts/utils/db/log.ts
 */
import { getEasyvLocalDB } from './_db';
const DB_STORE_NAME = 'collectData';

// 埋点日志
export class BuriedPointLog {
  public db;
  constructor() {
    this.db = null;
    this.init();
  }
  async init(): Promise<void> {
    const result: {
      success: boolean;
      data: any;
    } = await getEasyvLocalDB();
    if (result.success) {
      this.db = result.data;
    } else {
      console.log('初始化失败');
    }
  }
  //  添加数据
  addDB(data): any {
    if (data && Object.keys(data)?.length) {
      const result = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).add(data);
      result.onsuccess = function () {
        console.log('addDB log success');
      };
      result.error = function (event) {
        console.log('addDB log error', event);
      };
    }
  }

  // 读取
  readAll(): Promise<any> {
    return new Promise((resolve, reject) => {
      const result = this.db.transaction([DB_STORE_NAME]).objectStore([DB_STORE_NAME]).getAll();
      result.onerror = function (event) {
        console.log('readAll error', event);
        reject();
      };
      result.onsuccess = function (event) {
        if (event) {
          resolve(event.target.result);
        } else {
          resolve(null);
        }
      };
    });
  }

  // 修改
  put(data): Promise<any> {
    return new Promise((resolve, reject) => {
      const result = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore([DB_STORE_NAME]).put(data);

      result.onerror = (event) => {
        console.log(`update ${data.componentId} error`, event);
        reject(event);
      };
      result.onsuccess = (event) => {
        console.log(`update ${data.componentId} success`);
        resolve(event);
      };
    });
  }

  // 关闭数据库
  closeDB() {
    this.db.close();
    console.log(`db close`);
  }

  // 删除
  remove(id: number) {
    const result = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).delete(1);

    result.onerror = function (event) {
      console.log(`remove ${id} error`, event);
    };

    result.onsuccess = function () {
      console.log(`remove ${id} success`);
    };
  }

  // 整张表都被clear
  clear() {
    const result = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).clear();

    result.onerror = function (event) {
      console.log('clear error', event);
    };

    result.onsuccess = function () {
      console.log('clear success');
    };
  }
}
