package com.ruoyi.web.controller.pill;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pill.domain.PillExpiryWarning;
import com.ruoyi.pill.service.IPillExpiryWarningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 药品有效期预警，用于监控药品保质期Controller
 *
 * @author wuweiqiang
 * @date 2025-05-20
 */
@RestController
@RequestMapping("/pill/warning")
public class PillExpiryWarningController extends BaseController
{
    @Autowired
    private IPillExpiryWarningService pillExpiryWarningService;

    @PreAuthorize("@ss.hasPermi('pill:warning:list')")
    @GetMapping("/list")
    public TableDataInfo list(PillExpiryWarning pillExpiryWarning)
    {
        startPage();
        // 确保onlyExpire会映射到实体，并传给service和mapper
        List<PillExpiryWarning> list = pillExpiryWarningService.selectPillExpiryWarningList(pillExpiryWarning);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('pill:warning:export')")
    @Log(title = "药品有效期预警，用于监控药品保质期", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PillExpiryWarning pillExpiryWarning)
    {
        List<PillExpiryWarning> list = pillExpiryWarningService.selectPillExpiryWarningList(pillExpiryWarning);
        ExcelUtil<PillExpiryWarning> util = new ExcelUtil<PillExpiryWarning>(PillExpiryWarning.class);
        util.exportExcel(response, list, "药品有效期预警，用于监控药品保质期数据");
    }

    /**
     * 获取药品有效期预警，用于监控药品保质期详细信息
     */
    @PreAuthorize("@ss.hasPermi('pill:warning:query')")
    @GetMapping(value = "/{warningId}")
    public AjaxResult getInfo(@PathVariable("warningId") Long warningId)
    {
        return success(pillExpiryWarningService.selectPillExpiryWarningByWarningId(warningId));
    }

    /**
     * 新增药品有效期预警，用于监控药品保质期
     */
    @PreAuthorize("@ss.hasPermi('pill:warning:add')")
    @Log(title = "药品有效期预警，用于监控药品保质期", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PillExpiryWarning pillExpiryWarning)
    {
        return toAjax(pillExpiryWarningService.insertPillExpiryWarning(pillExpiryWarning));
    }

    /**
     * 修改药品有效期预警，用于监控药品保质期
     */
    @PreAuthorize("@ss.hasPermi('pill:warning:edit')")
    @Log(title = "药品有效期预警，用于监控药品保质期", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PillExpiryWarning pillExpiryWarning)
    {
        return toAjax(pillExpiryWarningService.updatePillExpiryWarning(pillExpiryWarning));
    }

    /**
     * 删除药品有效期预警，用于监控药品保质期
     */
    @PreAuthorize("@ss.hasPermi('pill:warning:remove')")
    @Log(title = "药品有效期预警，用于监控药品保质期", businessType = BusinessType.DELETE)
   @DeleteMapping("/{warningIds}")
    public AjaxResult remove(@PathVariable Long[] warningIds)
    {
        return toAjax(pillExpiryWarningService.deletePillExpiryWarningByWarningIds(warningIds));
    }
}


package com.ruoyi.pill.domain;

import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;

/**
 * 药品有效期预警，用于监控药品保质期对象 pill_expiry_warning
 *
 * @author wuweiqiang
 * @date 2025-05-20
 */
public class PillExpiryWarning extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 是否只查询15天内过期 */
    private Boolean onlyExpire;

    public Boolean getOnlyExpire() {
        return onlyExpire;
    }

    public void setOnlyExpire(Boolean onlyExpire) {
        this.onlyExpire = onlyExpire;
    }

    /** 主键ID */
    private Long warningId;

    /** 药品ID（关联pill_drug.drug_id） */
    @Excel(name = "药品ID", readConverterExp = "关=联pill_drug.drug_id")
    private Long drugId;

    /** 厂家ID（关联pill_factory.factory_id） */
    @Excel(name = "厂家ID", readConverterExp = "关=联pill_factory.factory_id")
    private Long factoryId;

    /** 药品生产日期 */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @Excel(name = "药品生产日期", width = 30, dateFormat = "yyyy-MM-dd")
    private Date productionDate;

    /** 保质期（天） */
    @Excel(name = "保质期", readConverterExp = "天=")
    private Long validityPeriod;

    /** 进货单ID（关联pill_purchase.purchase_id） */
    @Excel(name = "进货单ID", readConverterExp = "关=联pill_purchase.purchase_id")
    private Long purchaseId;

    /** 库存数量 */
    @Excel(name = "库存数量")
    private Long stock;

    /** 药品名称（来自pill_drug） */
    @Excel(name = "药品名称")
    private String drugName;

    /** 厂家名称（来自pill_factory） */
    @Excel(name = "生产厂家")
    private String factoryName;

