提交 9dbb531c authored 作者: zs's avatar zs

init

上级 d3cfa42a
......@@ -20,7 +20,7 @@ export default {
plus.screen.lockOrientation("landscape-primary"); //锁定横屏
// #endif
this.init();
// this.init();
// #ifdef APP-PLUS
plus.android.requestPermissions(
......@@ -60,7 +60,7 @@ export default {
if (now_user.user) {
this.$store.commit("SET_USER", now_user);
}
this.init();
// this.init();
},
onHide: function () {
// app关闭时将数据存储到本地缓存
......
<template>
<view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
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 userjson from '../../baseData/user.json'
export default {
// app初始化
async init() {
uni.showLoading({
title: '正在初始化...',
})
// 初始化目录
await this.initDir()
// 初始化数据库
// cookie.set('initDB', true)
await this.initSqlLite()
// 导入用戶文件文件
// await this.importFileData();
await userApi.saveBatch(userjson)
// 初始化完成通知首页
uni.$emit("initDone", "ok")
uni.hideLoading()
},
// 检查文件导入
async importFileData() {
// 解压缩需要导入的zip,导入后删除
try {
console.log('解压导入开始....')
console.log('导入基础数据开始')
await fileImport.importBaseFile()
console.log('导入基础数据结束!')
console.log('导入检查数据开始....')
await fileImport.importCheckFile()
console.log('导入检查数据结束!')
console.log('解压导入完成....')
} catch (e) {
console.log(e.message)
uni.showToast({
icon: 'none',
title: e.message
})
uni.hideLoading()
}
},
////////// 初始化数据库////////////
async initSqlLite() {
console.log('初始化数据库开始...')
let sqllitedb = null
try {
// 创建打开数据库,已经存在表则跳过
sqllitedb = await SqlliteDbUtil.initSqlliteDB()
// console.log('创建用户表...')
await sqllitedb.createTable(table.userName, table.user)
} 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() {
try {
const _www = _Path.getPrivateWWW()
const _doc = _Path.getPrivateDOC()
const _download = _Path.getDownloads()
const _temp = _Path.getTempPath()
const wwwEntry = await ioUtil.getFileEntry(_www)
const docEntry = await ioUtil.getFileEntry(_doc)
const downloadEntry = await ioUtil.getFileEntry(_download)
if (downloadEntry) {
await ioUtil.createDir(downloadEntry.fullPath, 'base')
await ioUtil.createDir(downloadEntry.fullPath, 'export')
await ioUtil.createDir(downloadEntry.fullPath, 'import')
await ioUtil.createDir(downloadEntry.fullPath, 'doc')
await ioUtil.createDir(downloadEntry.fullPath, 'error')
}
// 获取设备名称
uni.getSystemInfo({
success: async function (e) {
const deviceData = {
deviceId: e.deviceId,
brand: e.deviceBrand,
deviceModel: e.deviceModel,
}
const deviceFilePath = downloadEntry.fullPath + 'name.txt'
await ioUtil.removeExistFile(deviceFilePath)
await ioUtil.writeFile('name.txt', downloadEntry, JSON.stringify(deviceData))
},
});
// 文件目录
if (docEntry) {
await ioUtil.createDir(docEntry.fullPath, 'file')
}
// 临时目录
let tempEntry = await ioUtil.getFileEntry(_temp)
if (!tempEntry) {
await ioUtil.createDir(_temp)
tempEntry = await ioUtil.createDir(_Path.getTempParent(), 'inspectTemp')
}
await ioUtil.createDir(tempEntry.fullPath, 'db')
} 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
}
}
module.exports = {
// 用户表
userName: "SYS_USER",
user: [
{
field: "userId",
format: "TEXT",
},
{
field: "userName",
format: "TEXT",
},
{
field: "userType",
format: "TEXT",
},
{
field: "avatar",
format: "TEXT",
},
{
field: "password",
format: "TEXT",
},
{
field: "rememberPwd",
format: "TEXT",
},
],
};
import SqlliteDbUtil from '@/utils/sqllitedb'
import table from '@/constant/table'
import store from '@/store'
import {
fixNullVal
} from "@/utils/common";
// 用户
export default {
async selectList() {
let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
let rs = await sqllitedb.selectSQL(`select * from ${table.userName}`)
return rs
},
async login(data) {
let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
let account = data.account
let pwd = data.pwd
const sql = `select * from ${table.userName} where userName = '${account}'`
let res = await sqllitedb.selectSQL(sql);
const user = res[0]
return {
data: user,
msg: '登录成功'
};
},
async info(id) {
let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
let sql = `select * from ${table.userName} where userId = '${id}'`;
let res = await sqllitedb.selectSQL(sql);
if (res && res.length > 0) {
return res[0]
}
},
async changePwd(data) {
let {
userName,
userpwd
} = data
let sqllitedb = await SqlliteDbUtil.initSqlliteDB()
let sql = `update ${table.userName} set userpwd = ${userpwd} where userName = '${userName} and userId = '${userId}'`;
let res = await sqllitedb.executeSQL(sql);
},
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.userName}(${column}) values(${values})`
let has = await this.info(data.userId)
if (has && has.userId) {
await this.remove(data.userId)
}
await sqllitedb.executeSQL(sql)
}
} catch (e) {
console.log(e.message)
} finally {
await sqllitedb.closeDB();
}
console.log('导入完成...')
}
}
\ No newline at end of file
[ {
"userId": 29,
"userName": "叶一凡",
"userType": "sys_user",
"avatar": "",
"password": "123456",
"rememberPwd": "0"
}, {
"userId": 30,
"userName": "bjqxj",
"userType": "sys_user",
"avatar": "",
"password": "JF85250920",
"rememberPwd": "0"
}]
export default {
getDownloads() {
return '_downloads/';
},
getPrivateDOC() {
return '_doc/';
},
getPrivateWWW() {
return '_www/';
},
/****** 导出 ******/
getExportCheckData() {
return this.getDownloads() + 'export/';
},
/****** 导入 ******/
getImportData() {
return this.getDownloads() + 'import/';
},
getImportBase() {
return this.getDownloads() + 'base/';
},
getDownloadDoc() {
return this.getDownloads() + 'doc/';
},
getCheckFileDir() {
return this.getPrivateDOC() + 'file/';
},
/****** 错误 ******/
getErrorDir() {
return this.getDownloads() + 'error/';
},
/****** 模板 ******/
getTemplateFileDir() {
return this.getPrivateDOC();
},
/****** db存储 ******/
getDbPath() {
return this.getPrivateDOC() + 'db/';
},
/********* 临时 ********/
getTempPath() {
return '/storage/emulated/0/Android/data/inspectTemp/';
},
getTempParent() {
return '/storage/emulated/0/Android/data/';
},
getAppDataPath() {
return this.getPrivateDOC() + 'data/';
},
getAppinspectFilePath() {
return this.getAppDataPath() + 'inspect/';
},
}
module.exports = {
// 用户表
userName: "SYS_USER",
user: [
{
field: "userId",
format: "TEXT",
},
{
field: "deptId",
format: "TEXT",
},
{
field: "userName",
format: "TEXT",
},
{
field: "nickName",
format: "TEXT",
},
{
field: "userType",
format: "TEXT",
},
{
field: "email",
format: "TEXT",
},
{
field: "phonenumber",
format: "TEXT",
},
{
field: "sex",
format: "TEXT",
},
{
field: "avatar",
format: "TEXT",
},
{
field: "password",
format: "TEXT",
},
{
field: "status",
format: "TEXT",
},
{
field: "delFlag",
format: "TEXT",
},
],
};
......@@ -87,14 +87,21 @@
"style": {
"navigationBarTitleText": ""
}
},
{
"path" : "api/api",
"style" :
{
"navigationBarTitleText" : ""
}
}
// {
// "path" : "api/api",
// "style" :
// {
// "navigationBarTitleText" : ""
// }
// },
// {
// "path" : "api/db/db",
// "style" :
// {
// "navigationBarTitleText" : ""
// }
// }
],
"globalStyle": {
"pageOrientation": "landscape",
......
<template>
<!-- 登录页 -->
<view class="content">
<view class="login_wrap">
<view class="login_wrap">
{{personList}}
<view class="top-module">
<image src="@/static/logo.png" mode="aspectFit" alt="" />
<view class="title">杭州内网监管在线-运维在线</view>
</view>
<view class="form_wrap">
<view class="input_wrap">
<uni-easyinput class="log-input" clearSize="0" v-model="person.user" prefixIcon="person"
<uni-easyinput class="log-input" clearSize="0" v-model="person.account" prefixIcon="person"
placeholder="用户名"></uni-easyinput>
<uni-easyinput v-if="passwordVisible" class="log-input" prefixIcon="locked" clearSize="0" v-model="person.pd"
@iconClick="togglePasswordVisible" :placeholder="passwordPlaceholder" :passwordIcon="false"
:type="passwordVisible ? 'text' : 'password'"></uni-easyinput>
<uni-easyinput v-if="passwordVisible" class="log-input" prefixIcon="locked" clearSize="0"
v-model="person.pwd" @iconClick="togglePasswordVisible" :placeholder="passwordPlaceholder"
:passwordIcon="false" :type="passwordVisible ? 'text' : 'password'"></uni-easyinput>
<uni-easyinput v-else class="log-input" prefixIcon="locked-filled" clearSize="0" v-model="person.pd"
@iconClick="togglePasswordVisible" :placeholder="passwordPlaceholder" :passwordIcon="false"
:type="passwordVisible ? 'text' : 'password'"></uni-easyinput>
......@@ -30,29 +28,19 @@
</template>
<script>
import getDateTime from "@/common/getdateTime.js";
import initService from '@/api/sqllite/init.js'
import userApi from "@/api/user.js"
import SqlliteDbUtil from '@/utils/sqllitedb'
import table from '@/api/sqllite/table.js'
import {
SYNCHRONIZE_DATA_PAD,
checkAndCreateDirectory,
createFileWithPlusIO,
TEST,
TEST_2X,
USER_FILE_NAME,
getUserList,
} from "@/utils/systemCofig";
import {
LOG_TYPE_ENUM,
getLogContent,
addLog,
readDirectoryData,
readLogData,
} from "@/utils/IoReadingAndWriting.js";
import moment from "moment";
import {
Base64
} from "js-base64";
export default {
components: {},
data() {
......@@ -61,8 +49,8 @@
// user: "bjqxj",
// pd: "JF85250920",
user: "叶一凡", // 超管账号
pd: "123456",
account: "叶一凡", // 超管账号
pwd: "123456",
},
backButtonPress: 0,
personList: [],
......@@ -76,14 +64,14 @@
return this.passwordVisible ? "密码" : "********";
},
},
created() {
this.initDatabase()
onLoad: function(query) {
initService.init()
console.log('即将开始初始化app')
},
created() {},
onShow() {},
mounted() {
this.$store.commit("SET_DARF_DATA", {});
this.$store.commit("SET_LOG_LIST", []);
this.$store.commit("SET_ALL_DATA", []);
async mounted() {
},
// 定义返回退出
......@@ -107,147 +95,14 @@
return true;
},
methods: {
// 初始化数据库
initDatabase() {
// 打开或创建数据库
this.db = plus.sqlite.openDatabase({
name: 'test.db',
path: '_doc/test.db', // 应用私有目录
success: () => {
console.log('数据库打开成功');
this.createTable();
},
fail: (e) => {
console.log('数据库打开失败:' + JSON.stringify(e));
}
});
},
// 创建表
createTable() {
const sql = `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)`;
this.db.executeSql({
sql: sql,
success: () => {
console.log('表创建成功');
},
fail: (e) => {
console.log('表创建失败:' + JSON.stringify(e));
}
});
},
// 切换密码显示/隐藏
togglePasswordVisible() {
this.passwordVisible = !this.passwordVisible;
},
// 点击登录
login() {
getUserList().then((personList) => {
this.personList = personList;
// 是否输入账号密码
if (this.person.user && this.person.pd) {
let key = null;
const obj = this.personList.some((item, index) => {
if (item.user == this.person.user) {
key = index;
return true;
}
});
uni.showLoading({
title: "加载中",
});
// 存在该账号
if (obj) {
// 判断账号密码是否正确
if (
this.person.user == this.personList[key].user &&
this.person.pd == this.personList[key].passWord
) {
const userInfo = this.personList[key];
this.$store.commit("SET_USER", userInfo);
uni.setStorageSync("now_user", userInfo);
uni.setStorageSync("last_time", userInfo.LastSynchronizationTime || "");
uni.navigateTo({
url: "/pages/home/home",
});
uni.showToast({
title: "登录成功",
icon: "none",
duration: 2000,
});
readLogData()
.then((res) => {
const log_list = res;
// 更新日志信息
const logContent = getLogContent(LOG_TYPE_ENUM.login);
log_list.push(logContent);
this.$store.commit("SET_LOG_LIST", log_list);
addLog(log_list);
uni.hideLoading();
})
.catch((error) => {
if (error.code == 0) {
uni.showToast({
title: error.msg,
icon: "none",
duration: 2000,
});
return;
}
const log_list = [];
// 更新日志信息
const logContent = getLogContent(LOG_TYPE_ENUM.login);
log_list.push(logContent);
this.$store.commit("SET_LOG_LIST", log_list);
addLog(log_list);
});
// 密码不正确
} else {
uni.showToast({
title: "密码错误,请重试",
icon: "none",
duration: 2000,
});
uni.hideLoading();
}
// 不存在该账号
} else {
uni.showToast({
title: "您无权登录,请联系管理员处理",
icon: "none",
duration: 2000,
});
uni.hideLoading();
}
// 未输入账号或者密码
} else {
uni.showToast({
title: "账号密码不能为空",
icon: "none",
duration: 2000,
});
}
async login() {
userApi.login(this.person).then((personList) => {
this.personList = personList.data;
});
},
},
......
// 获取当前page
export function getCurrentPage() {
const pages = getCurrentPages() // 获取加载的页面
const currentPage = pages[pages.length - 1] // 获取当前页面的对象
return currentPage
}
export function getLastPage() {
const pages = getCurrentPages() // 获取加载的页面
const lastPage = pages[pages.length - 2] // 获取当前页面的对象
return lastPage
}
// 获取当前页面Url
export function getCurrentPageUrl() {
const currentPage = getCurrentPage()
const url = currentPage.route
return url
}
// 获取当前页面Url带参数
export function getCurrentPageUrlWithArgs() {
const currentPage = getCurrentPage()
let url = currentPage.route
let options = currentPage.options
// 拼接url的参数
let urlWithArgs = url + '?'
for (let key in options) {
let value = options[key]
if (value) {
urlWithArgs += key + '=' + value + '&'
}
}
if (urlWithArgs.indexOf('&') !== -1) {
urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
}
return urlWithArgs
}
// 解析url
export function parseQuery() {
const currentPage = getCurrentPage()
const res = {
path: currentPage.route,
query: currentPage.options
}
return res
}
// url参数处理
export function handleUrlParam(path) {
let req = new Object()
if (path.includes('?')) {
let url = path.split('?')[1] // 获取url中"?"符后的字串
let strs = url.split('&')
for (let i = 0; i < strs.length; i++) {
req[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
}
}
return req
}
// 处理二维码链接
export function handleQrCode() {
let param = parseQuery()['q']
if (!param) {
return ''
}
if (param.indexOf('%3F') != -1) {
param = param
.split('%3F')[1] // ?
.replace(/%3D/g, ':') // =
.replace(/%26/g, ',') // &
.split(',')
.map((item, index) => {
item = item.split(':')
return `"${item[0]}":"${item[1]}"`
})
.join(',')
param = JSON.parse('{' + param + '}')
return param
} else {
return handleUrlParam(param)
}
}
// 复制剪贴板
export const copyClipboard = data => {
if (!data) {
return
}
// 只能复制字符串,数值不生效
data = data + ''
uni.setClipboardData({
data: data,
success: res => {
uni.showToast({
title: '复制成功',
icon: 'success',
duration: 2000,
})
},
})
}
// 克隆对象
export function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// 处理数据库存储null
export function fixNullVal(val) {
val = fixZeroVal(val)
val = !val || val === 'null' ? '' : val
return val
}
// 处理数据库无法存储 数值:0
export function fixZeroVal(val) {
val = val === '0' || val === 0 ? '0' : val
return val
}
// 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/service/user'
import feedbackApi from '@/api/service/feedback'
import checkDetailApi from '@/api/service/checkDetail'
import templateApi from '@/api/service/feedbackTemplate'
import peopleApi from '@/api/service/peopleConfig'
import sampleApi from '@/api/service/sample'
import presenceApi from '@/api/service/presence'
import doubleRandomApi from '@/api/service/doubleRandom'
import _Path from '@/constant/ioPath'
import logger from './logger'
import ioUtil from "./ioUtil";
import dateUtil from "./date";
import cookie from './cookie'
// 检查是否有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 importCheckFile() {
const baseFilePath = _Path.getImportData()
const baseFileEntry = await ioUtil.getFileEntry(baseFilePath)
const unzipPath = baseFileEntry.fullPath + 'unzip/';
const zipFiles = await ioUtil.getFiles(baseFileEntry);
if (!zipFiles || zipFiles.length === 0) {
return
}
// 此处为每次导入的包
for (let zipFile of zipFiles) {
// 解压
if (zipFile.isDirectory || zipFile.name.indexOf('.zip') === -1) {
continue;
}
let dirName = zipFile.name.indexOf('.') > -1 ? zipFile.name.substring(0, zipFile.name.indexOf('.')) : zipFile.name
let unzipDir = unzipPath + dirName + '/'
await ioUtil.removeExistFile(unzipDir)
// 防止解压文件有问题
try{
let errorInfo = await ioUtil.decompressZip(zipFile.fullPath, unzipDir)
if (errorInfo && errorInfo.message) {
const errorDate = dateUtil.parseTime(new Date(), '{y}-{m}-{d}')
await ioUtil.createDir(_Path.getErrorDir(), errorDate)
const errorDirEntry = await ioUtil.getFileEntry(_Path.getErrorDir() + errorDate + '/')
await ioUtil.moveFile(zipFile, errorDirEntry)
}
}catch(e){
console.log(e.message)
}
let unzipDirEntry = await ioUtil.getFileEntry(unzipDir)
let checkZipFiles = await ioUtil.getFiles(unzipDirEntry)
// 导入数据
// 仅仅保证单个完整包不重复导入,单词导出检查数据是一致的
let checkList = []
for (let checkZipEntry of checkZipFiles) {
if (!checkZipEntry.isFile || checkZipEntry.name.indexOf('.zip') === -1) {
continue
}
let filename = ioUtil.getFilenameNoExt(checkZipEntry.name)
if (!filename || checkList.indexOf(filename) > -1) {
continue;
}
checkList.push(filename)
let nameArr = filename.split('_')
let id = nameArr[0]
let checkType = nameArr[1]
let checkPath = unzipDir + checkType + '/' + id
await ioUtil.decompressZip(checkZipEntry.fullPath, checkPath)
// 导入
await importCheck(checkPath, id, checkType)
}
// 处理完毕删除
await ioUtil.removeExistFile(zipFile.fullPath)
await ioUtil.removeExistFile(unzipDirEntry.fullPath)
}
}
// 导入检查
async function importCheck(checkPath, id, checkType) {
const checkDirEntry = await ioUtil.getFileEntry(checkPath)
const files = await ioUtil.getFiles(checkDirEntry)
if (!files || files.length === 0) {
return
}
// 创建附件文件目录
let checkFilePath = _Path.getCheckFileDir() + checkType + '/' + id
await ioUtil.removeExistFile(checkFilePath)
await ioUtil.createDir(_Path.getCheckFileDir(), checkType)
await ioUtil.createDir(_Path.getCheckFileDir() + '/' + checkType, id)
let checkFileEntry = await ioUtil.getFileEntry(checkFilePath)
for (let checkEntry of files) {
if (checkEntry.isFile && checkEntry.name.indexOf('.json') !== -1) {
// 写入数据库
let data = await ioUtil.readFile(checkEntry)
if (!data) {
continue
}
let checkData = JSON.parse(data)
// 把评分结果预先存入缓存,用于判断首页用户是否已评分
let checkScored = cookie.get('checkScored')
if (!checkScored) {
checkScored = {}
cookie.set('checkScored', checkScored)
}
const key = checkData.id + '_' + checkData.checkType
if (checkData.recheck === '1' && checkData.recheckScore) {
checkScored[key] = true
} else if (checkData.recheck === '0' && checkData.firstScore) {
checkScored[key] = true
} else {
checkScored[key] = false
}
cookie.set('checkScored', checkScored)
// 评分
await feedbackApi.saveBatch(checkData.feedbackList)
// 明细
await checkDetailApi.saveBatch(checkData.checkDetailList)
// 检查
if (checkData.checkType === '1') {
await sampleApi.save(checkData)
} else if (checkData.checkType === '2') {
await presenceApi.save(checkData)
} else if (checkData.checkType > 2) {
await doubleRandomApi.save(checkData)
}
} else {
await ioUtil.copyFileDir(checkEntry, checkFileEntry)
}
}
}
// 导入基础数据,包括:用户、人员配置、检查明细、评分表模板等
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)
}
} else if (fileEntry.isDirectory && fileEntry.name === 'template'){
// 廉政告知书、检查模板文件
const templateFileEntry = await ioUtil.getFileEntry(_Path.getTemplateFileDir())
await ioUtil.copyFileDir(fileEntry, templateFileEntry)
}
}
// 删除文件和解压目录
await ioUtil.removeExistFile(unzipPath)
await ioUtil.removeExistFile(zipFileEntry.fullPath)
}
export default {
importCheckFile,
importBaseFile,
hasCheckFile
};
// 检查是否有目录,有就删除
async function removeExistFile(path) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(path,
function(checkEntry) {
if (checkEntry.isDirectory) {
checkEntry.removeRecursively()
} else {
checkEntry.remove()
}
resolve(true)
},
function(e) {
console.log(e.message)
resolve(false)
})
});
}
// 获取无后缀名filename
function getFilenameNoExt(fileName) {
if (fileName.indexOf('.') === -1) {
return false
}
return fileName.substring(0, fileName.lastIndexOf('.'))
}
// 获取filename
function getFilename(fileName) {
if (fileName.indexOf('/') === -1) {
return false
}
return fileName.substring(fileName.lastIndexOf('/') + 1)
}
// 获取后缀名
function getSuffix(fileName) {
if (fileName.indexOf('.') === -1) {
return false
}
return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
}
// 获取后缀名
function getFileDir(fileName) {
if (fileName.indexOf('/') === -1) {
return false
}
return fileName.substring(0, fileName.lastIndexOf('/') + 1)
}
// 获取文件或目录
async function getFileEntry(path) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(path, function(entry) {
resolve(entry)
}, function(e) {
console.log(path + ',' + e.message)
resolve(null)
});
})
}
// 获取文件系统
async function getFileSystem(path) {
return new Promise((resolve, reject) => {
plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
resolve(fs)
}, function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 写入文件
async function writeFile(fileName, fileDirEntry, data) {
return new Promise((resolve, reject) => {
fileDirEntry.getFile(fileName, {
create: true
},
function(fileEntry) {
fileEntry.file(function(file) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function() {}
writer.seek(writer.length - 1);
writer.write(data);
resolve(file)
}, function(e) {
console.log(e.message);
reject(e.message)
});
}, function(e) {
console.log(e.message);
reject(e.message)
});
},
function(e) {
console.log(e.message)
reject(e.message)
});
})
}
// 获取文件Entry
async function getDirFileEntry(path, file) {
return await getFileEntry(path + '/' + file)
}
// 获取文件或目录
async function getParent(entry) {
return new Promise((resolve, reject) => {
entry.getParent(function(entry) {
resolve(entry)
}, function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 创建目录
function createDir(url, dirName) {
//url值可支持相对路径URL、本地路径URL
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(url, function(entry) {
entry.getDirectory(dirName, {
create: true,
exclusive: false
}, function(dir) {
resolve(dir)
}, function(e) {
console.log(e.message)
resolve(null)
});
}, function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 创建文件
function createFile(url, fileName) {
//url值可支持相对路径URL、本地路径URL
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(url, function(entry) {
entry.getFile(fileName, {
create: true
}, function(file) {
resolve(file)
}, function(e) {
console.log(e.message)
resolve(null)
});
}, function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 拷贝目录
async function copyFileDir(srcDirEntry, targetDirEntry, newName) {
return new Promise((resolve, reject) => {
let name = srcDirEntry.name
if (newName) {
name = newName
}
srcDirEntry.copyTo(targetDirEntry, name,
function(entry) {
resolve(entry)
},
function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 拷贝文件
async function copyFile(srcFile, targetDirEntry, newName) {
return new Promise((resolve, reject) => {
let name = srcFile.name
if (newName) {
name = newName
}
srcFile.copyTo(targetDirEntry, name,
function(entry) {
resolve(entry)
},
function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 移动文件
async function moveFile(srcFile, targetDirEntry, newName) {
return new Promise((resolve, reject) => {
let name = srcFile.name
if (newName) {
name = newName
}
srcFile.moveTo(targetDirEntry, name,
function(entry) {
resolve(entry)
},
function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 获取目录所有文件
async function getFiles(dirEntry) {
return new Promise((resolve, reject) => {
let dirReader = dirEntry.createReader();
dirReader.readEntries(
function(entries) { //历遍子目录即可
resolve(entries)
},
function(e) {
console.log(e.message)
resolve([])
}
);
})
}
// 读取文件entry
async function readFile(fileEntry) {
return new Promise((resolve, reject) => {
fileEntry.file(function(file) {
let fileReader = new plus.io.FileReader();
fileReader.readAsText(file, "utf-8")
fileReader.onloadend = function(res) {
resolve(res.target.result)
};
}, function(e) {
console.log(e.message)
resolve(null)
});
})
}
// 解压zip
async function decompressZip(zipFilePath, targetDir) {
return new Promise((resolve, reject) => {
plus.zip.decompress(
zipFilePath,
targetDir,
function(res) {
resolve()
},
function(e) {
console.log(e.message)
resolve(e)
}
)
})
}
// 压缩成zip
async function zip(targetPath, zipPath) {
return new Promise((resolve, reject) => {
plus.zip.compress(
targetPath,
zipPath,
function() {
resolve(true)
},
function(e) {
console.log(e.message)
resolve(null)
}
)
})
}
// 获取物理路径
async function getAbsolutePath (url) {
return new Promise((resolve, reject) => {
plus.io.convertLocalFileSystemURL(url,
function(entry) {
console.log(entry)
resolve(entry.fullPath)
},
function(e) {
console.log(e.message)
resolve(null)
}
)
})
}
export default {
removeExistFile,
getFileSystem,
getFilename,
getFilenameNoExt,
getSuffix,
getFileDir,
getFileEntry,
getParent,
createDir,
createFile,
writeFile,
decompressZip,
zip,
copyFile,
copyFileDir,
moveFile,
readFile,
getFiles
};
......@@ -2,7 +2,7 @@ import _Path from "@/constant/ioPath";
export default class SqlliteDB {
// 数据库名称
dbName = "jdjc";
dbName = "inspect";
open = false;
inst = null;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论