<template>
	<div>
		<el-container>
			<el-main>
				<el-form :inline="true" :model="formInline" class="demo-form-inline">
					<el-form-item>
						<el-input size="small" clearable v-model="formInline.picName" placeholder="请输入图片名称" @keydown.enter.native="queryPic"></el-input>
					</el-form-item>
					<el-form-item>
						<el-select size="small" clearable v-model="formInline.type" placeholder="请选择" @change="queryPic">
							<el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button size="small" type="primary" @click="queryPic">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button size="small" type="primary" @click="prepareAddPic">新增图片</el-button>
						<el-dialog title="新增图片" :visible.sync="addPicVisible" style="width: 100%">
							<el-select size="small" v-model="formInline.type" placeholder="请选择图片类型">
								<el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
							</el-select>
							<el-upload ref="upload" :limit="30" accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" name="files" multiple :action="getUploadAction()" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-success="handleUploadSuccess">
								<el-button slot="trigger" size="small" type="primary">选择图片</el-button>
								<el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
							</el-upload>
						</el-dialog>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="prepareBatchUpdatePic">批量修改</el-button>
						<el-dialog title="批量修改" :visible.sync="batchUpdatePicVisible" style="width: 100%">
							<el-form :model="form" class="custom-form">
								<el-form-item label="图片类型" :label-width="formLabelWidth" class="form-item">
									<el-select size="small" v-model="form.type" placeholder="请选择图片类型">
										<el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-form>
							<div slot="footer" class="dialog-footer">
								<el-button @click="batchUpdatePicVisible = false">取 消</el-button>
								<el-button type="primary" @click="batchUpdatePic()">确 定</el-button>
							</div>
						</el-dialog>
					</el-form-item>
				</el-form>
				<el-table border ref="multipleTable" v-loading="loading" :data="picList" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55"></el-table-column>
					<el-table-column prop="id" label="序号" align="center" sortable></el-table-column>
					<el-table-column prop="picName" label="图片名字" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="type" label="图片类型" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column align="center">
						<template slot-scope="props">
							<img :src="props.row.picUrl" alt="图片" height="100px" @click="showImageDialog(props.row.picUrl, props.$index)" style="cursor: pointer" />
						</template>
					</el-table-column>

					<el-table-column label="创建时间" align="center">
						<template slot-scope="props">
							{{ props.row.createTime | dateFormat }}
						</template>
					</el-table-column>

					<el-table-column prop="操作" label="操作" width="100px" align="center">
						<template slot-scope="props">
							<el-button size="small" type="primary" @click.prevent="prePicEdit(props.row.id, props.row.picName, props.row.picUrl, props.row.type)">编辑</el-button>
							<el-dialog title="编辑图片信息" :visible.sync="editPicVisible">
								<el-form :model="form" class="custom-form">
									<el-form-item align="center" class="form-item">
										<img :src="form.picUrl" alt="图片" height="100px" style="cursor: pointer" />
									</el-form-item>
									<el-form-item label="" class="form-item" align="middle">
										<el-select v-model="form.type" placeholder="请选择">
											<el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
										</el-select>
									</el-form-item>
									<el-form-item>
										<el-input clearable v-model="form.picName" placeholder="请输入图片名称"></el-input>
									</el-form-item>
								</el-form>
								<div slot="footer" class="dialog-footer">
									<el-button @click="editPicVisible = false">取 消</el-button>
									<el-button type="primary" @click="editPicConfirm">确 定</el-button>
								</div>
							</el-dialog>
						</template>
					</el-table-column>
				</el-table>
				<el-dialog :visible.sync="imageDialogVisible" width="30%">
					<div style="display: flex; align-items: center; justify-content: space-between">
						<button class="arrow-button" :class="{ disabled: imageIndex === 0 }" @click="showBeforeImage" :disabled="imageIndex === 0">
							<el-icon class="custom-icon" name="arrow-left"></el-icon>
						</button>
						<img :src="enlargedImageUrl" alt="放大图片" style="width: 80%" />
						<button class="arrow-button" :class="{ disabled: imageIndex === picList.length - 1 }" @click="showNextImage" :disabled="imageIndex === picList.length - 1">
							<el-icon class="custom-icon" name="arrow-right"></el-icon>
						</button>
					</div>
				</el-dialog>
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[8, 10, 50, 100, 200, 400]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
			</el-main>
		</el-container>
	</div>
</template>