    /** 进货时间（来自pill_purchase） */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @Excel(name = "进货时间", width = 30, dateFormat = "yyyy-MM-dd")
    private Date purchaseTime;

    /** 距离过期天数 */
    @Excel(name = "距离过期天数")
    private Long daysToExpire;

    public void setWarningId(Long warningId)
    {
        this.warningId = warningId;
    }

    public Long getWarningId()
    {
        return warningId;
    }

    public void setDrugId(Long drugId)
    {
        this.drugId = drugId;
    }

    public Long getDrugId()
    {
        return drugId;
    }

    public void setFactoryId(Long factoryId)
    {
        this.factoryId = factoryId;
    }

    public Long getFactoryId()
    {
        return factoryId;
    }

    public void setProductionDate(Date productionDate)
    {
        this.productionDate = productionDate;
    }

    public Date getProductionDate()
    {
        return productionDate;
    }

    public void setValidityPeriod(Long validityPeriod)
    {
        this.validityPeriod = validityPeriod;
    }

    public Long getValidityPeriod()
    {
        return validityPeriod;
    }

    public void setPurchaseId(Long purchaseId)
    {
        this.purchaseId = purchaseId;
    }

    public Long getPurchaseId()
    {
        return purchaseId;
    }

    public void setStock(Long stock)
    {
        this.stock = stock;
    }

    public Long getStock()
    {
        return stock;
    }

    public String getDrugName() {
        return drugName;
    }

    public void setDrugName(String drugName) {
        this.drugName = drugName;
    }

    public String getFactoryName() {
        return factoryName;
    }

    public void setFactoryName(String factoryName) {
        this.factoryName = factoryName;
    }

    public Date getPurchaseTime() {
        return purchaseTime;
    }

    public void setPurchaseTime(Date purchaseTime) {
        this.purchaseTime = purchaseTime;
    }

    public Long getDaysToExpire() {
        return daysToExpire;
    }

    public void setDaysToExpire(Long daysToExpire) {
        this.daysToExpire = daysToExpire;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
                .append("warningId", getWarningId())
                .append("drugId", getDrugId())
                .append("factoryId", getFactoryId())
                .append("productionDate", getProductionDate())
                .append("validityPeriod", getValidityPeriod())
                .append("purchaseId", getPurchaseId())
                .append("stock", getStock())
                .append("drugName", getDrugName())
                .append("factoryName", getFactoryName())
                .append("purchaseTime", getPurchaseTime())
                .append("daysToExpire", getDaysToExpire())
                .append("createTime", getCreateTime())
                .toString();
    }
}


package com.ruoyi.pill.mapper;

import java.util.List;
import com.ruoyi.pill.domain.PillExpiryWarning;

/**
 * 药品有效期预警，用于监控药品保质期Mapper接口
 * 
 * @author wuweiqiang
 * @date 2025-05-20
 */
public interface PillExpiryWarningMapper 
{
    /**
     * 查询药品有效期预警，用于监控药品保质期
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 药品有效期预警，用于监控药品保质期
     */
    public PillExpiryWarning selectPillExpiryWarningByWarningId(Long warningId);

    /**
     * 查询药品有效期预警，用于监控药品保质期列表
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 药品有效期预警，用于监控药品保质期集合
     */
    public List<PillExpiryWarning> selectPillExpiryWarningList(PillExpiryWarning pillExpiryWarning);

    /**
     * 新增药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    public int insertPillExpiryWarning(PillExpiryWarning pillExpiryWarning);

    /**
     * 修改药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    public int updatePillExpiryWarning(PillExpiryWarning pillExpiryWarning);

    /**
     * 删除药品有效期预警，用于监控药品保质期
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 结果
     */
    public int deletePillExpiryWarningByWarningId(Long warningId);

    /**
     * 批量删除药品有效期预警，用于监控药品保质期
     * 
     * @param warningIds 需要删除的数据主键集合
     * @return 结果
     */
    public int deletePillExpiryWarningByWarningIds(Long[] warningIds);
}


package com.ruoyi.pill.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pill.mapper.PillExpiryWarningMapper;
import com.ruoyi.pill.domain.PillExpiryWarning;
import com.ruoyi.pill.service.IPillExpiryWarningService;

/**
 * 药品有效期预警，用于监控药品保质期Service业务层处理
 * 
 * @author wuweiqiang
 * @date 2025-05-20
 */
@Service
public class PillExpiryWarningServiceImpl implements IPillExpiryWarningService 
{
    @Autowired
    private PillExpiryWarningMapper pillExpiryWarningMapper;

    /**
     * 查询药品有效期预警，用于监控药品保质期
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 药品有效期预警，用于监控药品保质期
     */
    @Override
    public PillExpiryWarning selectPillExpiryWarningByWarningId(Long warningId)
    {
        return pillExpiryWarningMapper.selectPillExpiryWarningByWarningId(warningId);
    }

