<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' && customerName(item)">
					<view class="card_form_item">
						<u-input v-model="model[`${item.field}`]" :clearable="item.clearable"
							:disabled="item.disabled ? true : false" :placeholder="item.placeholder"></u-input>
						<view class="card_sweep" v-if="['tamperProofLabel','code','drugBarCode'].includes(item.field)"
							@click="sweep(item.field)">
							<u-icon name="scan" size="18px"></u-icon>
							<span>扫一扫</span>
						</view>
						<view class="title_unit" v-if="item.unit">{{item.unit}}</view>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'drugBarCode'">
					<view class="card_form_item">
						<u-input v-model="model[`${item.field}`]" :clearable="item.clearable"
							:disabled="item.disabled ? true : false" :placeholder="item.placeholder">
							<template slot="suffix">
								<u-icon name="scan" size="24" @click="sweep(item.field)"></u-icon>
							</template>
						</u-input>
						<view class="add_cardil">
							<u-button class="custom-style" :loading="addloading" icon="plus"
								@click="sweep(item.field,true)"></u-button>
						</view>
						<!-- <view class="add_card center_in">
							<u-icon name="plus" size="18"></u-icon>
						</view> -->
					</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 == 'selectiveSearch'">
					<view class="card_form_item">
						<view class="card_search_gray frame" @click="changeil(item)" v-if="item.field == 'freezeClaim'">
							<span
								v-if="model[`${item.field}`] && model[`${item.field}`].length">{{getTimeName(model[`${item.field}`])}}</span>
							<span class="title_gray" v-else>{{item.placeholder}}</span>
							<u-icon name="arrow-down" color="#c8c9cc" size="18"></u-icon>
						</view>
						<view class="card_search_gray frame" @click="changeil(item)" v-else>
							<span v-if="model[`${item.field}`]">{{model[`${item.field}`]}}</span>
							<span class="title_gray" v-else>{{item.placeholder}}</span>
							<u-icon name="arrow-down" color="#c8c9cc" size="18"></u-icon>
						</view>
					</view>
				</u-form-item>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'selectil'">
					<view class="card_form_item">
						<u-input :placeholder="item.placeholder" suffixIcon="arrow-down"
							v-model="model[`${item.field}`]" @focus="changeil(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>
				<u-form-item :required="item.required ? true : false" :label="item.label" :prop="item.field"
					v-else-if="item.type == 'switch'">
					<view class="card_form_item">
						<u-switch v-model="model[`${item.field}`]" inactiveColor="#ff4949" activeColor="#13ce66"
							size="20"></u-switch>
					</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="item.fileList1" name="1" multiple :maxCount="10"
							@afterRead="afterRead($event, item)" @delete="deletePic($event, item)"></u-upload>
					</view>
				</u-form-item>
				<div class="card_drug_list" v-else-if="item.type == 'divider' && productData.length > 0">
					<x-productList :list="productData"></x-productList>
				</div>
			</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>
		<!-- 冷冻要求选择 -->
		<u-popup :show="freezeShow" @close="close">
			<view>
				<view class="space_between" style="height: 84rpx;">
					<view class="tittle_freeze gray_font" @click="freezeCancel">取消</view>
					<view class="tittle_freeze blue_font" @click="freezeConfirm">确定</view>
				</view>
				<view class="freeze_content">
					<view class="card_selected_list">
						<!-- <view class="hint_freeze center_in" v-if="selectedData.length == 0">请选择冷冻要求</view> -->
						<view v-for="(item,index) in selectedData" :key="index">
							<u-tag :text="getTagName(item)" closable plain @close="closeFreeze(item)"></u-tag>
						</view>
						<view v-if="tagFlag">
							<input class="input_tag" type="number" :focus="tagFocus" v-model="value"
								@blur="tagBlur"></input>
						</view>
						<view style="margin-top: 20rpx;" v-else>
							<u-tag text="+新增" plain @click="addTagClick"></u-tag>
						</view>
					</view>
					<view class="fontsize_freeze" v-for="(item,index) in freezeList" :key="index"
						@click="freezeSelect(item)">
						<view>{{item.label}}</view>
						<view v-if="item.flag">
							<u-icon name="checkmark" color="#2979ff" size="22"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	export default {
		name: 'x-form',
		props: {
			list: {
				type: Array,
				default () {
					return []
				}
			},
			model: {
				type: Object,
				default () {
					return {}
				}
			},
			rules: {
				type: Object,
				default () {
					return {}
				}
			},
			productData: {
				type: Array,
				default () {
					return []
				}
			},
			// 添加药品加载
			addloading: {
				type: Boolean,
				default () {
					return false
				}
			},
		},
		data() {
			return {
				show: false,
				columns: [],
				fieldType: '',
				fileList1: [],
				freezeShow: false,
				freezeList: [],
				selectedData: [],
				tagFlag: false,
				tagFocus: false,
				value: '',
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			customerName(value) {
				var userInfo = this.$cache.getCache('userInfo')
				if (userInfo.userType == 'customer') {
					if (value.field != 'customerName') {
						if (value.type == 'input') {
							return true
						}
					}
				} else {
					if (value.type == 'input') {
						return true
					}
				}
			},
			change(e) {
				this.columns = []
				this.fieldType = e.field
				this.show = true
				this.$nextTick(() => {
					this.columns.push(e.options)
				})
			},
			// 选择弹窗滚动
			changeil(value) {
				if (value.field == "status") {
					this.columns = []
					this.fieldType = value.field
					this.show = true
					this.$nextTick(() => {
						this.columns.push(value.options)
					})
				} else if (value.field == "freezeClaim") {
					this.freezeList = value.options
					this.freezeList.forEach(item => {
						item.flag = false
					})
					if (this.model.freezeClaim) {
						this.model.freezeClaim.forEach(event => {
							this.freezeList.filter(item1 => {
								if (item1.value == event) {
									item1.flag = true
								}
							})
						})
					}
					this.selectedData = JSON.parse(JSON.stringify(this.model.freezeClaim))
					this.freezeShow = true
				} else {
					this.$emit('selector', value)
				}
			},
			// 选择确定
			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 afterRead(event, each) {
				this.list.forEach(async item1 => {
					if (item1.field == each.field) {
						// item1.fileList1 = this.fileList1
						// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
						let lists = [].concat(event.file)
						let fileListLen = item1.fileList1.length
						lists.map((item) => {
							item1.fileList1.push({
								...item,
								status: 'uploading',
								message: '上传中'
							})
						})
						uni.showLoading({
							title: '上传中',
							mask: true,
						})
						for (let i = 0; i < lists.length; i++) {
							const result = await this.uploadFilePromise(lists[i].url)
							let item = item1.fileList1[fileListLen]
							item1.fileList1.splice(fileListLen, 1, Object.assign(item, {
								status: 'success',
								message: '',
								url: result
							}))
							fileListLen++
						}
						var arr = []
						item1.fileList1.forEach(item1 => {
							arr.push(item1.url)
						})
						uni.hideLoading();
						if (each.field == 'prescription') {
							this.model[each.field] = arr
							this.$refs.uForm.validateField(each.field)
						} else {
							this.model[each.field] = arr.join()
							this.$refs.uForm.validateField(each.field)
						}
					}
				})
			},
			// 删除图片
			deletePic(event, each) {
				this.list.forEach(async item1 => {
					if (item1.field == each.field) {
						item1.fileList1.splice(event.index, 1)
						var arr = []
						item1.fileList1.forEach(item1 => {
							arr.push(item1.url)
						})
						uni.hideLoading();
						if (each.field == 'prescription') {
							this.model[each.field] = arr
						} else {
							this.model[each.field] = arr.join()
						}
					}
				})
			},
			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)
								}
							}, 100)
						}
					});
				})
			},
			// 扫一扫
			sweep(field, flag) {
				if (flag) {
					if (!this.addloading && field == "drugBarCode") {
						if (this.model[field]) {
							this.$emit('getSweep', this.model[field])
						} else {
							uni.$u.toast('请先输入药品条形码')
						}
					}
				} else {
					// 允许从相机和相册扫码
					uni.scanCode({
						scanType: ['barCode', 'qrCode'],
						autoZoom: false,
						success: (res) => {
							if (res.result) {
								let url = res.result;
								if (field == "drugBarCode") {
									this.$emit('getSweep', url)
								}
								this.model[field] = url
							} else {
								console.log('请重新扫描');
								return false;
							}
						},
						fail: (res) => {
							console.log('未识别到二维码1');
						}
					})
				}
			},
			//子组件校验，传递到父组件
			async validateForm() {
				let flag = null
				await this.$refs.uForm.validate(valid => {}).then(res => {
					flag = true
				}).catch(err => {
					flag = false
				})
				return flag
			},
			// 选择冷冻时间
			freezeSelect(event) {
				this.freezeList.forEach(item => {
					if (item.value == event.value) {
						if (item.flag) {
							item.flag = false
						} else {
							item.flag = true
						}
					}
				})
				if (event.flag) {
					this.selectedData.push(event.value)
				} else {
					function removeElement(arr, element) {
						return arr.filter(function(item) {
							return item !== element;
						});
					}
					this.selectedData = removeElement(this.selectedData, event.value)
				}
				this.$forceUpdate()
			},
			// 获取选择名称
			getTagName(event) {
				let name
				let index = this.freezeList.findIndex((item) => item.value === event);
				// 如果有就替换，没有就添加
				if (index !== -1) {
					let arr1 = this.freezeList.find(item1 => {
						return item1.value === event;
					});
					if (arr1) {
						name = arr1.label
					}
				} else {
					name = event
				}
				return name
			},
			// 数组展示
			getTimeName(event) {
				var arr = event.join(' , ')
				return arr
			},
			// 删除选择项
			closeFreeze(event) {
				this.freezeList.forEach(item => {
					if (item.value == event) {
						item.flag = false
					}
				})
				this.selectedData = this.selectedData.filter(item => item !== event);
			},
			// 新增选择项
			addTagClick() {
				this.tagFlag = true
				this.tagFocus = true
			},
			// 失去焦点
			tagBlur(event) {
				var arr = {
					value: Number(this.value),
				}
				this.freezeSelect(arr)
				if (!this.value) {
					this.tagFlag = false
				} else {
					var arr1 = this.value.split('小时')
					this.selectedData.push(Number(arr1[0]))
					this.value = ''
					this.tagFlag = false
				}
				this.selectedData = this.uniqueArray(this.selectedData)
			},
			// 去重
			uniqueArray(arr) {
				return [...new Set(arr)];
			},
			// 单个表单验证
			formValidation(event) {
				this.$refs['uForm'].validateField(event)
			},
			// 取消
			freezeCancel() {
				this.freezeShow = false
			},
			// 确定
			freezeConfirm() {
				this.model.freezeClaim = this.selectedData
				this.freezeShow = false
			},
			close() {
				this.freezeShow = false
			}
		},
	}
