/**
 * sqlite
 */

export const DB_NAME = 'local_db';
export const DB_PATH = '_doc/local_db.db'

export default class SqliteBasic {
	constructor(opts) {
		this.opt = {
			name: DB_NAME, // db
			path: DB_PATH // 路径
		}
	}

	// 检查是否打开
	checkOpen() {
		return plus.sqlite.isOpenDatabase(this.opt);
	}

	// 打开db
	openOrCreateDb() {
		if (this.checkOpen()) {
			return Promise.resolve();
		}
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				...this.opt,
				success: function(res) {
					resolve(res)
				},
				fail: function(err) {
					reject(err)
				}
			})
		})
	}

	// 关闭db
	closeDb() {
		plus.sqlite.closeDatabase({
			name: DB_NAME
		})
	}

	// 查询语句
	executeSelect(sql) {
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				...this.opt,
				sql,
				success: function(res) {
					resolve(res)
				},
				fail: function(e) {
					reject(e)
				}
			})
		})
	}

	// 增删改
	executeSql(sql) {
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				...this.opt,
				sql,
				success: function(res) {
					resolve(res)
				},
				fail: function(e) {
					reject(e)
				}
			})
		})
	}
}
