import _Path from "@/constant/ioPath";

export default class SqlliteDB {
	// 数据库名称
	dbName = "inspect";
	open = false;
	inst = null;

	static async initSqlliteDB() {
		if (!this.inst) {
			this.inst = new SqlliteDB();
			await this.inst.openDB();
			return this.inst;
		}
		return this.inst;
	}

	// 打开数据库  不存在则创建，否则打开
	async openDB() {
		if (this.isOpen()) {
			console.log("isOpen");
			return;
		}
		console.log("db path:" + _Path.getDbPath() + `${this.dbName}.db`);
		let that = this;
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				name: this.dbName,
				path: _Path.getDbPath() + `${this.dbName}.db`,
				success(res) {
					that.open = true;
					resolve();
				},
				fail(e) {
					console.log(e.message);
					reject(e);
				},
			});
		});
	}

	// 检查数据库
	async checkDB() {
		if (!this.open) {
			if (!this.isOpen()) {
				await this.openDB();
			}
		}
	}

	// 关闭数据库
	async closeDB() {
		let open = await this.openDB();
		return new Promise((resolve, reject) => {
			if (!open) {
				resolve();
			} else {
				plus.sqlite.closeDatabase({
					name: this.dbName,
					success(res) {
						this.inst = null;
						this.open = false;
						resolve();
					},
					fail(e) {
						reject(e);
					},
				});
			}
		});
	}

	// 是否打开了数据库
	isOpen() {
		return plus.sqlite.isOpenDatabase({
			name: this.dbName,
			path: `_doc/db/${this.dbName}.db`,
		});
	}

	// 创建表
	async createTable(tableName, filedList) {
		if (!tableName || !filedList || filedList.length === 0) {
			throw new Error("数据库创建失败");
		}

		let fieldSql = "";
		console.log(filedList, "filedList--------------------->>>>");
		filedList.map((val, idx) => {
			fieldSql = fieldSql + '"' + val.field + '" ' + val.format;
			if (idx !== filedList.length - 1) {
				fieldSql = fieldSql + ",";
			}
		});
		return this.executeSQL(
			`CREATE TABLE IF NOT EXISTS ${tableName}(${fieldSql})`
		);
	}

	// 移除表
	// async removeTable(tableName) {
	//   return this.executeSQL(`DROP TABLE IF EXISTS ${tableName}`);
	// }

	// 清空表
	async deleteTable(tableName) {
		return this.executeSQL(`DELETE FROM ${tableName}`);
	}

	// 增删改使用
	async executeSQL(sql) {
		// console.log('excuteSQL:' + sql)
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: this.dbName,
				sql: sql,
				success(res) {
					resolve(res); // 暂时直接返回，方便调试
				},
				fail(e) {
					console.log(e.message);
					reject(e);
				},
			});
		});
	}
	// 增删改返回最后增加的id
	async executeReturnDataSQL(sql) {
		let _ = this
	    return new Promise((resolve, reject) => {
	        plus.sqlite.executeSql({
	            name: _.dbName,
	            sql: sql,
	            success(res) {
	                const queryLastInsertIdSql = "SELECT last_insert_rowid() AS lastId";
	                plus.sqlite.selectSql({
	                    name: _.dbName,
	                    sql: queryLastInsertIdSql,
	                    success(result) {
							console.log('理论上',result)
	                        if (result && result.length > 0) {
	                            let lastInsertId = result[0].lastId;
	                            resolve({ success: true, lastInsertId: lastInsertId });
	                        } else {
	                            resolve({ success: true, lastInsertId: null });
	                        }
	                    },
	                    fail(e) {
	                        reject(e);
	                    },
	                });
	            },
	            fail(e) {
	                console.error('SQL execution failed:', e.message);
	                reject(e); 
	            },
	        });
	    });
	}
	// 查询使用
	async selectSQL(sql) {
		await this.checkDB();
		// console.log('selectSQL:' + sql)
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: this.dbName,
				sql: sql,
				success(res) {
					//   console.log("数据", res);
					resolve(res);
				},
				fail(e) {
					console.log(e.message);
					reject(e);
				},
			});
		});
	}

	// 事务
	async openTransaction(open) {
		let oper = "open";
		if (open) {
			oper = open;
		}
		return new Promise((resolve, reject) => {
			plus.sqlite.transaction({
				name: this.dbName,
				operation: oper,
				success: function(e) {
					resolve();
				},
				fail: function(e) {
					reject(e.message);
				},
			});
		});
	}

	async rollbackTransaction() {
		this.openTransaction("rollback");
	}

	async commitTransaction() {
		this.openTransaction("commit");
	}

	static async checkIfDataImported(sqllitedb) {
		// 假设有一个表或字段来记录数据导入状态
		let result = await sqllitedb.selectSQL('SELECT value FROM SYS_CONFIG WHERE key = "data_imported"');
		return result && result.length > 0 && result[0].value === 'true';
	}

	static async markDataAsImported(sqllitedb) {
		await sqllitedb.executeSQL(
			'INSERT OR REPLACE INTO SYS_CONFIG (key, value) VALUES ("data_imported", "true")');
	}
}