<template>
	<div>
		<el-dialog :title="title" :close-on-click-modal="false" draggable width="560px" @close="close"
			@keyup.enter.native="doSubmit" v-model="visible">
			<el-form :model="inputForm" ref="inputForm" v-loading="loading"
				label-width="100px" @submit.native.prevent>
				<el-row :gutter="15">
					<el-col :span="22">
						<el-form-item label="分类名称" prop="name"
							:rules="[{ required: true, message: '分类名称不能为空', trigger: 'blur' }]">
							<el-input v-model="inputForm.name" placeholder="请输入分类名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="22">
						<el-form-item label="排序号" prop="sortOrder">
							<el-input-number v-model="inputForm.sortOrder" :min="0" style="width: 100%"></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
					<el-button type="primary" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import HotelDishService from '@/api/hotel/HotelDishService'
export default {
	data() {
		return {
			title: '',
			method: '',
			visible: false,
			loading: false,
			inputForm: {
				id: '',
				name: '',
				sortOrder: 0
			}
		}
	},
	hotelDishService: null,
	created() {
		this.hotelDishService = new HotelDishService()
	},
	methods: {
		init(method, id) {
			this.method = method
			this.inputForm = {
				id: '',
				name: '',
				sortOrder: 0
			}
			if (method === 'add') {
				this.title = '新建分类'
			} else if (method === 'edit') {
				this.inputForm.id = id
				this.title = '编辑分类'
			}
			this.visible = true
			this.loading = false
			this.$nextTick(() => {
				if (method === 'edit') {
					this.loading = true
					this.hotelDishService.categoryPage({ current: 1, size: 999 }).then((data) => {
						const records = data.records || []
						const found = records.find(item => item.id === id)
						if (found) {
							this.inputForm = { ...this.inputForm, ...found }
						}
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
				}
			})
		},
		doSubmit() {
			this.$refs['inputForm'].validate((valid) => {
				if (valid) {
					this.loading = true
					this.hotelDishService.categorySave(this.inputForm).then((data) => {
						this.close()
						this.$message.success(data)
						this.$emit('refreshDataList')
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
				}
			})
		},
		close() {
			this.$refs.inputForm && this.$refs.inputForm.resetFields()
			this.visible = false
		}
	}
}
</script>
