<template>
	<div>
		<!-- 搜索和添加按钮 -->
		<el-row :gutter="20" class="mb-4">
			<el-col :span="6">
				<el-input v-model="state.queryParams.medicineName" placeholder="药品名称" clearable @clear="handleSearch" @keyup.enter="handleSearch"/>
			</el-col>
			<el-col :span="6">
				<el-input v-model="state.queryParams.category" placeholder="药品类别" clearable @clear="handleSearch" @keyup.enter="handleSearch"/>
			</el-col>
			<el-col :span="12" class="text-right">
				<el-button type="primary" @click="handleSearch">搜索</el-button>
				<el-button type="success" @click="openAddDialog">添加药品</el-button>
			</el-col>
		</el-row>

		<!-- 表格 -->
		<el-table :data="state.tableData" border stripe v-loading="state.loading">
			<el-table-column prop="medicineName" label="药品名称" align="center" />
			<el-table-column prop="genericName" label="通用名称" align="center" />
			<el-table-column prop="specification" label="规格" align="center" />
			<el-table-column prop="manufacturer" label="生产厂家" align="center" />
			<el-table-column prop="category" label="药品类别" align="center" />
			<el-table-column prop="unitPrice" label="单价(元)" align="center">
				<template #default="{row}">
					{{ row.unitPrice.toFixed(2) }}
				</template>
			</el-table-column>
			<el-table-column prop="stockQuantity" label="库存数量" align="center" />
			<el-table-column prop="expiryDate" label="有效期至" align="center" />
			<el-table-column label="操作" align="center" width="180">
				<template #default="scope">
					<el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
			<template #empty>
				<el-empty description="暂无数据" />
			</template>
		</el-table>

		<!-- 分页 -->
		<el-pagination
			v-if="state.total > 0"
			class="mt-4"
			v-model:current-page="state.queryParams.pageNum"
			v-model:page-size="state.queryParams.pageSize"
			:total="state.total"
			:page-sizes="[10, 20, 30, 50]"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handlePageChange"
		/>

		<!-- 新增/编辑对话框 -->
		<el-dialog
			v-model="state.dialogVisible"
			:title="state.dialogTitle"
			width="50%"
			:close-on-click-modal="false"
		>
			<el-form
				ref="formRef"
				:model="state.formData"
				:rules="state.formRules"
				label-width="120px"
			>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="药品名称" prop="medicineName">
							<el-input v-model="state.formData.medicineName" placeholder="请输入药品名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="通用名称" prop="genericName">
							<el-input v-model="state.formData.genericName" placeholder="请输入通用名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="规格" prop="specification">
							<el-input v-model="state.formData.specification" placeholder="请输入规格" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="生产厂家" prop="manufacturer">
							<el-input v-model="state.formData.manufacturer" placeholder="请输入生产厂家" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="批号" prop="batchNumber">
							<el-input v-model="state.formData.batchNumber" placeholder="请输入批号" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="生产日期" prop="productionDate">
							<el-date-picker
								v-model="state.formData.productionDate"
								type="date"
								placeholder="请选择生产日期"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="有效期至" prop="expiryDate">
							<el-date-picker
								v-model="state.formData.expiryDate"
								type="date"
								placeholder="请选择有效期"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="药品类别" prop="category">
							<el-input v-model="state.formData.category" placeholder="请输入药品类别" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单价(元)" prop="unitPrice">
							<el-input-number
								v-model="state.formData.unitPrice"
								:min="0"
								:precision="2"
								:controls="false"
								class="w-full"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="库存数量" prop="stockQuantity">
							<el-input-number
								v-model="state.formData.stockQuantity"
								:min="0"
								:controls="false"
								class="w-full"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="补货警戒线" prop="reorderLevel">
							<el-input-number
								v-model="state.formData.reorderLevel"
								:min="0"
								:controls="false"
								class="w-full"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="储存条件" prop="storageConditions">
							<el-input v-model="state.formData.storageConditions" placeholder="请输入储存条件" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="需要处方" prop="prescriptionRequired">
							<el-radio-group v-model="state.formData.prescriptionRequired">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="state.dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit">保存</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Medicine {
	id?: number
	medicineName: string
	genericName?: string
	specification: string
	manufacturer?: string
	batchNumber?: string
	productionDate?: string
	expiryDate?: string
	category?: string
	unitPrice: number
	stockQuantity: number
	reorderLevel?: number
	storageConditions?: string
	prescriptionRequired?: number
}

