<template>
	<div class="house-management-container">
		<!-- 搜索区域 -->
		<div class="search-area">
			<el-form :inline="true" :model="state.query" class="search-form">
				<el-form-item label="房源名称：" class="search-item">
					<el-input
						v-model="state.query.title"
						placeholder="请输入房源名称"
						clearable
						@input="handleSearch"
						class="search-input"
					/>
				</el-form-item>
				<el-form-item label="状态：" class="search-item">
					<el-select clearable
										 v-model="state.query.status"
										 placeholder="请选择状态"
										 @change="handleSearch"
										 style="width: 120px">
						<el-option
							v-for="item in state.statusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item class="action-buttons">
					<el-button type="primary" @click="init" class="query-button">
						<el-icon><Search /></el-icon>
						<span>查询</span>
					</el-button>
					<el-button type="primary" @click="openAddDialog" class="add-button">
						<el-icon><Plus /></el-icon>
						<span>添加</span>
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 表格区域 -->
		<div class="table-area">
			<el-table
				v-loading="state.loading"
				:data="state.list"
				class="data-table"
				empty-text="暂无数据"
			>
				<el-table-column label="封面图" width="100" align="center">
					<template #default="{ row }">
						<el-image
							:src="row.image"
							fit="cover"
							class="house-image"
						/>
					</template>
				</el-table-column>

				<el-table-column prop="title" label="标题" min-width="120" align="center"/>
				<el-table-column prop="name" label="小区名称" min-width="120" align="center"/>
				<el-table-column prop="city" label="城市" width="100" align="center"/>
				<el-table-column prop="type" label="户型" width="120" align="center"/>
				<el-table-column prop="area" label="面积" width="100" align="center"/>
				<el-table-column prop="floor" label="楼层" width="80" align="center"/>
				<el-table-column prop="face" label="朝向" width="100" align="center"/>
				<el-table-column prop="decoration" label="装修" width="100" align="center"/>
				<el-table-column prop="price" label="价格 (元/㎡)" width="120" align="center"/>
				<el-table-column prop="status" label="状态" min-width="120" align="center">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">
							{{ getStatusName(row.status) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" width="180" align="center">
					<template #default="{ row }">
						<el-button size="small" type="primary" plain @click="edit(row)">编辑</el-button>
						<el-popconfirm title="确认删除该房源？" @confirm="del(row.id)">
							<template #reference>
								<el-button v-if="row.status != 1" size="small" type="danger" plain>删除</el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<div class="pagination-container" v-if="state.query.total > 0">
				<el-pagination
					:current-page="state.query.page"
					:page-size="state.query.limit"
					:total="state.query.total"
					:page-sizes="[5,10,20,50]"
					layout="total, sizes, prev, pager, next, jumper"
					background
					@size-change="handleSizeChange"
					@current-change="handlePageChange"
				/>
			</div>
		</div>
		<!-- 新增/编辑 对话框 -->
		<el-dialog
			v-model="state.dialogVisible"
			:title="state.formData.id ? '编辑房源' : '新增房源'"
			width="700px"
			:close-on-click-modal="false"
		>
			<el-form
				:model="state.formData"
				ref="formRef"
				label-width="120px"
				label-position="right"
			>
				<el-form-item label="用户" prop="userId" :rules="[{ required: true, message: '请选择用户', trigger: 'blur' }]">
					<el-select v-model="state.formData.userId" placeholder="请选择用户" filterable clearable>
						<el-option
							v-for="user in state.userList"
							:key="user.id"
							:label="`${user.username}（姓名: ${user.nickName}）`"
							:value="user.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
					<el-input v-model="state.formData.title" placeholder="请输入标题" />
				</el-form-item>



				<el-form-item label="小区名称" prop="name" :rules="[{ required: true, message: '请输入小区名称', trigger: 'blur' }]">
					<el-input v-model="state.formData.name" placeholder="请输入小区名称" />
				</el-form-item>
				<el-form-item label="城市" prop="city" :rules="[{ required: true, message: '请输入城市', trigger: 'blur' }]">
					<el-input v-model="state.formData.city" placeholder="请输入城市" />
				</el-form-item>
				<el-form-item label="户型" prop="type"  :rules="[{ required: true, message: '请输入户型', trigger: 'blur' }]">
					<el-select v-model="state.formData.type" placeholder="请选择户型" clearable>
						<el-option
							v-for="item in getHouseType()"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>

				</el-form-item>
				<el-form-item label="面积(㎡)" prop="area">
					<el-input v-model="state.formData.area" placeholder="请输入面积" />
				</el-form-item>
				<el-form-item label="楼层" prop="floor">
					<el-input-number v-model="state.formData.floor" :min="0" />
				</el-form-item>
				<el-form-item label="朝向" prop="face">
					<el-select v-model="state.formData.face" placeholder="请选择朝向">
						<el-option v-for="item in getFace()" :label="item" :value="item" />
					</el-select>
				</el-form-item>
				<el-form-item label="装修" prop="decoration">
					<el-select v-model="state.formData.decoration" placeholder="请选择装修">
						<el-option v-for="item in getDecoration()" :label="item" :value="item" />
					</el-select>
				</el-form-item>
				<el-form-item label="封面图" prop="image" :rules="[{ required: true, message: '请上传封面图', trigger: 'blur' }]">
					<image-upload
						class="image-uploader"
						:image-url="state.formData.image"
						@update:imageUrl="handleImageUrl"
					/>
				</el-form-item>
				<el-form-item label="价格(元/㎡)" prop="price">
					<el-input-number v-model="state.formData.price" :min="0" :step="0.01" />
				</el-form-item>
				<el-form-item label="标签" prop="tag">
					<el-input v-model="state.formData.tag" placeholder="请输入标签，用逗号分隔" />
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="state.formData.sort" :min="1" />
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input
						type="textarea"
						v-model="state.formData.description"
						rows="3"
						placeholder="请输入描述"
					/>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="state.formData.status" placeholder="请选择状态">
						<el-option
							v-for="item in getHouseStatus()"
							:key="item.status"
							:label="item.name"
							:value="item.status"
						/>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDialog">取消</el-button>
					<el-button type="primary" @click="saveTransaction">保存</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { Search, Plus, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getDecoration, getFace, getHouseStatus, getHouseType, getStatusName, getStatusType } from '~/utils/utils'
const formRef = ref<FormInstance>()
const state = reactive({
	route: 'sys/house',
	loading: false,
	list: [] as any[],
	dialogVisible: false,
	// 搜索 / 分页
	query: {
		total: 0,
		page: 1,
		limit: 5,
		title: '',
		status: null as number | null,
	},
	// 下拉状态选项
	statusOptions: [
		{ label: '未审核', value: 0 },
		{ label: '上架',   value: 1 },
		{ label: '下架',   value: 2 },
		{ label: '审核失败', value: 3 },
	],
	// 表单数据
	formData: {} as Record<string, any>,
	userList:[]
})

// 拉取列表
const init = () => {
	state.loading = true
	adminRequest
		.get(`${state.route}/page`, { params: state.query })
		.then((res: any) => {
			state.list = res.data.list
			state.query.total = res.data.total
		})
		.finally(() => {
			state.loading = false
		})

	adminRequest.get(`sys/user-front/page`, {
		params: { limit:999 }
	}).then((res:any) => {
		state.userList = res.data.list
	})
}

// 搜索重置页码
const handleSearch = () => {
	state.query.page = 1
	init()
}

// 打开新增
const openAddDialog = () => {
	state.formData = {
		title: '',
		name: '',
		city: '',
		type: '',
		area: '',
		floor: 1,
		face: '',
		decoration: '',
		image: '',
		price: 0,
		description: '',
		tag: '',
		hex: '',
		sort: 1,
		status: 0,
		view: 0,
		createTime: '',
		userId: null
	}
	state.dialogVisible = true
	nextTick(() => formRef.value?.clearValidate())
}

// 关闭对话框
const closeDialog = () => {
	state.dialogVisible = false
	state.formData = {}
}

// 编辑
const edit = (row: any) => {
	state.formData = { ...row }
	state.dialogVisible = true
}

// 保存（新增/更新）
const saveTransaction = () => {
	formRef.value?.validate(async valid => {
		if (!valid) return
		try {
			const req = state.formData.id
				? adminRequest.put(`${state.route}`, state.formData)
				: adminRequest.post(`${state.route}`, state.formData)
			await req
			ElMessage.success('操作成功')
			closeDialog()
			init()
		} catch {
			ElMessage.error('操作失败')
		}
	})
}

// 删除
const del = async (id: number) => {
	try {
		await adminRequest.delete(`${state.route}/${id}`)
		ElMessage.success('删除成功')
		init()
	} catch {
		ElMessage.error('删除失败')
	}
}

// 分页
const handlePageChange = (page: number) => {
	state.query.page = page
	init()
}
const handleSizeChange = (size: number) => {
	state.query.limit = size
	init()
}
// 处理图片上传回调
const handleImageUrl = (url: string) => {
	state.formData.image = url
}
onMounted(() => {
	init()
})
</script>
<style lang="scss" scoped>
.house-management-container {
	padding: 20px;
	background: #fff;
	border-radius: 4px;
	box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}
.search-area {
	margin-bottom: 20px;
	.search-form {
		display: flex;
		align-items: center;
		.search-item { margin-right: 16px; }
		.search-input { width: 220px; }
		.action-buttons { margin-left: auto; display: flex; gap: 8px; }
	}
}
.table-area {
	.data-table {
		width: 100%;
		.house-image {
			width: 60px; height: 60px; border-radius: 4px;
			&:hover { transform: scale(1.05); }
		}
	}
	.pagination-container {
		margin-top: 16px;
		display: flex; justify-content: flex-end;
	}
}
.form-dialog {
	:deep(.el-dialog__body) { padding: 20px 30px; }
	.image-uploader { width: 100%; }
	.dialog-footer { text-align: center; padding-top: 16px; border-top: 1px solid #eee; }
}
</style>
<route lang="json">
{
"meta": {
"layout": "admin",
"title": "房源管理"
}
}
</route>
