<template>
	<form  @submit="formSubmit" @reset="formReset">
		<slot />
	</form>	
</template>

<script>
	import bus from '../../utils/bus.js'
	export default {
		name: "z-form",
		props: {
			reportSubmit: {
				type: Boolean,
				default: false
			},
			model: Object,
			rules: Object
		},
		data() {
			return {
				once:false,
			};
		},
		watch: {
			model: {
				deep: true,
				handler: function(newval, oldval) {
					// console.log(newval)
					this.valiateValue();
				}
			},
			rules: {
				deep: true,
				handler: function(newval, oldval) {
				// console.log(newval)
					this.valiateValue();
				}
			},
		},
		mounted() {
			this.valiateValue();
		},
		methods: {
			valiateValue() {
				console.log(this.model)
				bus.$emit('valiate', {model:this.model,rules:this.rules})
			},
			formSubmit(e) {
				this.$emit('submit',e)
			},
			formReset(e) {
				this.$emit('reset',e)
			},
			// 规则校验 
			validate(callback) {
				let vb = true
				//获取表单下所有的子项目，如果显示了提示代表数据输入错误
				let item = this.getItem(this.$children)
				console.log(item)
				for(let i=0 ; i < item.length; ++i){
					item[i].appear=true;
				}
				for(let i = 0; i < item.length; ++i) {
					
					// 对表单下的子组件 form-item 做数据校验
					let bol =  item[i].isError ? false : true
					if(vb && !bol) {
						vb = false
					}
					if(this.msgType != 'in' && !bol) {
						break
					}
				}
				console.log(item)
				callback && callback(vb)
			},
			// 递归遍历子元素 筛选 form-item
			getItem(children,item) {
				item = item || []
				children.forEach(it => {
				
					if(it.$options.name && it.$options.name === 'ZFormItem' ||
					it.$options._componentTag && it.$options._componentTag === 'z-form-item'){
						item.push(it)
					} else if(it.$children.length){
						item = this.getItem(it.$children,item)
					}
				})
				
				return item
			}
			// validate(){
			// 	bus.$on('validateResult',(data)=>{
			// 		console.log(1)
			// 	})
			// 	console.log(this.$slots)
			
			// }
		}
	}
</script>

<style lang="scss">

</style>
