<template>
	<div>
		<el-container>
			<el-main>
				<el-form :inline="true" :model="formInline" class="demo-form-inline">
					<el-form-item>
						<el-input clearable v-model="formInline.question" placeholder="请输入问题" @keydown.enter.native="interviewPage"></el-input>
					</el-form-item>
					<el-select v-model="formInline.questionType" placeholder="请选择" @change="interviewPage">
						<el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
					</el-select>
					<el-form-item>
						<el-button type="primary" @click="interviewPage">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="prepareAdd">新增</el-button>
						<el-dialog title="新增面试问题" :visible.sync="dialogFormVisible" style="width: 100%">
							<el-form :model="form" class="custom-form">
								<el-form-item label="面试问题" :label-width="formLabelWidth" class="form-item">
									<el-input v-model="form.question" autocomplete="off" style="width: 100%"></el-input>
								</el-form-item>
								<br />
								<el-form-item label="问题类型" :label-width="formLabelWidth" class="form-item">
									<el-select v-model="form.questionType" 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="dialogFormVisible = false">取 消</el-button>
								<el-button type="primary" @click="handleConfirm(0)">确 定</el-button>
							</div>
						</el-dialog>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="prepareMutiAdd">批量新增</el-button>
						<el-dialog class="red-title" :visible.sync="dialogMutiFormVisible">
							<div class="red-title" slot="title">批量新增面试问题(多个问题换行填写)</div>
							<el-form :model="form" class="custom-form">
								<el-form-item label="面试问题" :label-width="formLabelWidth" class="form-item">
									<el-input type="textarea" v-model="form.question" autocomplete="off" :rows="5" :cols="30" style="width: 100%"></el-input>
								</el-form-item>
							</el-form>
							<div slot="footer" class="dialog-footer">
								<el-button @click="dialogMutiFormVisible = false">取 消</el-button>
								<el-button type="primary" @click="handleConfirm(1)">确 定</el-button>
							</div>
						</el-dialog>
					</el-form-item>
				</el-form>
				<el-table border :data="userlist" v-loading="loading">
					<el-table-column prop="id" label="序号" width="100" sortable></el-table-column>
					<el-table-column prop="question" label="面试问题" show-overflow-tooltip></el-table-column>

					<el-table-column prop="questionType" label="问题类型" show-overflow-tooltip align="center">
						<template slot-scope="scope">
							<span :style="{ color: getColorForValue(scope.row.questionType) }" v-html="scope.row.questionType"></span>
						</template>
					</el-table-column>

					<el-table-column label="创建时间" width="170">
						<template slot-scope="props">
							{{ props.row.createTime | dateFormat }}
						</template>
					</el-table-column>
					<el-table-column prop="操作" label="操作" width="180">
						<template slot-scope="props">
							<el-button type="success" @click.prevent="preEdit(props.row.id, props.row.question, props.row.questionType)" width="200">编辑</el-button>
							<el-dialog title="编辑面试问题" :visible.sync="editVisible">
								<el-form :model="form">
									<el-form-item label="面试问题" :label-width="formLabelWidth">
										<el-input class="custom-textarea" type="textarea" v-model="form.question" autocomplete="off" :rows="5" :cols="30" style="text-align: left"></el-input>
									</el-form-item>
									<el-form-item label="问题类型" :label-width="formLabelWidth">
										<el-select v-model="form.questionType" placeholder="请选择问题类型" style="text-align: left">
											<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="editVisible = false">取 消</el-button>
									<el-button type="primary" @click="editConfirm">确 定</el-button>
								</div>
							</el-dialog>

							<el-button type="danger" @click="prepareDelete(props.row.id)">删除</el-button>
							<el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
								<span>确认删除吗</span>
								<span slot="footer" class="dialog-footer">
									<el-button @click="dialogVisible = false">取 消</el-button>
									<el-button type="primary" @click.prevent="onDelete(currentRowId)">确 定</el-button>
								</span>
							</el-dialog>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination class="pagination" background :key="elementui_page_component_key" :current-page.sync="currentPage" :page-size="pageSize" :total="total" @current-change="handleCurrentChange"></el-pagination>
			</el-main>
			<el-backtop class="backtop"></el-backtop>
		</el-container>
	</div>
</template>

