import SqlliteDbUtil from '@/utils/sqllitedb'
import table from './sqllite/table.js'
import {
	fixNullVal
} from "@/utils/common";

// 用户
export default {

	async selectList() {
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		try {
			let rs = await sqllitedb.selectSQL(`select * from ${table.logListName}`)
			return rs
		} catch (e) {
			console.log(e.message)
		} finally {
			await sqllitedb.closeDB();
		}

	},
	// async pageSelect(data){
	// 	let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
	// 	let pre = (data.page -1) * data.size
	// 	let nxt = data.size
	// 	try {
	// 		let count  = await sqllitedb.selectSQL(`select count(*) as total from  ${table.logListName} limit 1 `)
	// 		let sql = `select * from ${table.logListName} ORDER BY time desc limit ${nxt} offset ${pre} `
	// 		let rs = await sqllitedb.selectSQL(sql)
	// 		console.log('sql',sql, rs)
	// 		return {
	// 			data:rs || [],
	// 			total:count[0].total || 0
	// 		}
	// 	} catch (e) {
	// 		console.log(e.message)
	// 	} finally {
	// 		await sqllitedb.closeDB();
	// 	}
	// },
	async pageSelect(data) {
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		let pre = (data.page - 1) * data.size
		let nxt = data.size

		// 拼接时间范围条件
		let whereClause = "1=1"

		if (data.startTime && data.endTime) {
			whereClause += ` AND time BETWEEN '${data.startTime} 00:00:00' AND '${data.endTime} 23:59:59'`
		} 

		try {
			// 获取总数
			let countSql = `SELECT count(*) as total FROM ${table.logListName} WHERE ${whereClause} LIMIT 1`
			let count = await sqllitedb.selectSQL(countSql)

			// 获取分页数据
			let sql =
				`SELECT * FROM ${table.logListName} WHERE ${whereClause} ORDER BY time DESC LIMIT ${nxt} OFFSET ${pre}`
			let rs = await sqllitedb.selectSQL(sql)

			console.log('sql', sql, rs)

			return {
				data: rs || [],
				total: count[0]?.total || 0
			}
		} catch (e) {
			console.log(e.message)
		} finally {
			await sqllitedb.closeDB()
		}
	},
	async addlog(data) {
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		try {
			const values = `(
			        '${data.LastSynchronizationTime || ""}',
			        '${data.avatar || ""}',
			        '${data.detail || ""}',
			        '${data.isAdmin}',
			        '${data.level}',
			        '${data.module}',
			        '${data.passWord}',
			        '${data.roleName}',
			        '${data.time}',
			        '${data.type}',
			        '${data.unitName}',
			        '${data.user}',
			        '${data.userId}',
			        ${data.userType === null ? 'NULL' : `'${data.userType}'` }
			    )`
			const sql = `INSERT INTO ${table.logListName} (
			        LastSynchronizationTime,
			        avatar,
			        detail,
			        isAdmin,
			        level,
			        module,
			        passWord,
			        roleName,
			        time,
			        type,
			        unitName,
			        user,
			        userId,
			        userType
			    ) VALUES ${values}`;
			let rs = await sqllitedb.selectSQL(sql)
			return rs
		} catch (e) {
			console.log(e.message)
		} finally {
			await sqllitedb.closeDB();
		}
	},

	async remove(id) {
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		try {
			if (!id) {
				return
			}
			let sql = `delete from ${table.logListName} where id = '${id}'`;
			await sqllitedb.executeSQL(sql);
		} catch (e) {
			console.log(e.message)
		} finally {
			// await sqllitedb.closeDB();
		}
	},
	async info(id) {
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		let sql = `select * from ${table.logListName} where id = '${id}'`;
		let res = await sqllitedb.selectSQL(sql);
		if (res && res.length > 0) {
			return res[0]
		}
	},


	async saveBatch(list) {
		if (list.length === 0) {
			return;
		}
		console.log('开始保存用户信息....' + list.length)
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
		try {
			for (let data of list) {
				let column = ''
				let values = ''
				let idx = 0
				for (let attr in data) {
					let dataField = table['user'].find(v => {
						if (v.field === attr) {
							return v
						}
					})
					if (!dataField) {
						continue
					}
					column += dataField.field + ','
					values += "'" + fixNullVal(data[attr]) + "',"
					idx++
				}

				column = column.endsWith(',') ? column.substring(0, column.length - 1) : column
				values = values.endsWith(',') ? values.substring(0, values.length - 1) : values

				let sql = `insert into ${table.logListName}(${column}) values(${values})`
				let has = await this.info(data.id)
				if (has && has.id) {
					await this.remove(data.id)
				}
				await sqllitedb.executeSQL(sql)
			}
		} catch (e) {
			console.log(e.message)
		} finally {
			await sqllitedb.closeDB();
		}
		console.log('导入完成...')
	}
}