<template>
	<el-form-item :label="keys._name || label">
		<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="(name, prop) in keys" :label="name" v-if="prop != '_name'" :key="prop" min-width="100">
				<template slot-scope="scope">
					<el-switch v-if="includes(scope.row[prop], 'Boolean')" v-model="scope.row[prop]"></el-switch>
					<el-color-picker v-else-if="prop == 'color'" v-model="scope.row[prop]"></el-color-picker>
					<template v-else>
						<el-input v-model="scope.row[prop]"></el-input>
					</template>
				</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="del(scope.$index)"></el-button>
					<el-button type="primary" icon="el-icon-plus" circle @click="add(scope.$index)"></el-button>
				</template>
			</el-table-column>
			<template slot="empty">
				<el-button type="primary" @click="add(-1)">新增</el-button>
			</template>
		</el-table>
	</el-form-item>
</template>

<script>
import md5 from 'md5';
export default {
	name: 'tplArray',
	props: {
		value: {
			type: Array,
			default() {
				return {};
			}
		},
		keys: {
			type: Object,
			default() {
				return {};
			}
		},
		label:{
			type: String,
			default() {
				return "数据集";
			}
		}
	},
	data() {
		return {};
	},
	methods: {
		add(index) {
			this.$emit('change', {
				keys: this.keys,
				index,
				type: 'add'
			});
			//如果数据其他项没有ID 则取下标作为ID
			let newId = [],
				time = new Date().getTime()+Math.random();
			this.value.map((x, i) => {
				const id = x.id || (x.id + '' == 'undefined' ? false : x.id + ''),
					_id = md5(`${i}${time}`);
				id || (this.value[i].id = _id);
				newId.push(this.value[i].id);
				//处理菜单
				x.path && (this.value[i].uId = md5(x.path).slice(5, 10));
			});
			newId.push(time);
			/**
			 * 计算该新增项的ID
			 * 取其他数据项ID相加+时间戳 md5 = 该新增项ID
			 */
			this.value.splice(index + 1, 0, { ...(this.value[index] || this.keys), id: md5(newId.join('-')) });
		},
		del(index) {
			this.$emit('change', {
				keys: this.keys,
				index,
				type: 'del'
			});
			this.value.splice(index, 1);
		}
	}
};
</script>