<script>
import axios from 'axios'
import ApiService from '../../api/ApiService'
export default {
	name: 'MyPic',
	data() {
		return {
			fileUrl: 'http://localhost:80/picInfo/upload',
			form: {
				picName: '',
				picUrl: '',
				type: '',
			},
			formInline: {
				type: '',
				picName: '',
			},
			//待上传的图片
			fileList: [],
			multipleSelection: [],
			// 用户列表数据
			picList: [],
			loading: false,
			elementui_page_component_key: 0,
			currentPage: 1,
			pageSize: 6,
			total: 0,
			formLabelWidth: '120px',
			imageDialogVisible: false,
			batchUpdatePicVisible: false,
			addPicVisible: false,
			editPicVisible: false,
			enlargedImageUrl: '',
			currentRowId: null,
			imageIndex: 0, // 当前展示的图片索引
			options: ['全部', '宝宝', '学习', '风景', '美女', '猫咪', '素材', '动漫', '其他'],
		}
	},
	watch: {
		formInline: {
			handler(newVal, oldVal) {
				this.currentPage = 1
				localStorage.setItem('picPage', this.currentPage)
				this.queryPic()
			},
			deep: true,
		},
		// 监听currentPage的变化，将新值保存到localStorage中
		currentPage(newPage) {
			localStorage.setItem('picPage', newPage.toString())
		},
	},
	created() {
		// 调用请求数据的方法
		this.queryPic()
	},
	methods: {
		prepareBatchUpdatePic() {
			this.form.type = ''
			this.batchUpdatePicVisible = true
		},
		getUploadAction() {
			return this.fileUrl + '?type=' + this.formInline.type
		},
		async submitUpload() {
			this.$refs.upload.submit()
			this.addPicVisible = false
		},
		handleRemove(file, fileList) {
			console.log(file, fileList)
		},
		handlePreview(file) {
			console.log(file)
		},
		prepareAddPic() {
			this.addPicVisible = true
		},
		prePicEdit(id, picName, picUrl, type) {
			this.currentRowId = id
			this.form.picName = picName
			this.form.picUrl = picUrl
			this.form.type = type
			this.editPicVisible = true
		},
		handleUploadSuccess(response, file, fileList) {
			if (response.success) {
				setTimeout(() => {
					this.queryPic()
				}, 1000)
				this.fileList = []
			} else {
				this.$message.error('Upload failed')
			}
		},
		showBeforeImage() {
			if (this.imageIndex > 0) {
				// 增加索引以显示下一张图片
				this.imageIndex--
				this.enlargedImageUrl = this.picList[this.imageIndex].picUrl
				this.imageDialogVisible = true // 打开对话框展示图片
			}
		},
		showNextImage() {
			if (this.imageIndex < this.picList.length - 1) {
				// 增加索引以显示下一张图片
				this.imageIndex++
				this.enlargedImageUrl = this.picList[this.imageIndex].picUrl
				this.imageDialogVisible = true
			}
		},
		showImageDialog(url, index) {
			this.enlargedImageUrl = url
			this.imageDialogVisible = true
			this.imageIndex = index
		},
		async queryPic() {
			this.loading = true
			const { data: res } = await ApiService.queryPic(this.currentPage, this.pageSize, this.formInline)
			if (res.code === 200) {
				this.picList = res.result.records
				this.total = res.result.total
			}
			this.loading = false
		},
		async editPicConfirm() {
			try {
				this.loading = true
				this.editPicVisible = false
				const { data: res } = await ApiService.editPicConfirm(this.currentRowId, this.form.type, this.form.picName)
				if (res.code === 200) {
					this.form.picName = ''
					this.form.type = ''
					this.form.picUrl = null
					this.currentRowId = null
					this.queryPic()
				} else {
					console.error('Received non-200 status code', res)
				}
			} catch (error) {
				console.error('An error occurred while adding the questionName:', error)
				// 异常处理逻辑
			} finally {
				this.loading = false
			}
		},

		async batchUpdatePic() {
			this.loading = true
			this.batchUpdatePicVisible = false
			if (this.multipleSelection && this.multipleSelection.length === 0) {
				this.loading = false
				this.errorMsg('请选择需要处理项')
			} else {
				let ids = this.multipleSelection.map((item) => item.id)
				const { data: res } = await ApiService.batchUpdatePic(ids, this.form.type)
				if (res.code === 200) {
					this.multipleSelection = []
					this.form.type = ''
					this.queryPic()
				} else {
					console.error('Received non-200 status code', res)
				}
			}
			this.loading = false
		},

		handleCurrentChange(currentPage) {
			this.currentPage = currentPage
			this.queryPic()
		},
		handleSizeChange(currentSize) {
			this.pageSize = currentSize
			this.queryPic()
		},
		handleSelectionChange(val) {
			this.multipleSelection = val
		},
		errorMsg(msg) {
			this.$message({
				showClose: true,
				message: msg,
				type: 'error',
			})
		},
	},
}
</script>

<style lang="less" scoped>
.el-header {
	background-color: #b3c0d1;
	color: #333;
	line-height: 60px;
}

.el-aside {
	color: #333;
}

.pagination {
	margin-top: 16px;
	text-align: right;
}

.arrow-button {
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	background-color: transparent;
	cursor: pointer;
}

.custom-icon {
	font-size: 24px;
	color: #ff9900;
	margin-right: 6px;
}

.arrow-button.disabled {
	pointer-events: none;
	opacity: 0.1;
}
</style>