<template>
	<div class="page">
		<el-form :inline="true" v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm"
			@keyup.enter.native="refreshList()" @submit.native.prevent>
			<el-form-item label="菜品名称" prop="name">
				<el-input v-model="searchForm.name" placeholder="请输入菜品名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="分类" prop="categoryId">
				<el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable style="width: 140px">
					<el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
					<el-option label="在售" value="ON_SALE"></el-option>
					<el-option label="下架" value="OFF_SHELF"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
				<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
			</el-form-item>
		</el-form>

		<div class="jp-table top">
			<vxe-toolbar :refresh="{ query: refreshList }" custom>
				<template #buttons>
					<el-button v-if="hasPermission('hotel:admin:dish:add')" type="primary" icon="el-icon-plus"
						@click="add()">新建</el-button>
					<el-button v-if="hasPermission('hotel:admin:dish:delete')" type="danger" icon="el-icon-delete"
						@click="batchDelete()"
						:disabled="$refs.dataTable && $refs.dataTable.getCheckboxRecords().length === 0"
						plain>删除</el-button>
				</template>
				<template #tools>
					<vxe-button text type="primary" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
						class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
				</template>
			</vxe-toolbar>
			<div style="height: calc(100% - 90px)">
				<vxe-table border="inner" auto-resize resizable height="auto" :loading="loading" ref="dataTable"
					show-header-overflow show-overflow highlight-hover-row :menu-config="{}" :data="dataList"
					:checkbox-config="{}">
					<vxe-column type="seq" width="60" title="序号"></vxe-column>
					<vxe-column type="checkbox" width="60"></vxe-column>
					<vxe-column width="80" align="center" title="菜品图片" field="image">
						<template #default="scope">
							<el-image v-if="scope.row.previewImageUrl" :src="scope.row.previewImageUrl"
								:preview-src-list="scope.row.previewImageList" fit="cover"
								style="width: 44px; height: 44px; border-radius: 4px;" hide-on-click-modal
								append-to-body :z-index="9999"></el-image>
							<span v-else>暂无图片</span>
						</template>
					</vxe-column>
					<vxe-column min-width="150" align="left" title="菜品名称" field="name"></vxe-column>
					<vxe-column width="100" align="center" title="分类" field="categoryName"></vxe-column>
					<vxe-column width="90" align="right" title="价格" field="price">
						<template #default="scope">¥{{ scope.row.price }}</template>
					</vxe-column>
					<vxe-column width="100" align="center" title="制作时长" field="prepTime">
						<template #default="scope">{{ scope.row.prepTime ? scope.row.prepTime + '分钟' : '-' }}</template>
					</vxe-column>
					<vxe-column width="80" align="center" title="月销" field="sales"></vxe-column>
					<vxe-column width="100" align="center" title="状态" field="status">
						<template #default="scope">
							<el-tag :type="scope.row.status === 'ON_SALE' ? 'success' : 'info'">
								{{ scope.row.status === 'ON_SALE' ? '在售' : '下架' }}
							</el-tag>
						</template>
					</vxe-column>
					<vxe-column width="80" align="center" title="售罄" field="soldOut">
						<template #default="scope">
							<el-tag v-if="scope.row.soldOut === 1" type="danger">售罄</el-tag>
							<span v-else>-</span>
						</template>
					</vxe-column>
					<vxe-column width="80" align="center" title="推荐" field="isRecommended">
						<template #default="scope">
							<el-tag v-if="scope.row.isRecommended === 1" type="warning">推荐</el-tag>
							<span v-else>-</span>
						</template>
					</vxe-column>
					<vxe-column width="70" align="center" title="排序" field="sortOrder"></vxe-column>
					<vxe-column title="操作" width="220px" fixed="right" align="center">
						<template #default="scope">
							<el-button v-if="hasPermission('hotel:admin:dish:edit')" text type="primary" size="small"
								@click="edit(scope.row.id)">修改</el-button>
							<el-button v-if="hasPermission('hotel:admin:dish:edit')" text type="primary" size="small"
								@click="changeStatus(scope.row)">{{ scope.row.status === 'ON_SALE' ? '下架' : '上架' }}</el-button>
							<el-button v-if="hasPermission('hotel:admin:dish:delete')" text type="primary" size="small"
								@click="doDelete(scope.row.id)">删除</el-button>
						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager background :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
					:total="tablePage.total" :page-sizes="[10, 20, 100, 1000, { label: '全量数据', value: 1000000 }]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
					@page-change="currentChangeHandle">
				</vxe-pager>
			</div>
		</div>
		<DishForm ref="dishForm" @refreshList="refreshList"></DishForm>
	</div>
