<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="dishName">
				<el-input v-model="searchForm.dishName" placeholder="请输入菜品名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="菜品编码" prop="dishCode">
				<el-input v-model="searchForm.dishCode" placeholder="请输入菜品编码" clearable></el-input>
			</el-form-item>
			<el-form-item label="菜品分类" prop="typeId">
				<SelectTree ref="searchDishTypeTree" :props="{
					value: 'id',
					label: 'name',
					children: 'children'
				}" url="/psi-management-server/psi/dishType/treeData" :value="searchForm.typeId" :clearable="true"
					:accordion="true" size="default" style="width: 180px"
					@getValue="(value) => { searchForm.typeId = value }" />
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
					<el-option label="启用" value="0"></el-option>
					<el-option label="停用" value="1"></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('psi:dish:add')" type="primary" icon="el-icon-plus"
						@click="add()">新建</el-button>
					<el-button v-if="hasPermission('psi:dish:del')" type="danger" icon="el-icon-delete" @click="del()"
						:disabled="$refs.dishTable && $refs.dishTable.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="dishTable"
					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="imageUrl">
						<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="center" title="菜品编码" field="dishCode"></vxe-column>
					<vxe-column min-width="180" align="center" title="菜品名称" field="dishName">
						<template #default="scope">
							<el-link type="primary" :underline="false" v-if="hasPermission('psi:dish:view')"
								@click="view(scope.row.id)">{{ scope.row.dishName }}</el-link>
							<span v-else>{{ scope.row.dishName }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="150" align="center" title="菜品分类" field="typeName"></vxe-column>
					<vxe-column width="90" align="center" title="单位" field="unit"></vxe-column>
					<vxe-column min-width="120" align="center" title="规格" field="spec"></vxe-column>
					<vxe-column width="110" align="center" title="销售价" field="salePrice"></vxe-column>
					<vxe-column width="120" align="center" title="参考成本价" field="costPrice"></vxe-column>
					<vxe-column width="100" align="center" title="状态" field="status">
						<template #default="scope">
							<el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
								{{ scope.row.status === '0' ? '启用' : '停用' }}
							</el-tag>
						</template>
					</vxe-column>
					<vxe-column min-width="130" align="center" title="创建人" field="createName"></vxe-column>
					<vxe-column min-width="180" align="center" title="创建时间" field="createTime"></vxe-column>
					<vxe-column title="操作" width="220px" fixed="right" align="center">
						<template #default="scope">
							<el-button v-if="hasPermission('psi:dish:edit')" text type="primary" size="small"
								@click="edit(scope.row.id)">修改</el-button>
							<el-button v-if="hasPermission('psi:dish:edit')" text type="primary" size="small"
								@click="changeStatus(scope.row)">{{ scope.row.status === '0' ? '停用' : '启用'
								}}</el-button>
							<el-button v-if="hasPermission('psi:dish:del')" text type="primary" size="small"
								@click="del(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>
		<DishLibraryForm ref="dishLibraryForm" @refreshList="refreshList"></DishLibraryForm>
	</div>
</template>

<script>
import DishLibraryService from '@/api/psi/DishLibraryService'
import DishLibraryForm from './DishLibraryForm'
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import OSSSerivce from '@/api/sys/OSSService'
export default {
	data() {
		return {
			searchVisible: true,
			searchForm: {
				dishName: '',
				dishCode: '',
				typeId: '',
				status: ''
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: []
			},
			loading: false
		}
	},
	dishLibraryService: null,
	ossService: null,
	created() {
		this.dishLibraryService = new DishLibraryService()
		this.ossService = new OSSSerivce()
	},
	components: {
		DishLibraryForm,
		SelectTree
	},
	mounted() {
		this.refreshList()
	},
	activated() {
		this.refreshList()
	},
	methods: {
		add() {
			this.$refs.dishLibraryForm.init('add', '')
		},
		edit(id) {
			this.$refs.dishLibraryForm.init('edit', id)
		},
		view(id) {
			this.$refs.dishLibraryForm.init('view', id)
		},
		refreshList() {
			this.loading = true
			this.dishLibraryService.list({
				'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
				this.loading = false
				this.loadImagePreview()
			}).catch(() => {
				this.loading = false
			})
		},
		loadImagePreview() {
			this.dataList.forEach((row) => {
				const urls = this.getImageUrls(row.imageUrl)
				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 === '0' ? '1' : '0'
			const message = status === '0' ? '确定启用该菜品吗？' : '确定停用该菜品吗？'
			this.$confirm(message, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.dishLibraryService.changeStatus(row.id, status).then((data) => {
					this.$message.success(data)
					this.refreshList()
				})
			})
		},
		del(id) {
			let ids = id || this.$refs.dishTable.getCheckboxRecords().map(item => {
				return item.id
			}).join(',')
			this.$confirm(`确定删除所选项吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				this.dishLibraryService.delete(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			})
		},
		resetSearch() {
			this.$refs.searchForm.resetFields()
			this.searchForm.typeId = ''
			this.tablePage.currentPage = 1
			this.refreshList()
		}
	}
}
</script>
