import table from '../sqllite/table'
import _Path from '@/constant/ioPath'
import ioUtil from '@/utils/ioUtil'
import SqlliteDbUtil from '@/utils/sqllitedb'
import userApi from '@/api/user'
import hoistwayApi from '@/api/hoistway'
import assRoomApi from '@/api/assRoom.js'
import hoistwayjson from '../../baseData/hoistway.json'
import userjson from '../../baseData/user.json'
import assroomjson from '../../baseData/assroom.json'
import fileImport from '@/utils/fileImport.js'
export default {

	// app初始化
	async init() {
		// uni.showLoading({
		// 	title: '正在初始化...',
		// })
		// 初始化目录
		// await this.initDir()
		// 初始化数据库
		let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
		console.log('Database initialized.');

		await this.initSqlLite(sqllitedb); // 确保表被创建
		console.log('Tables created.');
		await this.initDir()
		let isInit = await SqlliteDbUtil.checkIfDataImported(sqllitedb); // 确保表存在后再查询
		console.log('Data imported:', isInit);
		if (!isInit) {
			await userApi.saveBatch(userjson)
			await hoistwayApi.saveBatch(hoistwayjson)
			await assRoomApi.saveBatch(assroomjson)
			await SqlliteDbUtil.markDataAsImported(sqllitedb)
		}


		// 初始化完成通知首页
		uni.hideLoading()
	},

	// 检查文件导入
	async importFileData() {
		// 解压缩需要导入的zip，导入后删除
		try {
			console.log('解压导入开始....')
			console.log('导入基础数据开始')
			await fileImport.importBaseFile()
			console.log('导入基础数据结束！')
			console.log('解压导入完成....')
		} catch (e) {
			console.log(e.message)
			uni.showToast({
				icon: 'none',
				title: e.message
			})
			uni.hideLoading()
		}
	},

	////////// 初始化数据库////////////
	async initSqlLite(sqllitedb) {
		console.log('初始化数据库开始...')
		try {
			// 创建打开数据库,已经存在表则跳过
			await sqllitedb.createTable(table.metadataName, table.metadata)
			await sqllitedb.createTable(table.userName, table.user)
			await sqllitedb.createTable(table.inspectionRecordName, table.inspectionRecord) // 巡检记录表
			await sqllitedb.createTable(table.assRoomName, table.assRoom) // 机房、井道信息表
			await sqllitedb.createTable(table.assBuildingName, table.assBuilding) // 楼宇信息
			await sqllitedb.createTable(table.logListName, table.logList) // 日志信息
			// await sqllitedb.createTable(table.listDevicesName, table.listDevices) // 设备上架信息
		} catch (e) {
			console.log(e.message)
		} finally {
			return
			// 关闭数据库
			if (sqllitedb) {
				await sqllitedb.closeDB()
			}
			// 初始化完成后重启APP/退出APP
			uni.showToast({
				icon: 'none',
				title: '初始化完毕即将重新加载...',
				duration: 3000
			})
			let that = this
			setTimeout(function() {
				that.restartApp()
			}, 3000)
		}
	},

	// 初始化目录
	async initDir() {
		const BASE_PATH = "_documents/data/asmzx/pad"; // 基础路径
		try {
			const _doc = _Path.getPrivateDOC()
			const docEntry = await ioUtil.getFileEntry(_doc)
			if(docEntry){
				const parentPaths = [
				      '_documents',
				      '_documents/data',
				      '_documents/data/asmzx',
					  '_documents/data/photos',
				      '_documents/data/asmzx/pad'
				    ];
				    
				    for (const path of parentPaths) {
				      const parts = path.split('/');
				      const parent = parts.slice(0, -1).join('/') || '/';
				      await ioUtil.createDir(parent, parts.pop());
				    }
				
				    const subDirs = ['发送数据', '日志文件', '巡检数据', 'history', 'fssj','list'];
				    await Promise.all(
				      subDirs.map(dir => ioUtil.createDir(BASE_PATH, dir))
				    );
			}

		} catch (e) {
			console.log(e.message)
		}
	},

	// 重启app
	restartApp() {
		// #ifdef APP-PLUS
		if (plus.os.name.toLowerCase() === 'android') {
			plus.runtime.restart();
		}
		// #endif
	},

	// 退出app
	exitApp() {
		// #ifdef APP-PLUS
		if (plus.os.name.toLowerCase() === 'android') {
			plus.runtime.quit();
		} else {
			const threadClass = plus.ios.importClass("NSThread");
			const mainThread = plus.ios.invoke(threadClass, "mainThread");
			plus.ios.invoke(mainThread, "exit");
			// 或者如下
			// plus.ios.import('UIApplication').sharedApplication().performSelector('exit');
		}
		// #endif
	}
}