好的,基于你现有代码和需求,我帮你整合和完善一套完整示例代码,实现:
- 查询条件的“药品ID”“厂家ID”“进货单ID”改成下拉框远程搜索加载
- 表格显示药品名称、厂家名称、生产日期、保质期、进货时间、距离过期天数、库存(来自pill_drug.num)
- SQL部分联合查询pill_purchase.purchase_time和pill_drug.num
- 表单调整,库存数量不让用户手动输入,只显示库存(只读)
一、前端代码(Vue 单文件组件)
<template>
<div class="app-container">
<!-- 搜索条件 -->
<el-form
:model="queryParams"
ref="queryForm"
size="small"
:inline="true"
v-show="showSearch"
label-width="68px"
>
<el-form-item label="药品" prop="drugId">
<el-select
v-model="queryParams.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 160px"
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家" prop="factoryId">
<el-select
v-model="queryParams.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 180px"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="productionDate">
<el-date-picker
clearable
v-model="queryParams.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 130px"
></el-date-picker>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod">
<el-input
v-model="queryParams.validityPeriod"
placeholder="请输入保质期"
clearable
style="width: 100px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="进货单" prop="purchaseId">
<el-select
v-model="queryParams.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 180px"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="handleQuery"
>
搜索
</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
重置
</el-button>
</el-form-item>
</el-form>
<!-- 操作按钮 -->
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['pill:warning:add']"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['pill:warning:export']"
>
导出
</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
</el-row>
<!-- 表格 -->
<el-table
v-loading="loading"
:data="warningList"
@selection-change="handleSelectionChange"
style="width: 100%"
border
size="small"
>
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键ID" align="center" prop="warningId" width="90" />
<el-table-column label="药品名称" align="center" prop="drugName" width="150" />
<el-table-column label="生产厂家" align="center" prop="factoryName" width="180" />
<el-table-column
label="药品生产日期"
align="center"
prop="productionDate"
width="140"
>
<template #default="{ row }">
<span>{{ parseTime(row.productionDate, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column
label="保质期(天)"
align="center"
prop="validityPeriod"
width="100"
/>
<el-table-column
label="进货时间"
align="center"
prop="purchaseTime"
width="180"
>
<template #default="{ row }">
<span>{{ parseTime(row.purchaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="距离过期天数" align="center" width="120">
<template #default="{ row }">
<span>{{ getRemainingDays(row.productionDate, row.validityPeriod) }}</span>
</template>
</el-table-column>
<el-table-column label="库存数量" align="center" prop="stock" width="100" />
<el-table-column
label="操作"
align="center"
class-name="small-padding fixed-width"
width="120"
>
<template #default="{ row }">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(row)"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(row)"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<pagination
v-show="total > 0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 弹窗-添加或修改 -->
<el-dialog
:title="title"
:visible.sync="open"
width="500px"
append-to-body
@close="cancel"
>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="药品ID" prop="drugId" required>
<el-select
v-model="form.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 100%"
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家ID" prop="factoryId" required>
<el-select
v-model="form.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 100%"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="药品生产日期" prop="productionDate" required>
<el-date-picker
clearable
v-model="form.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod" required>
<el-input
v-model.number="form.validityPeriod"
placeholder="请输入保质期"
style="width: 100%"
type="number"
min="0"
/>
</el-form-item>
<el-form-item label="进货单ID" prop="purchaseId" required>
<el-select
v-model="form.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 100%"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item label="库存数量">
<el-input
v-model="stockDisplay"
disabled
placeholder="自动获取库存数量"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import {
listWarning,
getWarning,
delWarning,
addWarning,
updateWarning,
} from "@/api/pill/warning"
import { listDrugs } from "@/api/pill/drug"
import { listFactories } from "@/api/pill/factory"
import { listPurchases } from "@/api/pill/purchase"
export default {
name: "Warning",
data() {
return {
loading: false,
ids: [],
single: true,
multiple: true,
showSearch: true,
total: 0,
warningList: [],
title: "",
open: false,
drugOptions: [],
factoryOptions: [],
purchaseOptions: [],
drugLoading: false,
factoryLoading: false,
purchaseLoading: false,
queryParams: {
pageNum: 1,
pageSize: 10,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
},
form: {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
},
stockDisplay: "",
rules: {
drugId: [{ required: true, message: "药品ID不能为空", trigger: "change" }],
factoryId: [{ required: true, message: "厂家ID不能为空", trigger: "change" }],
productionDate: [
{ required: true, message: "药品生产日期不能为空", trigger: "change" },
],
validityPeriod: [
{ required: true, message: "保质期不能为空", trigger: "blur" },
{ type: "number", min: 0, message: "保质期必须大于等于0", trigger: "blur" },
],
purchaseId: [{ required: true, message: "进货单ID不能为空", trigger: "change" }],
},
}
},
watch: {
"form.drugId"(newVal) {
this.updateStockDisplay()
},
},
created() {
this.getList()
},
methods: {
/** 解析时间 */
parseTime(time, pattern) {
if (!time) return "-"
const date = new Date(time)
const Y = date.getFullYear()
const M = (date.getMonth() + 1).toString().padStart(2, "0")
const D = date.getDate().toString().padStart(2, "0")
const h = date.getHours().toString().padStart(2, "0")
const m = date.getMinutes().toString().padStart(2, "0")
const s = date.getSeconds().toString().padStart(2, "0")
if (!pattern) return `${Y}-${M}-${D} ${h}:${m}:${s}`
return pattern
.replace("{y}", Y)
.replace("{m}", M)
.replace("{d}", D)
.replace("{h}", h)
.replace("{i}", m)
.replace("{s}", s)
},
/** 计算剩余天数 */
getRemainingDays(productionDate, validityPeriod) {
if (!productionDate || validityPeriod == null) return ""
const prodDate = new Date(productionDate)
const expireDate = new Date(
prodDate.getTime() + validityPeriod * 24 * 60 * 60 * 1000
)
const now = new Date()
const diffTime = expireDate.getTime() - now.getTime()
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
return diffDays >= 0 ? `${diffDays}天` : `已过期${-diffDays}天`
},
/** 查询列表 */
getList() {
this.loading = true
listWarning(this.queryParams)
.then((response) => {
this.warningList = response.rows
this.total = response.total
this.loading = false
})
.catch(() => {
this.loading = false
})
},
// 取消按钮
cancel() {
this.open = false
this.reset()
},
// 表单重置
reset() {
this.form = {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
}
this.stockDisplay = ""
this.resetForm("form")
},
// 重置el-form
resetForm(refName) {
if (this.$refs[refName]) {
this.$refs[refName].resetFields()
}
},
/** 搜索按钮 */
handleQuery() {
this.queryParams.pageNum = 1
this.getList()
},
/** 重置搜索 */
resetQuery() {
this.resetForm("queryForm")
this.queryParams = {
pageNum: 1,
pageSize: 10,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
}
this.handleQuery()
},
// 表格选中
handleSelectionChange(selection) {
this.ids = selection.map((item) => item.warningId)
this.single = selection.length !== 1
this.multiple = !selection.length
},
/** 新增 */
handleAdd() {
this.reset()
this.open = true
this.title = "添加药品有效期预警,用于监控药品保质期"
},
/** 修改 */
handleUpdate(row) {
this.reset()
const warningId = row?.warningId || this.ids[0]
getWarning(warningId).then((response) => {
this.form = response.data
this.open = true
this.title = "修改药品有效期预警,用于监控药品保质期"
// 更新库存显示
this.updateStockDisplay()
})
},
/** 提交表单 */
submitForm() {
this.$refs["form"].validate((valid) => {
if (valid) {
if (this.form.warningId != null) {
updateWarning(this.form).then(() => {
this.$modal.msgSuccess("修改成功")
this.open = false
this.getList()
})
} else {
addWarning(this.form).then(() => {
this.$modal.msgSuccess("新增成功")
this.open = false
this.getList()
})
}
}
})
},
/** 删除 */
handleDelete(row) {
const warningIds = row?.warningId || this.ids
this.$modal
.confirm(
`是否确认删除药品有效期预警,用于监控药品保质期编号为"${warningIds}"的数据项?`
)
.then(() => delWarning(warningIds))
.then(() => {
this.getList()
this.$modal.msgSuccess("删除成功")
})
.catch(() => {})
},
/** 导出 */
handleExport() {
this.download(
"pill/warning/export",
{
...this.queryParams,
},
`warning_${new Date().getTime()}.xlsx`
)
},
// 以下为药品厂家进货下拉远程搜索
async fetchDrugOptions(query) {
if (!query) {
this.drugOptions = []
return
}
this.drugLoading = true
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 })
this.drugOptions = res.rows || []
} catch (error) {
this.drugOptions = []
}
this.drugLoading = false
},
async fetchFactoryOptions(query) {
if (!query) {
this.factoryOptions = []
return
}
this.factoryLoading = true
try {
const res = await listFactories({ factoryName: query, pageNum: 1, pageSize: 20 })
this.factoryOptions = res.rows || []
} catch (error) {
this.factoryOptions = []
}
this.factoryLoading = false
},
async fetchPurchaseOptions(query) {
if (!query) {
this.purchaseOptions = []
return
}
this.purchaseLoading = true
try {
// 简单使用purchaseId模糊匹配或其他字段,服务器端接口可调整
const res = await listPurchases({ purchaseId: query, pageNum: 1, pageSize: 20 })
this.purchaseOptions = res.rows || []
} catch (error) {
this.purchaseOptions = []
}
this.purchaseLoading = false
},
updateStockDisplay() {
// 根据选中的药品ID,查找库存,优先从查询结果中找,或者调接口获得
if (!this.form.drugId) {
this.stockDisplay = ""
return
}
// 在drugOptions中查找库存num
const drug = this.drugOptions.find((d) => d.drug_id === this.form.drugId)
if (drug && drug.num !== undefined) {
this.stockDisplay = drug.num
} else {
// 如果drugOptions 无法满足,API重新请求
listDrugs({ drugId: this.form.drugId, pageNum: 1, pageSize: 1 })
.then(res => {
if (res.rows && res.rows.length > 0) {
this.stockDisplay = res.rows[0].num || ""
} else {
this.stockDisplay = ""
}
})
.catch(() => (this.stockDisplay = ""))
}
},
},
}
</script>
二、后端 Mapper XML 核心部分
<mapper namespace="com.ruoyi.pill.mapper.PillExpiryWarningMapper">
<resultMap id="PillExpiryWarningResult" type="com.ruoyi.pill.domain.PillExpiryWarning">
<result property="warningId" column="warning_id" />
<result property="drugId" column="drug_id" />
<result property="factoryId" column="factory_id" />
<result property="productionDate" column="production_date" />
<result property="validityPeriod" column="validity_period" />
<result property="purchaseId" column="purchase_id" />
<result property="stock" column="stock" />
<result property="createTime" column="create_time" />
<result property="drugName" column="drug_name"/>
<result property="factoryName" column="factory_name"/>
<result property="purchaseTime" column="purchase_time"/>
<result property="daysToExpire" column="days_to_expire"/>
</resultMap>
<sql id="BaseSelectSql">
select
pe.warning_id,
pe.drug_id,
pe.factory_id,
pe.production_date,
pe.validity_period,
pe.purchase_id,
pd.num as stock,
pe.create_time,
pd.drug_name,
pf.factory_name,
pp.purchase_time,
datediff(date_add(pe.production_date, interval pe.validity_period day), curdate()) as days_to_expire
from pill_expiry_warning pe
LEFT JOIN pill_drug pd ON pe.drug_id = pd.drug_id
LEFT JOIN pill_factory pf ON pe.factory_id = pf.factory_id
LEFT JOIN pill_purchase pp ON pe.purchase_id = pp.purchase_id
</sql>
<select id="selectPillExpiryWarningList" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
<where>
<if test="drugId != null "> and pe.drug_id = #{drugId}</if>
<if test="factoryId != null "> and pe.factory_id = #{factoryId}</if>
<if test="productionDate != null "> and pe.production_date = #{productionDate}</if>
<if test="validityPeriod != null "> and pe.validity_period = #{validityPeriod}</if>
<if test="purchaseId != null "> and pe.purchase_id = #{purchaseId}</if>
</where>
</select>
<select id="selectPillExpiryWarningByWarningId" parameterType="Long" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
where pe.warning_id = #{warningId}
</select>
<insert id="insertPillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" useGeneratedKeys="true" keyProperty="warningId">
insert into pill_expiry_warning
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="drugId != null">drug_id,</if>
<if test="factoryId != null">factory_id,</if>
<if test="productionDate != null">production_date,</if>
<if test="validityPeriod != null">validity_period,</if>
<if test="purchaseId != null">purchase_id,</if>
<if test="stock != null">stock,</if>
<if test="createTime != null">create_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="drugId != null">#{drugId},</if>
<if test="factoryId != null">#{factoryId},</if>
<if test="productionDate != null">#{productionDate},</if>
<if test="validityPeriod != null">#{validityPeriod},</if>
<if test="purchaseId != null">#{purchaseId},</if>
<if test="stock != null">#{stock},</if>
<if test="createTime != null">#{createTime},</if>
</trim>
</insert>
<update id="updatePillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning">
update pill_expiry_warning
<set>
<if test="drugId != null">drug_id = #{drugId},</if>
<if test="factoryId != null">factory_id = #{factoryId},</if>
<if test="productionDate != null">production_date = #{productionDate},</if>
<if test="validityPeriod != null">validity_period = #{validityPeriod},</if>
<if test="purchaseId != null">purchase_id = #{purchaseId},</if>
<if test="stock != null">stock = #{stock},</if>
<if test="createTime != null">create_time = #{createTime},</if>
</set>
where warning_id = #{warningId}
</update>
<delete id="deletePillExpiryWarningByWarningId" parameterType="Long">
delete from pill_expiry_warning where warning_id = #{warningId}
</delete>
<delete id="deletePillExpiryWarningByWarningIds" parameterType="Long[]">
delete from pill_expiry_warning where warning_id in
<foreach item="warningId" collection="array" open="(" separator="," close=")">
#{warningId}
</foreach>
</delete>
</mapper>
三、建议补充API接口
示例前端代码中调用了:
import { listDrugs } from "@/api/pill/drug"
import { listFactories } from "@/api/pill/factory"
import { listPurchases } from "@/api/pill/purchase"
这些列表接口需要实现分页和模糊搜索。简单接口示例如下:
// pill/drug.js
import request from '@/utils/request'
export function listDrugs(params) {
return request({
url: '/pill/drug/list',
method: 'get',
params: params
})
}
// pill/factory.js
import request from '@/utils/request'
export function listFactories(params) {
return request({
url: '/pill/factory/list',
method: 'get',
params: params
})
}
// pill/purchase.js
import request from '@/utils/request'
export function listPurchases(params) {
return request({
url: '/pill/purchase/list',
method: 'get',
params: params
})
}
后端对应list接口实现根据传递参数模糊查询分页即可。
四、总结
- 前端搜索表单:药品、厂家、进货单为远程搜索下拉,方便选择
- 表格展示所有需要字段,包括进货时间和库存
- 表单编辑时库存只读展示,不可修改
- SQL中join查询进货时间和库存数据,库存取自pill_drug.num字段,进货时间取自pill_purchase.purchase_time
如果你有需要,我可以帮你写后端Controller层、Service层示例代码。或者帮你写完整的后端分页查询接口代码。需要告诉我!