</template>

<script>
import HotelDishService from '@/api/hotel/HotelDishService'
import DishForm from './DishForm'
import OSSSerivce from '@/api/sys/OSSService'
export default {
	data() {
		return {
			searchVisible: true,
			searchForm: {
				name: '',
				categoryId: '',
				status: ''
			},
			categoryList: [],
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: []
			},
			loading: false
		}
	},
	hotelDishService: null,
	ossService: null,
	created() {
		this.hotelDishService = new HotelDishService()
		this.ossService = new OSSSerivce()
	},
	components: {
		DishForm
	},
	mounted() {
		this.refreshList()
		this.loadCategories()
	},
	activated() {
		this.refreshList()
	},
	methods: {
		add() {
			this.$refs.dishForm.init('add', '')
		},
		edit(id) {
			this.$refs.dishForm.init('edit', id)
		},
		loadCategories() {
			this.hotelDishService.categoryAll().then((data) => {
				this.categoryList = Array.isArray(data) ? data : (data.list || [])
			})
		},
		refreshList() {
			this.loading = true
			this.hotelDishService.page({
				'current': this.tablePage.currentPage,
				'size': this.tablePage.pageSize,
				'orders': this.tablePage.orders,
				...this.searchForm
			}).then((data) => {
				this.dataList = data.records || []
				this.tablePage.total = data.total || 0
				this.loading = false
				this.loadImagePreview()
			}).catch(() => {
				this.loading = false
			})
		},
		loadImagePreview() {
			this.dataList.forEach((row) => {
				const urls = this.getImageUrls(row.image)
				if (urls.length === 0) {
					row.previewImageUrl = ''
					row.previewImageList = []
					return
				}
				row.previewImageList = urls
				row.previewImageUrl = urls[0]
				Promise.all(urls.map(url => this.getPreviewUrl(url))).then((list) => {
					row.previewImageList = list
					row.previewImageUrl = list[0]
				})
			})
		},
		getImageUrls(value) {
			if (!value) {
				return []
			}
			return value.split(',').map(item => item.trim()).filter(item => item)
		},
		getPreviewUrl(url) {
			if (url.indexOf('http') === 0) {
				return Promise.resolve(url)
			}
			return this.ossService.getTemporaryUrl(url).catch(() => url)
		},
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage
			this.tablePage.pageSize = pageSize
			this.refreshList()
		},
		changeStatus(row) {
			const status = row.status === 'ON_SALE' ? 'OFF_SHELF' : 'ON_SALE'
			const message = status === 'ON_SALE' ? '确定上架该菜品吗？' : '确定下架该菜品吗？'
			this.$confirm(message, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.hotelDishService.updateStatus(row.id, status).then((data) => {
					this.$message.success(data)
					this.refreshList()
				})
			})
		},
		doDelete(id) {
			this.$confirm('确定删除该菜品吗？删除后不可恢复！', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				this.hotelDishService.delete(id).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			})
		},
		batchDelete() {
			const ids = this.$refs.dataTable.getCheckboxRecords().map(item => item.id).join(',')
			this.$confirm(`确定删除所选的 ${ids.split(',').length} 个菜品吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				this.hotelDishService.batch({ ids: ids.split(','), operation: 'DELETE' }).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			})
		},
		resetSearch() {
			this.$refs.searchForm.resetFields()
			this.searchForm.categoryId = ''
			this.tablePage.currentPage = 1
			this.refreshList()
		}
	}
}
</script>
