// andrid9支持
// const zipFilePath = "/storage/emulated/0/Download/inspect/import/"
// const unzipFilePath = "/storage/emulated/0/Download/inspect/unzip/"
// const userFilePath = "/storage/emulated/0/Download/inspect/user/user.json"
// const exportFilePath = "/storage/emulated/0/Download/inspect/export/"
// andrid10支持
// const zipFilePath = "/storage/emulated/0/Android/data/io.dcloud.HBuilder/inspect/import/"
// const zipFilePath = "/storage/emulated/0/Android/data/io.dcloud.HBuilder/inspect/unzip/"
// const userFilePath = "/storage/emulated/0/Android/data/io.dcloud.HBuilder/inspect/user/user.json"
// const userFilePath = "/storage/emulated/0/Android/data/io.dcloud.HBuilder/inspect/export/"

import userApi from '@/api/user.js'
import assroomApi from '@/api/assRoom.js'
import hoistwayApi from '@/api/hoistway.js'
import inspectApi from '@/api/inspect.js'
import _Path from '@/constant/ioPath'
import ioUtil from "./ioUtil";

// 检查是否有zip包
async function hasCheckFile() {
	const baseFilePath = _Path.getImportData()
	const baseFileEntry = await ioUtil.getFileEntry(baseFilePath)
	let zipFiles = await ioUtil.getFiles(baseFileEntry);
	zipFiles = zipFiles.filter(i => i.name.indexOf('.zip') !== -1);
	return zipFiles.length;
}

// 导入基础数据，包括：用户、人员配置、检查明细、评分表模板等
async function importBaseFile() {
	const baseFilePath = _Path.getImportBase()
	const baseFileEntry = await ioUtil.getFileEntry(baseFilePath)
	const unzipPath = baseFileEntry.fullPath + 'unzip';
	let unzipEntry = await ioUtil.getFileEntry(unzipPath)
	const zipFileEntry = await ioUtil.getFileEntry(baseFilePath + 'base.zip')

	// 解压
	await ioUtil.removeExistFile(unzipPath)
	if (zipFileEntry) {
		await ioUtil.decompressZip(zipFileEntry.fullPath, unzipPath)
		unzipEntry = await ioUtil.getFileEntry(unzipPath);
	}
	// 导入
	let fileEntries = []
	if (unzipEntry) {
		fileEntries = await ioUtil.getFiles(unzipEntry)
	}
	if (!fileEntries || fileEntries.length === 0) {
		return
	}
	for (let fileEntry of fileEntries) {
		if (!fileEntry) {
			continue
		}
		
		if (fileEntry.isFile) {
			let fileData = await ioUtil.readFile(fileEntry)
			if (!fileData) {
				continue
			}
			let jsonData = JSON.parse(fileData)
			if (!jsonData || jsonData.length === 0) {
				continue
			}
			
			const filename = fileEntry.name
			// 写入数据库
			if (filename === 'on') {
				await peopleApi.saveBatch(jsonData)
			} else if (filename === 'template.json') {
				await templateApi.saveBatch(jsonData)
			} else if (filename === 'user.json') {
				await userApi.saveBatch(jsonData)
			}
		} 
	}

	// 删除文件和解压目录
	await ioUtil.removeExistFile(unzipPath)
	await ioUtil.removeExistFile(zipFileEntry.fullPath)
}

export default {
	importBaseFile,
	hasCheckFile
};