</script>

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

	.card_sweep {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 70rpx;
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		margin-left: 10rpx;

		span {
			margin: 0rpx 10rpx;
			display: flex;
			font-size: 22rpx;
		}
	}

	.card_search_gray {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		flex: 1;
		padding: 12rpx 18rpx;
		border-radius: 8rpx;
		line-height: 48rpx;
	}

	.title_gray {
		font-size: 30rpx;
		color: #c8c9cc;
	}

	.gray_font {
		color: #c8c9cc;
	}

	.blue_font {
		color: #3c9cff;
	}

	// 伪元素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;
		pointer-events: none;
		/* 使伪元素不会阻止鼠标事件 */
	}

	.card_drug_list {
		border-radius: 10rpx;
		border-top: 1px solid #f4f4f5;
		// box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, .12),
	}

	.tittle_freeze {
		padding: 0px 30rpx;
	}

	.freeze_content {
		position: relative;
		padding: 100rpx 0rpx;
	}

	.card_selected_list {
		position: absolute;
		top: 20rpx;
		left: 0;
		right: 0;
		border-bottom: 1rpx solid #f4f4f5;
		display: flex;
		align-items: center;
		justify-content: center;
		padding-bottom: 20rpx;
	}

	.hint_freeze {
		color: #909399;
		height: 74rpx;
		font-size: 30rpx;
	}

	.fontsize_freeze {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 50rpx;
	}

	.add_card {
		margin-left: 10rpx;
		width: 40rpx;
		height: 46rpx;
		border-radius: 8rpx;
		padding: 6px 9px;
		border: 1px solid #dadbde;
	}

	.add_cardil {
		display: flex;
		margin-left: 10rpx;
	}

	.input_tag {
		width: fit-content;
		width: -webkit-fit-content;
		width: -moz-fit-content;
		width: 70rpx;
		min-width: 50rpx;
		margin-top: 20rpx;
		padding: 0rpx 20rpx;
		height: 52rpx;
		border-radius: 6rpx;
		border: 1rpx solid #dadbde;
		font-size: 26rpx;
		text-align: center;
	}

	.title_unit {
		display: flex;
		align-items: center;
		margin-left: 10rpx;
	}
</style>