/**
 * 草稿操作
 */

import SqliteBasic from './SqliteBasic';

// TODO: 1、存储图片类型

export default class SaveDraft extends SqliteBasic {
	constructor() {
	    super();
		this.tableName = 'draft_box';
		this.hasTable = false;
	}

	executeWidthCheckDb(operation) {
		return this.openOrCreateDb().then(() => {
			return this.createDraftTable();
		}).then(() => {
			return operation();
		})
	}

	// 创建数据表
	createDraftTable() {
		if (this.hasTable) {
			return Promise.resolve();
		}
		const createSql = `CREATE TABLE if not exists ${this.tableName} (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			key1 CHAR(50),
			key2 CHAR(50) NOT NULL,
			upload INT NOT NULL DEFAULT 0,
			createTime DATETIME default (datetime('now', 'localtime')),
			updateTime DATETIME default (datetime('now', 'localtime'))
		 )`;
		return this.executeSql(createSql).then(() => {
			this.hasTable = true;
		});
	}

	// 插入数据表中
	saveToDraft(item) {
		return this.executeWidthCheckDb(() => {
			const {keys, values} = this.objToSql(item);
			const insertSql = `INSERT INTO ${this.tableName} (${keys})
			VALUES (${values})`;
			return this.executeSql(insertSql);
		})
	}

	// 从数据表中删除
	deleteDraftById(id) {
		return this.executeWidthCheckDb(() => {
			const deleteSql = `DELETE FROM ${this.tableName} WHERE id = ${id}`;
			return this.executeSql(deleteSql);
		})
	}

	// 清空
	clearTable() {
		return this.executeWidthCheckDb(() => {
			return this.executeSql(`DELETE FROM ${this.tableName}`);
		})
	}

	// 从数据表中更新
	updateDraft(id, item) {
		const {values} = this.objToSql(item, true);
		return this.executeWidthCheckDb(() => {
			const updateSql = `UPDATE ${this.tableName}
			SET ${values}
			WHERE id = ${id}`;
			return this.executeSql(updateSql);
		})
	}

	// 查询某一条数据
	selectDataById(id) {
		return this.executeWidthCheckDb(() => {
			const selectSql = `select * from ${this.tableName}
			where id = ${id}`;
			return this.executeSelect(selectSql);
		})
	}

	// 查询所有数据
	selectAllData() {
		return this.executeWidthCheckDb(() => {
			const selectSql = `select * from ${this.tableName}`;
			return this.executeSelect(selectSql);
		})
	}
	
	// 对象转sql语句
	objToSql(obj, isUpdate = false) {
		const keys = Object.keys(obj);
		const values = keys.map(item => {
			// 不同数据类型做不同处理
			let val = obj[item];
			if (typeof val === 'string') {
				val = `'${val}'`;
			}
			if (isUpdate) {
				return `${item}=${val}`;
			}
			return val;
		}).join(',');
		return {keys: keys.join(','), values};
	}
}
