<template>
<el-dialog :title="titleMap[mode]" v-model="visible" :width="1000" destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
	<el-main>
		<el-form ref="dialogForm" :model="form" :rules="rules" label-width="160px">
			<el-form-item label="规格标题" prop="title">
				<el-input v-model="form.title" placeholder="请输入规格标题" clearable />
			</el-form-item>
			<el-form-item label="规格值" prop="value">
				<el-button type="primary" @click="form.value.push({name: '', value: ['']})" style="margin: 0 0 10px 0;">添加规格值</el-button>
				<el-table :data="form.value" border>
					<el-table-column prop="name" label="规格名" width="200">
						<template #default="{row, index}">
							<el-input v-model="row.name" placeholder="请输入规格名" clearable>
								<template #append>
									<el-button type="danger" icon="el-icon-delete" circle @click="form.value.splice(index, 1)" />
								</template>
							</el-input>
						</template>
					</el-table-column>
					<el-table-column prop="value" label="规格值" min-width="200">
						<template #default="{row}">
							<el-input v-model="row.value[index]" placeholder="请输入规格值" clearable v-for="(item, index) in row.value" :key="index" style="width: 160px; margin: 5px;">
								<template #append>
									<el-button type="danger" icon="el-icon-delete" circle @click="row.value.splice(index, 1)" />
								</template>
							</el-input>
							<el-button type="primary" icon="el-icon-plus" circle @click="row.value.push('')" style="margin: 5px;" />
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
		</el-form>
	</el-main>
	<template #footer>
		<el-button type="primary" @click="onSubmit">确认提交</el-button>
	</template>
</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {add: '新增', edit: '编辑'},
			form: {title: '', value: [{name: '', value: ['']}]},
			rules: {
				title: [{required: true, message: '请输入分类标题'}],
				value: [{required: true, message: '请输入规格值'}],
			},
			visible: false,
			isSaveing: false,
			cache: {}
		}
	},
	mounted(){
	},
	methods:{
		//显示
		open(mode='add'){
			this.mode = mode;
			this.visible = true;
			return this;
		},
		//表单提交方法
		onSubmit(){
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					let res
					if(this.form.id){
						res = await this.$API.goods.spec.edit.post(this.form);
					}else{
						res = await this.$API.goods.spec.add.post(this.form);
					}

					this.isSaveing = false;
					if(res.code == 1){
						this.$emit('success', res.data)
						this.visible = false;
						this.$message.success("操作成功")
					}else{
						this.$message.error(res.message)
					}
				}
			})
		},
		//表单注入数据
		setData(data){
			this.loading = true
			Object.assign(this.form, data)
		}
	}
}
</script>

<style scoped>
</style>