<template>
	<el-form-item :label="keys._name || '数据表格'">
		<el-table :data="value" border style="width: 100%;" size="mini" max-height="400">
			<el-table-column
			      type="index"
			      width="50"
				  label="序号">
			    </el-table-column>
			<el-table-column v-for="(x, index) in headers" :label="x.name" :key="index" min-width="100">
				<template slot-scope="scope">
					<el-input v-model="scope.row[index].value"></el-input>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="100">
				<template slot-scope="scope">
					<el-button v-if="scope.$index > 0" type="danger" icon="el-icon-delete" circle @click="value.splice(scope.$index,1)"></el-button>
					<el-button type="primary" icon="el-icon-plus" circle @click="add(scope.$index)"></el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-form-item>
</template>

<script>
export default {
	name: 'tplTabArray',
	props: {
		value: {
			type: Array,
			default() {
				return [];
			}
		},
		keys: {
			type: Object,
			default() {
				return {};
			}
		},
		headers: {
			type: Array,
			default() {
				return [];
			}
		},
		changeData:{
			type:Object,
			default(){
				return {};
			}
		}
	},
	data(){
		return {
			itemKey:this.value[0] || {}
		}
	},
	watch: {
		//监听检测哪一项发生变化了
		headers(n){
			const {index,type} = this.changeData;
			switch(type){
				case "add":
					this.value.map((x,i)=>{
						this.value[i].splice(index+1, 0, {...this.keys});
					});
				break;
				case "del":
					this.value.map((x,i)=>{
						this.value[i].splice(index,1);
					});
				break;
			}
		}
	},
	methods:{
		add(index){
			const {length} = this.value,
			obj = JSON.parse(JSON.stringify({...(this.value[index] || this.itemKey),id:Math.random()+""}));
			length && this.value.splice(index+1,0,obj);
		}
	}
};
</script>