    /**
     * 查询药品有效期预警，用于监控药品保质期列表
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 药品有效期预警，用于监控药品保质期
     */
    @Override
    public List<PillExpiryWarning> selectPillExpiryWarningList(PillExpiryWarning pillExpiryWarning)
    {
        return pillExpiryWarningMapper.selectPillExpiryWarningList(pillExpiryWarning);
    }

    /**
     * 新增药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    @Override
    public int insertPillExpiryWarning(PillExpiryWarning pillExpiryWarning)
    {
        pillExpiryWarning.setCreateTime(DateUtils.getNowDate());
        return pillExpiryWarningMapper.insertPillExpiryWarning(pillExpiryWarning);
    }

    /**
     * 修改药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    @Override
    public int updatePillExpiryWarning(PillExpiryWarning pillExpiryWarning)
    {
        return pillExpiryWarningMapper.updatePillExpiryWarning(pillExpiryWarning);
    }

    /**
     * 批量删除药品有效期预警，用于监控药品保质期
     * 
     * @param warningIds 需要删除的药品有效期预警，用于监控药品保质期主键
     * @return 结果
     */
    @Override
    public int deletePillExpiryWarningByWarningIds(Long[] warningIds)
    {
        return pillExpiryWarningMapper.deletePillExpiryWarningByWarningIds(warningIds);
    }

    /**
     * 删除药品有效期预警，用于监控药品保质期信息
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 结果
     */
    @Override
    public int deletePillExpiryWarningByWarningId(Long warningId)
    {
        return pillExpiryWarningMapper.deletePillExpiryWarningByWarningId(warningId);
    }
}

package com.ruoyi.pill.service;

import java.util.List;
import com.ruoyi.pill.domain.PillExpiryWarning;

/**
 * 药品有效期预警，用于监控药品保质期Service接口
 * 
 * @author wuweiqiang
 * @date 2025-05-20
 */
public interface IPillExpiryWarningService 
{
    /**
     * 查询药品有效期预警，用于监控药品保质期
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 药品有效期预警，用于监控药品保质期
     */
    public PillExpiryWarning selectPillExpiryWarningByWarningId(Long warningId);

    /**
     * 查询药品有效期预警，用于监控药品保质期列表
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 药品有效期预警，用于监控药品保质期集合
     */
    public List<PillExpiryWarning> selectPillExpiryWarningList(PillExpiryWarning pillExpiryWarning);

    /**
     * 新增药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    public int insertPillExpiryWarning(PillExpiryWarning pillExpiryWarning);

    /**
     * 修改药品有效期预警，用于监控药品保质期
     * 
     * @param pillExpiryWarning 药品有效期预警，用于监控药品保质期
     * @return 结果
     */
    public int updatePillExpiryWarning(PillExpiryWarning pillExpiryWarning);

    /**
     * 批量删除药品有效期预警，用于监控药品保质期
     * 
     * @param warningIds 需要删除的药品有效期预警，用于监控药品保质期主键集合
     * @return 结果
     */
    public int deletePillExpiryWarningByWarningIds(Long[] warningIds);

    /**
     * 删除药品有效期预警，用于监控药品保质期信息
     * 
     * @param warningId 药品有效期预警，用于监控药品保质期主键
     * @return 结果
     */
    public int deletePillExpiryWarningByWarningId(Long warningId);
}


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<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>
            <!-- 只有在onlyExpire为true时才增加过期数据过滤 -->
            <if test="onlyExpire != null and onlyExpire == true">
                AND datediff(date_add(pe.production_date, interval pe.validity_period day), curdate()) &lt;= 15
            </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>

