<template>
	<view class="dynamicModel-form-v jnpf-wrap jnpf-wrap-form" v-if="showPage">
		<jnpf-parser :formConf="formConf" ref="dynamicForm" v-if="!loading" @submit="sumbitForm" :key="key" />
		<view class="buttom-actions" v-if="btnType === 'btn_edit' || btnType === 'btn_add'">
			<u-button class="buttom-btn" :loading="btnLoading" @click="showAction = true"
				v-if="formConf.hasConfirmAndAddBtn">
				更多<u-icon name="arrow-down" size="24"></u-icon>
			</u-button>
			<u-button class="buttom-btn" type="primary" @click.stop="submit" :loading="btnLoading">
				{{formConf.confirmButtonText||'确定'}}
			</u-button>
			<u-button class="buttom-btn" @click.stop="jnpf.goBack">{{formConf.cancelButtonText||'取消'}}</u-button>
		</view>
		<u-action-sheet @click="handleAction" :list="actionList" :tips="{ text: '更多操作' , color: '#000' , fontSize: 30 }"
			v-model="showAction">
		</u-action-sheet>
	</view>
</template>
<script>
	import {
		getConfigData,
		createModel,
		updateModel,
		getModelInfo
	} from '@/api/apply/visualDev'
	export default {
		data() {
			return {
				actionList: [],
				actionListLength: false,
				showAction: false,
				webType: '',
				showPage: false,
				btnLoading: false,
				loading: true,
				isPreview: '0',
				modelId: '',
				formConf: {},
				formData: {},
				dataForm: {
					id: '',
					data: ''
				},
				btnType: '',
				formPermissionList: {},
				formList: [],
				key: +new Date(),
				config: {},
				clickType: 'submit',
				prevDis: false,
				nextDis: false,
				index: 0,
				userInfo: {},
				isAdd: false
			}
		},
		onLoad(option) {
			this.userInfo = uni.getStorageSync('userInfo') || {}
			this.config = JSON.parse(this.base64.decode(option.config))
			this.index = this.config.index
			this.formPermissionList = !this.config.currentMenu ? [] : JSON.parse(decodeURIComponent(this.config
				.currentMenu))
			this.formList = this.formPermissionList.formList
			this.btnType = this.config.jurisdictionType || ''
			this.modelId = this.config.modelId;
			this.isPreview = this.config.isPreview || '0';
			this.dataForm.id = this.config.id || ''
			uni.setNavigationBarTitle({
				title: this.dataForm.id ? '编辑' : '新建'
			})
			this.getConfigData()
		},
		onBackPress() {
			uni.$emit('refresh')
		},
		methods: {
			handleAction(index) {
				if (this.actionList[index].id === 'save_add' || this.actionList[index].id === 'save_proceed') {
					this.commonSubmit(this.actionList[index].id)
				} else {
					this.calculation(this.actionList[index].id, index)
				}
			},
			calculation(type, index) {
				if (type === 'upper') {
					this.index--
					this.actionList[index + 1].disabled = false
					if (this.index == 0) this.actionList[index].disabled = true
				} else {
					this.index++
					this.actionList[index - 1].disabled = false
					if (this.index == this.config.list.length - 1) this.actionList[index].disabled = true
				}
				this.dataForm.id = this.config.list[this.index].id
				this.getConfigData()
			},
			getConfigData() {
				getConfigData(this.modelId).then(res => {
					if (res.code !== 200 || !res.data) {
						uni.showToast({
							title: '暂无此页面',
							icon: 'none',
							complete: () => {
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							}
						})
						return
					}
					this.formConf = res.data.formData ? JSON.parse(res.data.formData) : {};
					this.actionList = []
					if (this.formConf.hasConfirmAndAddBtn) {
						if (!this.dataForm.id) {
							this.actionList.push({
								text: '确定并新增',
								id: 'save_add'
							})
						} else {
							this.actionList.push({
								text: '上一条',
								id: 'upper',
								disabled: false
							}, {
								text: '下一条',
								id: 'lower',
								disabled: false
							}, {
								text: '确定并继续',
								id: 'save_proceed'
							})
						}
					}
					this.showPage = true
					this.initData()
				})
			},
			initData() {
				this.$nextTick(() => {
					if (this.dataForm.id) {
						this.actionList.map(o => {
							if (this.index == 0 && o.id === 'upper') {
								o.disabled = true
							}
							if (this.index == this.config.list.length - 1 && o.id === 'lower') {
								o.disabled = true
							}
						})
						let extra = {
							modelId: this.modelId,
							id: this.dataForm.id,
							type: 2
						}
						uni.setStorageSync('dynamicModelExtra', extra)
						getModelInfo(this.modelId, this.dataForm.id).then(res => {
							this.dataForm = res.data
							if (!this.dataForm.data) return
							this.formData = {
								...JSON.parse(this.dataForm.data),
								id: this.dataForm.id
							}
							this.fillFormData(this.formConf, this.formData)
							this.$nextTick(() => {
								this.loading = false
							})
						})
					} else {
						this.isAdd = true
						uni.setStorageSync('dynamicModelExtra', {})
						this.formData = {}
						this.loading = false
						this.fillFormData(this.formConf, this.formData)
					}
					this.key = +new Date()
				})
			},
			fillFormData(form, data) {
				this.key = +new Date()
				const loop = (list, parent) => {
					for (let i = 0; i < list.length; i++) {
						let item = list[i]
						if (item.__vModel__) {
							let val = data.hasOwnProperty(item.__vModel__) ? data[item.__vModel__] : item.__config__
								.defaultValue
							if (!item.__config__.isSubTable) item.__config__.defaultValue = val
							if (this.isAdd || item.__config__.isSubTable) { //新增时候，默认当前
								if (item.__config__.defaultCurrent) {
									if (item.__config__.jnpfKey === 'datePicker') {
										if (!data.hasOwnProperty(item.__vModel__)) {
											let format = this.jnpf.handelFormat(item.format)
											let dateStr = this.jnpf.toDate(new Date().getTime(), format)
											let time = format === 'yyyy' ? '-01-01 00:00:00' : format === 'yyyy-MM' ?
												'-01 00:00:00' : format === 'yyyy-MM-dd' ?
												' 00:00:00' : ''
											val = new Date(dateStr + time).getTime()
											item.__config__.defaultValue = val
										}
									}
									if (item.__config__.jnpfKey === 'timePicker') {
										if (!data.hasOwnProperty(item.__vModel__)) {
											val = this.jnpf.toDate(new Date(), item.format)
											item.__config__.defaultValue = val
										}
									}
									if (item.__config__.jnpfKey === 'organizeSelect' && (this.userInfo
											.organizeIdList instanceof Array && this.userInfo.organizeIdList.length > 0
										)) {
										item.__config__.defaultValue = item.multiple ? [this.userInfo.organizeIdList] :
											this.userInfo.organizeIdList
									}
									if (item.__config__.jnpfKey === 'depSelect' && this.userInfo.departmentId) {
										item.__config__.defaultValue = item.multiple ? [this.userInfo.departmentId] :
											this.userInfo.departmentId;
									}
									if (item.__config__.jnpfKey === 'posSelect' && (this.userInfo
											.positionIds instanceof Array && this.userInfo.positionIds.length > 0)) {
										item.__config__.defaultValue = item.multiple ? this.userInfo.positionIds.map(
											o => o.id) : this.userInfo.positionIds[0].id
									}
									if (item.__config__.jnpfKey === 'roleSelect' && (this.userInfo
											.roleIds instanceof Array && this.userInfo.roleIds.length > 0)) {
										item.__config__.defaultValue = item.multiple ? this.userInfo.roleIds : this
											.userInfo.roleIds[0];
									}
									if (item.__config__.jnpfKey === 'groupSelect' && (this.userInfo
											.groupIds instanceof Array && this.userInfo.groupIds.length > 0)) {
										item.__config__.defaultValue = item.multiple ? this.userInfo.groupIds : this
											.userInfo.groupIds[0];
									}
								}
							}
							const btn_detail = this.$setPermission.hasBtnP('btn_detail', this.formPermissionList
								.menuId)
							const btn_edit = this.$setPermission.hasBtnP('btn_edit', this.formPermissionList
								.menuId)
							if (!!this.dataForm.id && !btn_edit && !btn_detail) {
								item.disabled = btn_detail
							}
							let noShow = !item.__config__.noShow ? false : item.__config__.noShow
							let isVisibility = false
							if (!item.__config__.visibility || (Array.isArray(item.__config__.visibility) && item
									.__config__.visibility.includes('app'))) isVisibility = true
							this.$set(item.__config__, 'isVisibility', isVisibility)
							if (this.formPermissionList.useFormPermission) {
								let id = item.__config__.isSubTable ? parent.__vModel__ + '-' + item.__vModel__ :
									item
									.__vModel__
								noShow = true
								if (this.formList && this.formList.length) {
									noShow = !this.formList.some(o => o.enCode === id)
								}
								noShow = item.__config__.noShow ? item.__config__.noShow : noShow
								this.$set(item.__config__, 'noShow', noShow)
							}
						} else {
							let noShow = item.__config__.noShow ? item.__config__.noShow : false,
								isVisibility = false
							if (!item.__config__.visibility || (Array.isArray(item.__config__.visibility) && item
									.__config__.visibility.includes('app'))) isVisibility = true
							this.$set(item.__config__, 'isVisibility', isVisibility)
							this.$set(item.__config__, 'noShow', noShow)
						}
						if (item.__config__ && item.__config__.children && Array.isArray(item.__config__
								.children)) {
							loop(item.__config__.children, item)
						}
					}
				}
				loop(form.fields)
				form.formData = data
				this.key = +new Date()
			},
			sumbitForm(data, callback) {
				if (!data) return
				this.btnLoading = true
				const formData = {
					...this.formData,
					...data
				}
				this.dataForm.data = JSON.stringify(formData)
				if (callback && typeof callback === "function") callback()
				const formMethod = this.dataForm.id ? updateModel : createModel
				formMethod(this.modelId, this.dataForm).then(res => {
					uni.showToast({
						title: res.msg,
						complete: () => {
							setTimeout(() => {
								if (this.clickType == 'save_add') {
									this.key = +new Date()
									this.$nextTick(() => {
										this.$refs.dynamicForm && this
											.$refs
											.dynamicForm.resetForm()
									})
								}
								this.btnLoading = false
								this.initData()
								if (this.clickType != 'save_proceed' && this
									.clickType !=
									'save_add') {
									uni.navigateBack()
								}
							}, 1500)
						}
					})
				}).catch(() => {
					this.btnLoading = false
				})
			},
			commonSubmit(type) {
				this.clickType = type
				this.submit(type)
			},
			submit(type) {
				this.clickType = type
				if (this.isPreview == '1') {
					uni.showToast({
						title: '功能预览不支持数据保存',
						icon: 'none'
					})
					return
				}
				this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f0f2f6;
	}

	.dynamicModel-form-v {}
</style>