<template>
	<view class="w-table" :key="_value.length">
		<uni-collapse ref="collapse" v-model="opened">
			<uni-collapse-item :show-animation="true" class="w-table-row" v-for="(row, i) in _value" :key="`row_${i}`">
				<template v-slot:title>
					<view class="w-table-row-tt">
						<view style="display: flex; flex: 1; align-items: center;">
							<text style="padding: 8px 15px;">第 {{i+1}} 项</text>
							<uni-icons v-if="errRow.has(i)" type="info" :size="20" color="#CE5266"></uni-icons>
						</view>
						<view @click.stop="delTbRow(i)" style="color: #999999;" v-if="!readonly">删除</view>
					</view>

				</template>
				<uni-forms :ref="`wflowTableForm_${i}`" :rules="rules" :modelValue="_value[i]" label-position="top"
					label-width="200">
					<uni-forms-item class="w-form-item" v-for="col in formProps.columns" :name="col.id" :key="col.id"
						:required="col.props.required">
						<template v-slot:label>
							<view style="display: flex; align-items: center; padding: 13rpx 0;">
								<text style="color: #CE5266;" v-if="col.props.required">* </text>
								<text style="font-size: 32rpx;">{{col.title}}</text>
							</view>
						</template>
						<w-form-item :type="col.name" v-model="_value[i][col.id]" :form-props="col.props"
							:readonly="col.perm !== 'E'" :formData="formData" :index="i+ 1" />
					</uni-forms-item>
				</uni-forms>
			</uni-collapse-item>
		</uni-collapse>
		<view class="w-table-add" @click="addRow" v-if="!readonly">+ 添加明细</view>
	</view>
</template>

<script>
	export default {
		name: 'TableList',
		props: {
			modelValue: { //表单双向绑定的值
				type: Array,
				default: () => {
					return []
				}
			},
			formData: { //表单值
				type: Object,
				default: () => {
					return {}
				}
			},
			formProps: { //表单联动相关配置
				type: Object,
				default: () => {
					return {}
				}
			},
			readonly: Boolean,

		},
		computed: {
			_value: {
				get() {
					return this.modelValue
				},
				set(val) {
					this.$emit('update:modelValue', val)
				}
			},
			rules() {
				const formRule = {}
				this.formProps.columns.forEach(v => {
					formRule[v.id] = {
						rules: [{
							required: v.props.required,
							errorMessage: '请填写' + v.title
						}]
					}
				})
				return formRule
			}
		},
		data() {
			return {
				opened: [],
				errRow: new Set()
			}
		},
		//// #ifdef MP
		mounted() {
			this.$nextTick(() => {
				this.$refs.collapse.resize()
				uni.$emit('showFp')
			})
		},
		//// #endif
		methods: {
			validate(call) {
				//校验表格所有行数据
				const valids = []
				this._value.forEach((v, i) => {
					valids.push(new Promise((resolve) => {
						//对表格数据进行循环校验
						const formRef = this.$refs[`wflowTableForm_${this._value.length - 1}`]
						formRef[0].validate().then(res => {
							this.errRow.delete(i)
							resolve(true)
						}).catch(err => {
							//展开所有错误的行
							if (this.opened.indexOf(i) < 0) {
								this.opened.push(i)
							}
							this.errRow.add(i)
							resolve(false)
						})
					}))
				})
				if (valids.length > 0) {
					Promise.all(valids).then((results) => {
						// 检查结果所有校验都成功为true
						const isSuccess = results.every((valid) => valid === true);
						call(isSuccess)
					})
				}
			},
			addRow() {
				if (this._value.length > 0) {
					const formRef = this.$refs[`wflowTableForm_${this._value.length - 1}`]
					//校验上一行表单
					this.validate(valid => {
						if (valid) {
							this.doAddRow()
						} else {
							uni.showToast({
								icon: 'none',
								title: '请完成之前的数据'
							})
						}
					})
				} else {
					this.doAddRow()
				}
			},
			delTbRow(i) {
				uni.showModal({
					title: '提示',
					content: '确定要删除当前表格行数据吗？',
					success: (res) => {
						if (res.confirm) {
							this._value.splice(i, 1)
							this._value = this._value
							setTimeout(() => uni.$emit('showFp'), 500)
						}
					}
				});
			},
			doAddRow() {
				if ((this.formProps.maxSize || 0) > 0 && this.formProps.columns.length >= this.formProps.maxSize) {
					uni.showToast({
						icon: 'none',
						title: '已达到限制行数'
					})
					return
				}
				const row = {}
				this.formProps.columns.forEach(v => row[v.id] = null)
				this._value.push(row)
				this._value = this._value
				this.$forceUpdate()
				setTimeout(() => uni.$emit('showFp'), 500)
			}
		},
		watch: {
			opened: {
				deep: true,
				handler() {
					setTimeout(() => uni.$emit('showFp'), 500)
				}
			}
		},
		emits: ['update:modelValue']
	}
</script>

<style lang="less" scoped>
	.w-table {
		//background-color: #F4F5F7;
	}

	.w-table-add {
		display: flex;
		color: #4478F7;
		justify-content: center;
		align-items: center;
		padding-top: 5px;
	}

	:deep(.w-table-row) {
		.w-table-row-tt {
			display: flex;
			align-items: center;
			
			&>view:first-child {
				flex: 1;
			}
			
			&>view:last-child {
				
			}
		}
		
		.uni-collapse-item__title-box {
			height: 35px;
			line-height: 35px;
			background-color: #f8f9fa;
		}

		.uni-collapse-item__title {
			border-bottom: 2px solid white;
			background-color: #f8f9fa;
			border-radius: 5px;

			.uni-collapse-item__title-wrap {
				display: flex;
				align-items: center;
				margin-right: 10px;
			}
		}

		.uni-collapse-item__wrap-content.uni-collapse-item--border {
			border-bottom-color: white;
		}

		.w-form-item {
			border-bottom: 2px solid #F8F9FA;
			margin-bottom: 0;
		}

		.w-form-item:last-child {
			border-bottom: none;
		}
	}
</style>