<script>
import axios from 'axios'
export default {
	name: 'MyInterview',

	data() {
		return {
			// 用户列表数据
			userlist: [],
			loading: false,
			elementui_page_component_key: 0,
			currentPage: Number(localStorage.getItem('interviewLastPage')) || 1,
			pageSize: 9,
			total: 0,
			formInline: {
				question: '',
				questionType: '',
			},
			options: ['MySQL', 'JVM', '并发编程', '微服务'],
			// 新增的内容
			dialogFormVisible: false,
			dialogMutiFormVisible: false,
			form: {
				question: '',
				questionType: '',
			},
			formLabelWidth: '120px',
			dialogVisible: false,
			editVisible: false,
			currentRowId: null,
			colorMap: {}, // 创建一个空的颜色映射关系对象
		}
	},
	watch: {
		'formInline.question'(newVal, oldVal) {
			if (newVal !== oldVal) {
				this.currentPage = 1
				localStorage.setItem('interviewLastPage', this.currentPage)
				this.interviewPage()
			}
		},
		// 监听currentPage的变化，将新值保存到localStorage中
		currentPage(newPage) {
			localStorage.setItem('interviewLastPage', newPage.toString())
		},
	},
	created() {
		//获取问题列表
		this.interviewPage()
	},
	mounted() {
		this.currentPage = 1
	},
	methods: {
		prepareAdd() {
			this.form.question = ''
			this.form.questionType = ''
			this.dialogFormVisible = true
		},
		prepareMutiAdd() {
			this.form.question = ''
			this.form.questionType = ''
			this.dialogMutiFormVisible = true
		},

		prepareDelete(id) {
			this.currentRowId = id
			this.dialogVisible = true
		},
		preEdit(id, question, questionType) {
			this.form.question = question
			this.form.questionType = questionType
			this.currentRowId = id
			this.editVisible = true
		},
		handleClose(done) {
			this.$confirm('确认关闭？')
				.then((_) => {
					done()
				})
				.catch((_) => {})
		},
		handleConfirm(addType) {
			this.dialogFormVisible = false // 关闭对话框
			this.dialogMutiFormVisible = false
			this.addQuestion(addType) // 发送请求
		},

		async addQuestion(addType) {
			try {
				this.loading = true

				const { data: res } = await axios.post('http://localhost:80/interviewQuestion/add', {
					addType: addType,
					question: this.form.question,
					questionType: this.form.questionType,
				})
				if (res.code === 200) {
					this.currentPage = 1
					this.form.question = ''
					this.form.questionType = ''
					this.interviewPage() // 确保这个方法是有效的
				} else {
					console.error('Received non-200 status code', res)
					this.errorMsg(res.message)
				}
			} catch (error) {
				console.error('An error occurred while adding the question:', error)
				// 异常处理逻辑
			} finally {
				this.loading = false
			}
		},
		errorMsg(msg) {
			this.$message({
				showClose: true,
				message: msg,
				type: 'error',
			})
		},
		async editConfirm() {
			try {
				this.loading = true

				const { data: res } = await axios.post('http://localhost:80/interviewQuestion/update', {
					id: this.currentRowId,
					question: this.form.question,
					questionType: this.form.questionType,
				})
				if (res.code === 200) {
					this.form.question = ''
					this.form.questionType = 0
					this.editVisible = false
					currentRowId: null
					this.interviewPage() // 确保这个方法是有效的
				} else {
					console.error('Received non-200 status code', res)
				}
			} catch (error) {
				console.error('An error occurred while adding the question:', error)
				// 异常处理逻辑
			} finally {
				this.loading = false
			}
		},

		async onDelete(id) {
			this.dialogVisible = false
			this.loading = true
			const { data: res } = await axios.get('http://localhost:80/interviewQuestion/delete', {
				params: {
					id: id,
				},
			})
			this.interviewPage()
			this.loading = false
		},

		refreshPage() {
			//获取问题类型的枚举
			this.interviewPage()
			location.reload()
		},
		async interviewPage() {
			this.loading = true
			const { data: res } = await axios.get('http://localhost:80/interviewQuestion/page', {
				params: {
					page: this.currentPage,
					pageSize: this.pageSize,
					question: this.formInline.question,
					questionType: this.formInline.questionType,
				},
			})
			if (res.code === 200) {
				this.total = res.result.totalElements
				this.userlist = res.result.content
			}
			this.loading = false
		},
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage
			this.interviewPage()
		},
		getColorForValue(value) {
			// 检查颜色映射关系中是否已经有该值对应的颜色
			if (!this.colorMap[value]) {
				// 如果没有，随机生成一个颜色并将其关联到该值
				this.colorMap[value] = this.getRandomColor()
			}
			// 返回值对应的颜色
			return this.colorMap[value]
		},
		getRandomColor() {
			// 从颜色数组中随机选取一个颜色
			const colorArray = [
				'red',
				'blue',
				'green',
				'purple',
				'orange',
				'pink',
				'brown',
				'magenta',
				'maroon',
				'navy',
				'olive',
				'teal',
				'silver',
				'gray',
				'indigo',
				'violet',
				'coral',
				'salmon',
				'orchid',
				'slategray',
				'thistle',
				'burlywood',
				'cadetblue',
				'chocolate',
				'crimson',
				'darkblue',
				'darkcyan',
				'darkgoldenrod',
				'darkgray',
				'darkgreen',
				'darkkhaki',
				'darkmagenta',
				'darkolivegreen',
				'darkorange',
				'darkorchid',
				'darkred',
				'darksalmon',
				'darkseagreen',
				'darkslateblue',
				'darkslategray',
				'darkturquoise',
				'darkviolet',
				'deeppink',
				'deepskyblue',
				'dodgerblue',
				'firebrick',
				'forestgreen',
				'fuchsia',
				'hotpink',
				'indianred',
				'lightcoral',
				'lightpink',
				'lightsalmon',
				'lightseagreen',
				'lightskyblue',
				'lightslategray',
				'lightsteelblue',
				'mediumaquamarine',
				'mediumblue',
				'mediumorchid',
				'mediumpurple',
				'mediumslateblue',
				'mediumturquoise',
				'mediumvioletred',
				'midnightblue',
				'orangered',
				'palevioletred',
				'peru',
				'rosybrown',
				'saddlebrown',
				'seagreen',
				'sienna',
				'skyblue',
				'slateblue',
				'tan',
				'thistle',
				'tomato',
				'violet',
			]
			const randomIndex = Math.floor(Math.random() * colorArray.length)
			return colorArray[randomIndex]
		},
	},
}
</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;
}
.header-button-item {
	margin-right: 15px;
	font-size: 20px;
}

.red-title {
	line-height: 24px;
	font-size: 18px;
	color: red;
}

.backtop {
	position: fixed;
	bottom: 50px;
	right: 50px;
	height: 40px;
	width: 40px;
	line-height: 40px;
	text-align: center;
	border-radius: 20px;
	background-color: #007aff;
	color: #fff;
	cursor: pointer;
	z-index: 999;
}
.custom-textarea {
	width: 100%;
	text-align: left;
}

.backtop:hover {
	background-color: #0050a0;
}
</style>