const formRef = ref<FormInstance>()
const state = reactive({
	loading: false,
	tableData: [] as Medicine[],
	total: 0,
	dialogVisible: false,
	dialogTitle: '',
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		medicineName: '',
		category: ''
	},
	formData: {
		medicineName: '',
		genericName: '',
		specification: '',
		manufacturer: '',
		batchNumber: '',
		productionDate: '',
		expiryDate: '',
		category: '',
		unitPrice: 0,
		stockQuantity: 0,
		reorderLevel: 10,
		storageConditions: '',
		prescriptionRequired: 1
	} as Medicine,
	formRules: {
		medicineName: [
			{ required: true, message: '请输入药品名称', trigger: 'blur' }
		],
		specification: [
			{ required: true, message: '请输入规格', trigger: 'blur' }
		],
		unitPrice: [
			{ required: true, message: '请输入单价', trigger: 'blur' },
			{ type: 'number', min: 0, message: '单价不能小于0', trigger: 'blur' }
		],
		stockQuantity: [
			{ required: true, message: '请输入库存数量', trigger: 'blur' },
			{ type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
		],
		expiryDate: [
			{ required: true, message: '请选择有效期', trigger: 'change' }
		]
	} as FormRules
})

// 获取药品列表
const getMedicineList = async () => {
	try {
		state.loading = true
		// 这里替换为实际的API调用
		const res = await adminRequest.get('sys/management/page', { params: state.queryParams })
		state.tableData = res.data.list
		state.total = res.data.total
		state.total = state.tableData.length
	} catch (error) {
		ElMessage.error('获取药品列表失败')
	} finally {
		state.loading = false
	}
}

// 搜索
const handleSearch = () => {
	state.queryParams.pageNum = 1
	getMedicineList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
	state.queryParams.pageSize = val
	getMedicineList()
}

// 页码改变
const handlePageChange = (val: number) => {
	state.queryParams.pageNum = val
	getMedicineList()
}

// 打开新增对话框
const openAddDialog = () => {
	state.dialogTitle = '新增药品'
	state.formData = {
		medicineName: '',
		genericName: '',
		specification: '',
		manufacturer: '',
		batchNumber: '',
		productionDate: '',
		expiryDate: '',
		category: '',
		unitPrice: 0,
		stockQuantity: 0,
		reorderLevel: 10,
		storageConditions: '',
		prescriptionRequired: 1
	}
	state.dialogVisible = true
}

// 打开编辑对话框
const handleEdit = (row: Medicine) => {
	state.dialogTitle = '编辑药品信息'
	state.formData = { ...row }
	state.dialogVisible = true
}

// 提交表单
const handleSubmit = () => {
	formRef.value?.validate(async (valid) => {
		if (!valid) return

		try {
			// 这里替换为实际的API调用
			if (state.formData.id) {
				// 更新
				await adminRequest.put('sys/management', state.formData)
				ElMessage.success('修改成功')
			} else {
				// 新增
				await adminRequest.post('sys/management', state.formData)
				ElMessage.success('添加成功')
			}
			state.dialogVisible = false
			getMedicineList()
		} catch (error) {
			ElMessage.error('操作失败')
		}
	})
}

// 删除药品
const handleDelete = (id: number) => {
	ElMessageBox.confirm('确定要删除该药品吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		try {
			// 这里替换为实际的API调用
			await adminRequest.delete(`sys/management/${id}`)
			ElMessage.success('删除成功')
			getMedicineList()
		} catch (error) {
			ElMessage.error('删除失败')
		}
	}).catch(() => {})
}

onMounted(() => {
	getMedicineList()
})
</script>

<style scoped>
.mb-4 {
	margin-bottom: 1rem;
}
.mt-4 {
	margin-top: 1rem;
}
.text-right {
	text-align: right;
}
.w-full {
	width: 100%;
}
</style>
<route lang="json">
{
"meta": {
"layout": "admin"
}
}
</route>