现在要两独立业务模块写接口（pill/drug和pill/factory）。
分别单独做“药品列表”和“厂家列表”接口，前端调用以做下拉框数据绑定。<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="药品ID" prop="drugId">
        <el-input v-model="queryParams.drugId" placeholder="请输入药品ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="厂家ID" prop="factoryId">
        <el-input v-model="queryParams.factoryId" placeholder="请输入厂家ID" clearable @keyup.enter.native="handleQuery" />
      </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="请选择生产日期"/>
      </el-form-item>
      <el-form-item label="保质期" prop="validityPeriod">
        <el-input v-model="queryParams.validityPeriod" placeholder="请输入保质期" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="进货单ID" prop="purchaseId">
        <el-input v-model="queryParams.purchaseId" placeholder="请输入进货单ID" clearable @keyup.enter.native="handleQuery" />
      </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-button type="warning" size="mini" :plain="!queryParams.onlyExpire" @click="toggleOnlyExpire">
          {{ queryParams.onlyExpire ? '查看全部' : '查看过期' }}
        </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"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="warningList" @selection-change="handleSelectionChange" stripe border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键ID" align="center" prop="warningId"/>
      <el-table-column label="药品ID" align="center" prop="drugId"/>
      <el-table-column label="药品名称" align="center" prop="drugName"/>
      <el-table-column label="厂家ID" align="center" prop="factoryId"/>
      <el-table-column label="厂家名称" align="center" prop="factoryName"/>
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" align="center" prop="validityPeriod"/>
      <el-table-column label="进货单ID" align="center" prop="purchaseId"/>
      <el-table-column label="库存数量" align="center" prop="stock"/>
      <el-table-column label="剩余天数" align="center" prop="daysToExpire" width="110">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.daysToExpire <= 15 ? 'red' : 'inherit', fontWeight: scope.row.daysToExpire <= 15 ? 'bold' : 'normal' }">
            {{ scope.row.daysToExpire }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['pill:warning:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.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>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品ID" prop="drugId">
          <el-input v-model="form.drugId" placeholder="请输入药品ID"/>
        </el-form-item>
        <el-form-item label="厂家ID" prop="factoryId">
          <el-input v-model="form.factoryId" placeholder="请输入厂家ID"/>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择生产日期"/>

        </el-form-item>
        <el-form-item label="保质期" prop="validityPeriod">
          <el-input v-model="form.validityPeriod" placeholder="请输入保质期"/>
        </el-form-item>
        <el-form-item label="进货单ID" prop="purchaseId">
          <el-input v-model="form.purchaseId" placeholder="请输入进货单ID"/>
        </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"

export default {
  name: "Warning",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      warningList: [],
      title: "",
      open: false,
      // 新增onlyExpire字段控制是否只看过期15天内的数据
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drugId: null,
        factoryId: null,
        productionDate: null,
        validityPeriod: null,
        purchaseId: null,
        onlyExpire: false, // 新增标识
      },
      form: {},
      rules: {
        drugId: [{ required: true, message: "药品ID不能为空", trigger: "blur" }],
        factoryId: [{ required: true, message: "厂家ID不能为空", trigger: "blur" }],
        productionDate: [{ required: true, message: "生产日期不能为空", trigger: "blur" }],
        validityPeriod: [{ required: true, message: "保质期不能为空", trigger: "blur" }],
        purchaseId: [{ required: true, message: "进货单ID不能为空", trigger: "blur" }],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 点击“查看过期”按钮，切换筛选状态
    toggleOnlyExpire() {
      this.queryParams.onlyExpire = !this.queryParams.onlyExpire
      this.queryParams.pageNum = 1
      this.getList()
    },
    getList() {
      this.loading = true
      // 这里调用接口时把onlyExpire传递给后端，后端根据该字段筛选daysToExpire <= 15
      listWarning(this.queryParams).then(response => {
        this.warningList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        warningId: null,
        drugId: null,
        factoryId: null,
        productionDate: null,
        validityPeriod: null,
        purchaseId: null,
        createTime: null,
        stock: null,
        daysToExpire: null
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.onlyExpire = false // 重置时恢复全部数据
      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 = "添加药品有效期预警，用于监控药品保质期"
      // 新增时，set stock = 0 避免数据库报错
      this.form.stock = 0
    },
    handleUpdate(row) {
      this.reset()
      const warningId = row.warningId || this.ids
      getWarning(warningId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改药品有效期预警，用于监控药品保质期"
        if (this.form.stock == null) {
          this.form.stock = 0
        }
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.stock == null) {
            this.form.stock = 0
          }
          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(() => {
        return delWarning(warningIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport() {
      // 导出时只传onlyExpire参数，告诉后端导出筛选后的数据
      this.download('pill/warning/export', { ...this.queryParams }, `warning_${Date.now()}.xlsx`)
    }
  }
}
</script>
import request from '@/utils/request'

// 查询药品有效期预警，用于监控药品保质期列表
export function listWarning(query) {
  return request({
    url: '/pill/warning/list',
    method: 'get',
    params: query
  })
}

// 查询药品有效期预警，用于监控药品保质期详细
export function getWarning(warningId) {
  return request({
    url: '/pill/warning/' + warningId,
    method: 'get'
  })
}

// 新增药品有效期预警，用于监控药品保质期
export function addWarning(data) {
  return request({
    url: '/pill/warning',
    method: 'post',
    data: data
  })
}

// 修改药品有效期预警，用于监控药品保质期
export function updateWarning(data) {
  return request({
    url: '/pill/warning',
    method: 'put',
    data: data
  })
}

// 删除药品有效期预警，用于监控药品保质期
export function delWarning(warningId) {
  return request({
    url: '/pill/warning/' + warningId,
    method: 'delete'
  })
}