<template>
	<!-- 表单 -->
	<view style="margin: 0rpx 20rpx 0rpx 30rpx;">
		<u--form :model="model" :rules="rules" labelPosition="left" ref="uForm" labelWidth="70">
			<view v-for="(item,index) in list" :key="index">
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-if="item.type == 'input'">
					<view class="card_form_item">
						<u--input v-model="model[`${item.field}`]" :disabled="item.disabled ? true : false"
							:placeholder="item.placeholder"></u--input>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'select'">
					<view class="card_form_item">
						<u--input :placeholder="item.placeholder" suffixIcon="arrow-down"
							v-model="model[`${item.field}`]" @focus="change(item)"></u--input>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'textarea'">
					<view class="card_form_item">
						<u--textarea v-model="model[`${item.field}`]" autoHeight
							:placeholder="item.placeholder"></u--textarea>
					</view>
				</u-form-item>
			</view>
		</u--form>
		<u-picker :defaultIndex="findIndex(model[fieldType], columns[0])" :show="show" :columns="columns"
			keyName="label" @confirm="confirm($event, fieldType)" @cancel="cancel"></u-picker>
	</view>
</template>

<script>
	export default {
		name: 'x-form',
		props: {
			list: {
				type: Array,
				default () {
					return []
				}
			},
			model: {
				type: Object,
				default () {
					return {}
				}
			},
			rules: {
				type: Object,
				default () {
					return {}
				}
			},
		},
		data() {
			return {
				show: false,
				columns: [],
				fieldType: '',
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			change(e) {
				this.columns = []
				this.fieldType = e.field
				this.show = true
				this.$nextTick(() => {
					this.columns.push(e.options)
				})
			},
			// 选择确定
			confirm(value, type) {
				this.show = false
				this.model[type] = value.value[0].label
			},
			// 点击确定
			cancel() {
				this.show = false
			},
			findIndex(code, list) {
				if (!code || !list) {
					return [0]
				}
				return [list.findIndex((item) => (item.label === code || item.label === code))]
			},
			//子组件校验，传递到父组件
			async validateForm() {
				let flag = null
				await this.$refs.uForm.validate(valid => {}).then(res => {
					flag = true
				}).catch(err => {
					flag = false
				})
				return flag
			}
		},
	}
</script>

<style lang="scss">
	.card_form_item {
		width: 100%;
	}
</style>