|
- import { conforms, reject } from 'lodash'
- import get from 'lodash/get'
- import omit from 'lodash/omit'
- import moment from 'moment'
-
- /**
- * 用于代码生成器页面,加载表单数据使用
- *
- * 提供以下工具方法:
- *
- * 【新建表单时使用】:
- * async getDefaultForm()
- * async getDefaultValue(path, scheme)
- * 根据表单 scheme 获取初始化的空表单数据 / 获取单条表单项的初始数据
- *
- * 【提交表单时使用】:
- * async getPostData()
- * async convertToPostData()
- * 生成 POST 提交用的表单数据 / 获取单条表单项的提交数据
- *
- * verifyForm()
- * 验证表单数据,返回一个输入错误信息的数组
- *
- * 【打开一个表单时使用】:
- * async formatFormData(formData)
- * async convertToFormValue(scheme, val, dataSource)
- * 将拉取的表单值转化为表单数据 / 将单条表单项的表单值转化为表单数据
- *
- */
- export default {
- methods: {
- // 获取表单默认值
- async getDefaultForm() {
-
- const result = {}
- for (const [tableName, tableItem] of Object.entries(this.scheme)) {
- const itemData = {}
- for (const [fieldName, scheme] of Object.entries(tableItem)) {
- if (fieldName !== '__GIRDTABLE__') {
- itemData[fieldName] = await this.getDefaultValue(`${tableName}.${fieldName}`, scheme,tableName,fieldName)
- }
- }
- result[tableName] = '__GIRDTABLE__' in tableItem ? [itemData] : itemData
- }
-
- return result
- },
-
- // 获取单条表单项的默认值
- async getDefaultValue(path, schemeItem,tableName,fieldName) {
- switch (schemeItem.type) {
- case 'keyValue':
- return this.processId
-
- case 'currentInfo':
- switch (schemeItem.dataType) {
- case 'user':
- return this.GET_GLOBAL('loginUser').userId
- case 'department':
- return this.GET_GLOBAL('loginUser').departmentId
- case 'company':
- return this.GET_GLOBAL('loginUser').companyId
- case 'time':
- return moment().format('YYYY-MM-DD HH:mm:ss')
- default:
- return ''
- }
-
- case 'datetime':
- const datetimeFormat = (Number(schemeItem.dateformat) === 0 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss')
- const today = moment()
- const dfDatetime = [
- today.subtract(1, 'day'),
- today,
- today.add(1, 'day')
- ][Number(schemeItem.dfvalue)] || today
-
- return dfDatetime.format(datetimeFormat) || ''
-
- case 'radio':
- case 'select':
- const radioItem = get(this.dataSource, path).find(t => t.value === schemeItem.dfvalue) ||
- get(this.dataSource, path)[0]
- return schemeItem.type === 'radio' ? radioItem.value : ''
-
- case 'checkbox':
- if (!schemeItem.dfvalue) { return [] }
- return schemeItem.dfvalue.split(',').filter(t => get(this.dataSource, path, []).find(s => s.value === t))
-
- case 'encode':
- if (!schemeItem.rulecode) { return '' }
- const result = await this.FETCH_ENCODE(schemeItem.rulecode)
- return result || ''
-
- case 'upload':
- let folderIds = {}
- let getstData = uni.getStorageSync('folderIds');
- if(getstData){
- folderIds = JSON.parse(getstData)
- }
- if(folderIds[tableName]){
- folderIds[tableName][fieldName] = ''
- }else{
- let obj = {}
- obj[fieldName] = ''
- folderIds[tableName] = obj
- }
- uni.setStorageSync('folderIds',JSON.stringify(folderIds));
- return []
-
- case 'guid':
- return this.GUID('-')
-
- default:
- return schemeItem.dfvalue || ''
- }
- },
-
- // 验证表单项输入是否正确,返回一个包含所有错误信息的数组
- verifyForm() {
- console.log(this.scheme)
- const result = []
- Object.entries(this.scheme).forEach(([tableName, tableItem]) => {
- if ('__GIRDTABLE__' in tableItem) {
- this.getValue(tableName).forEach((tableValue, index) => {
- Object.entries(tableItem).forEach(([fieldName, scheme]) => {
- if (fieldName === '__GIRDTABLE__' || !scheme.verify) { return }
-
- const val = tableValue[fieldName]
- const verifyResult = this.verify[scheme.verify](val)
-
- if (verifyResult !== true) {
- result.push(`[表格${tableItem.__GIRDTABLE__}第${index}行${scheme.title}列]: ${verifyResult}`)
- }
- })
- })
- } else {
- Object.entries(tableItem).forEach(([fieldName, scheme]) => {
- if (!scheme.verify) { return }
-
- const val = this.getValue(`${tableName}.${fieldName}`)
- const verifyResult = this.verify[scheme.verify](val)
-
- if (verifyResult !== true) {
- result.push(`[${scheme.title}]: ${verifyResult}`)
- }
- })
- }
- })
-
- return result
- },
-
- // 获取要提交的表单数据(提交时使用)
- async getPostData(keyValue) {
- const result = {}
-
- for (const [tableName, tableItem] of Object.entries(this.scheme)) {
- if ('__GIRDTABLE__' in tableItem) {
- // 从表
- const tableArray = []
- const tableData = this.current[tableName]
- for (let index = 0; index < tableData.length; ++index) {
- const tableValue = tableData[index]
- const tableObj = {}
- for (const [fieldName, scheme] of Object.entries(tableItem)) {
- if (fieldName === '__GIRDTABLE__') { continue }
- tableObj[fieldName] = await this.convertToPostData(scheme, tableValue[fieldName],tableName,fieldName)
- }
- tableArray.push(tableObj)
- }
- result[`str${tableName}Entity`] = JSON.stringify(tableArray)
-
- } else {
- // 主表
- const strEntity = {}
- for (const [fieldName, scheme] of Object.entries(tableItem)) {
- strEntity[fieldName] = await this.convertToPostData(scheme, this.current[tableName][fieldName],tableName,fieldName)
- }
- result['strEntity'] = JSON.stringify(strEntity)
- }
- }
-
- if (keyValue) {
- result.keyValue = keyValue
- }
-
- return result
- },
-
- newguid() {
- return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
- var r = Math.random() * 16 | 0,
- v = c == 'x' ? r : (r & 0x3 | 0x8);
- return v.toString(16);
- });
- },
-
- // 将单项表单数据转为 post 数据(提交时使用)
- async convertToPostData(scheme, val,tableName,fieldName) {
- switch (scheme.type) {
- case 'checkbox':
- return val ? val.join(',') : ''
-
- case 'datetimerange':
- const startTime = this.getValue(scheme.startTime)
- const endTime = this.getValue(scheme.endTime)
- if (!startTime || !endTime || moment(endTime).isBefore(startTime)) {
- return ''
- } else {
- return moment.duration(moment(endTime).diff(moment(startTime))).asDays().toFixed(0)
- }
-
- case 'datetime':
- return val ? moment(val).format('YYYY-MM-DD HH:mm') : ''
-
- case 'upload':
- // let uploadUid = []
- // console.log(val)
- // for (const entity of val) {
- // if (entity.uid) {
- // uploadUid.push(entity.uid)
- // continue
- // } else {
-
- // const fileId = await this.HTTP_UPLOAD(entity)
- // console.log(fileId)
- // if (fileId) {
- // uploadUid.push(fileId)
- // }
- // }
-
- // }
-
- // console.log(uploadUid.join(','))
- // reject()
- // return uploadUid.join(',')
-
- var uploadUid = '';
-
- let folderIds = uni.getStorageSync('folderIds');
- if(folderIds){
- folderIds = JSON.parse(folderIds)
- if(folderIds[tableName]&&folderIds[tableName][fieldName]){
- uploadUid = folderIds[tableName][fieldName]
- }
- }
- if(!uploadUid){
- uploadUid = this.newguid()
- }
-
- for (const item of val) {
- if (item.uid) {
- // uploadUid = item.uid
- continue
- }
-
- const fileId = await this.HTTP_UPLOAD(item.path || item, undefined, uploadUid)
- if (fileId) {
- uploadUid = fileId;
- }
- }
- return uploadUid;
-
- default:
- return val || ''
- }
- },
-
- // 格式化处理表单数据(拉取时使用)
- async formatFormData(formData) {
- const data = omit(formData, 'keyValue')
- for (const [tableName, schemeItem] of Object.entries(this.scheme)) {
- if ('__GIRDTABLE__' in schemeItem) {
- if (!data[tableName] || data[tableName].length <= 0) { data[tableName] = [{}] }
- const tableData = data[tableName]
-
- for (let index = 0; index < tableData.length; ++index) {
- const tableValue = tableData[index]
-
- for (const [fieldName, scheme] of Object.entries(schemeItem)) {
- if (fieldName === '__GIRDTABLE__') { continue }
- const dataSource = get(this.dataSource, `${tableName}.${fieldName}`)
- tableValue[fieldName] = await this.convertToFormValue(scheme, tableValue[fieldName], dataSource,tableName,fieldName)
- }
- }
- } else {
- for (const [fieldName, scheme] of Object.entries(schemeItem)) {
- const dataSource = get(this.dataSource, `${tableName}.${fieldName}`)
- data[tableName][fieldName] = await this.convertToFormValue(scheme, data[tableName][fieldName], dataSource,tableName,fieldName)
- }
- }
- }
-
- return data
- },
-
- // 将单项表单数据格式化(拉取时使用)
- async convertToFormValue(scheme, val, dataSource,tableName,fieldName) {
- switch (scheme.type) {
- case 'upload':
- // if (!val) { return [] }
- // const uidList = val.split(',')
- // const fileList = []
-
- // for (const uid of uidList || []) {
- // const fileInfo = await this.FETCH_FILEINFO(uid)
- // if (!fileInfo) { continue }
-
- // const fileType = fileInfo.F_FileType
- // const fileSize = fileInfo.F_FileSize
- // const fileName = fileInfo.F_FileName
-
- // const path = this.API + '/learun/adms/annexes/wxdown?' + this.URL_QUERY(uid, true)
- // fileList.push({ path, type: fileType, uid, size: fileSize, name:fileName })
- // }
- // return fileList
- let folderIds = {}
- let getstData = uni.getStorageSync('folderIds');
- if(getstData){
- folderIds = JSON.parse(getstData)
- }
- if(folderIds[tableName]){
- folderIds[tableName][fieldName] = val
- }else{
- let obj = {}
- obj[fieldName] = val
- folderIds[tableName] = obj
- }
- uni.setStorageSync('folderIds',JSON.stringify(folderIds));
-
- if (!val) {
- return []
- }
- const uidList = val;
- const fileList = []
- const wxlist = await this.FETCH_FILEList(uidList);
- for (const wxfile of wxlist) {
- const fileInfo = await this.FETCH_FILEINFO(wxfile.F_Id)
- if (!fileInfo) {
- continue
- }
-
- const fileType = fileInfo.F_FileType
- const fileSize = fileInfo.F_FileSize
- const fileName = fileInfo.F_FileName
-
- const path = this.API + '/learun/adms/annexes/wxdown?' + this.URL_QUERY(wxfile.F_Id, true)
- fileList.push({
- path,
- type: fileType,
- uid:wxfile.F_Id,
- folderId:wxfile.F_FolderId,
- size: fileSize,
- name:fileName
- })
- }
- return fileList
-
- case 'radio':
- case 'select':
- if ((!val&&val!==0) || !dataSource.map(t => t.value).includes(String(val))) { return '' }
- return String(val)
- case 'selectNoMap':
- if (!val) { return '' }
- return String(val)
-
- case 'checkbox':
- if (!val) { return [] }
- const validValue = dataSource.map(t => t.value)
- const checkboxVal = val.split(',') || []
- return checkboxVal.filter(t => validValue.includes(t))
-
- case 'datetime':
- if (!val) { return '' }
- return moment(val).format(
- Number(scheme.dateformat) === 0 || scheme.datetime === 'date' ?
- 'YYYY-MM-DD' :
- 'YYYY-MM-DD HH:mm:ss'
- )
-
- default:
- return val === null || val === undefined ? '' : val
- }
- }
- },
-
- computed: {
- // 验证函数
- verify() {
- return {
- NotNull: t => t.length > 0 || '不能为空',
- Num: t => !isNaN(t) || '须输入数值',
- NumOrNull: t => t.length <= 0 || !isNaN(t) || '须留空或输入数值',
- Email: t => /^[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_]+.[a-zA-Z0-9]+$/.test(t) || '须符合Email格式',
- EmailOrNull: t => t.length <= 0 || /^[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_]+.[a-zA-Z0-9]+$/.test(t) ||
- '须留空或符合Email格式',
- EnglishStr: t => /^[a-zA-Z]*$/.test(t) || '须由英文字母组成',
- EnglishStrOrNull: t => t.length <= 0 || /^[a-zA-Z]*$/.test(t) || '须留空或由英文字母组成',
- Phone: t => /^[+0-9- ]*$/.test(t) || '须符合电话号码格式',
- PhoneOrNull: t => t.length <= 0 || /^[+0-9- ]*$/.test(t) || '须留空或符合电话号码格式',
- Fax: t => /^[+0-9- ]*$/.test(t) || '须符合传真号码格式',
- Mobile: t => /^1[0-9]{10}$/.test(t) || '须符合手机号码格式',
- MobileOrPhone: t => /^[+0-9- ]*$/.test(t) || /^1[0-9]{10}$/.test(t) || '须符合电话或手机号码格式',
- MobileOrNull: t => t.length <= 0 || /^1[0-9]{10}$/.test(t) || '须留空或符合手机号码格式',
- MobileOrPhoneOrNull: t => t.length <= 0 || /^1[0-9]{10}$/.test(t) || /^[+0-9- ]*$/.test(t) ||
- '须留空或符合手机/电话号码格式',
- Uri: t => /^[a-zA-z]+:\/\/[^\s]*$/.test(t) || '须符合网址Url格式',
- UriOrNull: t => t.length <= 0 || /^[a-zA-z]+:\/\/[^\s]*$/.test(t) || '须留空或符合网址Url格式'
- }
- }
- }
- }
|