<template>
	<view>
		<u-form labelPosition="top" labelWidth="auto" :model="model" :rules="rules" ref="uForm">
			<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' && !item.visible">
					<view class="card_form_item">
						<u-input v-model="model[`${item.field}`]" :disabled="item.disabled ? true : false"
							:type="item.genre || 'text'" :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 == 'radio' && !item.visible">
					<view class="card_form_item" style="margin-top: 10rpx;">
						<u-radio-group v-model="model[`${item.field}`]" placement="row">
							<u-radio shape="circle" :customStyle="{marginRight: '20px'}"
								v-for="(item1, index2) in item.options" :key="index2" :label="item1.label"
								:name="item1.value"></u-radio>
						</u-radio-group>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'cascader' || item.type == 'select' && !item.visible">
					<view class="card_selector frame" @click="change(item)">
						<span style="color: #303133;" v-if="model[`${item.field}`]">{{model[`${item.field}`]}}</span>
						<span v-else>{{item.placeholder}}</span>
						<u-icon name="arrow-down"></u-icon>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'upload' && !item.visible">
					<view class="card_form_item">
						<u-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
							@delete="deletePic"></u-upload>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'textarea' && !item.visible">
					<view class="card_form_item">
						<u--textarea v-model="model[`${item.field}`]" autoHeight
							:placeholder="item.placeholder"></u--textarea>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'line' && !item.visible">
					<view class="card_form_item">
						<u-line></u-line>
					</view>
				</u-form-item>
				<u-form-item labelPosition="left" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'default' && !item.visible">
					<view class="card_form_item" style="display: flex;justify-content: flex-end">
						<u-switch v-model="model[`${item.field}`]" inactiveColor="rgb(230, 230, 230)"
							size="20"></u-switch>
					</view>
				</u-form-item>
			</view>
		</u-form>
		<u-picker :show="singleShow" :columns="columns" :defaultIndex="downIndex" keyName="label"
			@cancel="singleShow = false" @confirm="confirmEnsure"></u-picker>
		<u-picker :show="show" ref="uPicker" :columns="addressColumns" :defaultIndex="areaDetault" keyName="label"
			@confirm="confirm" @change="changeHandler" @cancel="cancel"></u-picker>
		<view style="width: 100%;height: 170rpx;"></view>
		<view class="check_btn">
			<view class="btn_submit">
				<u-button type="primary" :loading="loading" :text="btnTitle" @click="clientele"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	import {
		urbanArea
	} from '@/static/js/districtCode.js'
	export default {
		name: 'x-form',
		props: {
			list: {
				type: Array,
				default () {
					return []
				}
			},
			model: {
				type: Object,
				default () {
					return {}
				}
			},
			rules: {
				type: Object,
				default () {
					return {}
				}
			},
			userType: {
				type: Number,
				default () {
					return null
				}
			},
			btnTitle: {
				type: String,
				default () {
					return '提交'
				}
			},
			loading: {
				type: Boolean,
				default () {
					return false
				}
			}
		},
		data() {
			return {
				singleShow: false,
				show: false,
				areaData: urbanArea(), //原始数据
				addressColumns: [], //数据数组
				areaDetault: [], //默认选中数据
				fileList1: [],
				columns: [],
				fieldType: '',
				downIndex: [],
			}
		},
		mounted() {},
		methods: {
			change(value) {
				this.fieldType = value.field
				if (value.type == 'cascader') {
					this.show = true
					this.addressColumns = [
						this.areaData,
						this.areaData[0].children,
					];
					this.$nextTick(() => {
						if (this.model.hr) {
							this.setDefault()
						}
					})
				} else {
					this.downIndex = []
					let orderId = null
					if (value.field == 'commodity') {
						orderId = this.model.goodsId
					} else if (value.field == 'specification') {
						orderId = this.model.specId
					}
					value.options[0].forEach((item, index) => {
						if (item.value == orderId) {
							this.downIndex.push(index)
						}
					})
					this.columns = value.options
					this.singleShow = true
				}
			},
			confirmEnsure(value) {
				const param = {
					id: value.value[0].value,
					type: this.fieldType,
				}
				this.model[this.fieldType] = value.value[0].label
				this.singleShow = false
				this.$emit('confirmEnsure', param)
			},
			confirm(value) {
				let arr = value.value
				let arr1 = []
				let arr2 = []
				arr.forEach(item => {
					arr1.push(item.value)
					arr2.push(item.label)
				})
				this.model.hr = arr1.join('/')
				this.model.region = arr2.join('/')
				this.show = false
				this.$emit('confirm', value)
			},
			cancel() {
				this.show = false
			},
			// 补全客户资料
			clientele() {
				this.$refs.uForm.validate().then(res => {
					this.$emit('clientele')
				}).catch(errors => {
					// uni.$u.toast('校验失败')
				})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				var arr = []
				this.fileList1.forEach(item1 => {
					arr.push(item1.url)
				})
				this.model.addressImg = arr.join()
				this.$refs.uForm.validateField('addressImg')
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: ENV.APP_DEV_URL + '/api/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						// formData: {
						// 	user: 'test'
						// },
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
						},
						success: (res) => {
							let state = JSON.parse(res.data)
							setTimeout(() => {
								if (state.code == 200) {
									resolve(state.data)
								}
							}, 1000)
						}
					});
				})
			},
			// 根据回显数据设置默认选中项
			setDefault() {
				// 户籍所在地
				let temp = []
				temp = this.model.hr.split('/')
				let index, index1 = 0
				let arr, arr1 = []
				//市区对应每列的第几个
				this.areaData.forEach((item, i) => {
					if (item.value == temp[0]) {
						index = i
						item.children.forEach((val, ind) => {
							if (val.value == temp[1]) {
								index1 = ind
							}
						})
					}
				})
				//匹配省市区对应每列的第几个
				arr = this.areaData.map(e => {
					return e
				})
				arr1 = this.areaData[index].children.map(e => {
					return e
				})
				this.addressColumns = [arr, arr1]
				this.areaDetault = [index, index1]
			},
			// 选中时执行
			changeHandler(e) {
				const {
					columnIndex,
					index,
					indexs,
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					const children1 = this.areaData[index].children.map(e1 => {
						return e1
					})
					picker.setColumnValues(1, children1)
					if (columnIndex === 1) {
						const children3 = this.areaData[indexs[0]].children[indexs[1]].children.map(e2 => {
							return e2
						})
						picker.setColumnValues(2, children3)
					}
				}
			},
		}
	}
</script>

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

	.check_btn {
		z-index: 2024;
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: center;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		border-top: 1rpx solid #f7f7f7;
		padding-bottom: constant(safe-area-inset-bottom); //兼容 IOS<11.2
		padding-bottom: env(safe-area-inset-bottom); //兼容 IOS>11.2
	}

	.btn_submit {
		margin-top: 10rpx;
		padding-bottom: 20rpx;
		width: calc(100% - 80rpx);
	}

	.card_selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		padding: 6px 9px;
		border-radius: 8rpx;
		color: rgb(192, 196, 204);
		font-size: 28rpx;
		line-height: 42rpx;
	}
	
	// 伪元素1rpx边框
	.frame {
		position: relative; //重要
	}
	.frame::after {
		position: absolute;
		content: '';
		border: 2rpx solid #e7e6e4;
		border-radius: 16rpx;
		width: 200%;
		height: 200%;
		top: 0;
		left: 0;
		transform: scale(0.5);
		transform-origin: 0 0;
	}
</style>