去除远程搜索，新增的药品id，厂家id，进货单id直接加载完整列表用于下拉框选择<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"
          default-first-option
        >
          <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"
          default-first-option
        >
          <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-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"
          default-first-option
        >
          <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%"
            default-first-option
          >
            <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%"
            default-first-option
          >
            <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%"
            default-first-option
          >
            <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 = "添加药品有效期预警，用于监控药品保质期"

      // 预加载下拉选项，方便选择
      this.fetchDrugOptions()
      this.fetchFactoryOptions()
      this.fetchPurchaseOptions()
    },
    /** 修改 */
    async handleUpdate(row) {
      this.reset()
      const warningId = row?.warningId || this.ids[0]
      const response = await getWarning(warningId)
      this.form = response.data
      this.open = true
      this.title = "修改药品有效期预警，用于监控药品保质期"

      // 确保修改时对应选项存在于下拉列表中，否则下拉无法显示label
      await this.fetchDrugOptions()
      if (!this.drugOptions.find(d => d.drug_id === this.form.drugId)) {
        try {
          const res = await listDrugs({ drugId: this.form.drugId, pageNum: 1, pageSize: 1 })
          if (res.rows.length) this.drugOptions.push(res.rows[0])
        } catch {}
      }

      await this.fetchFactoryOptions()
      if (!this.factoryOptions.find(f => f.factory_id === this.form.factoryId)) {
        try {
          // 如果你有查询单个厂家的接口，可调用补充。示例：
          // const res = await getFactoryById(this.form.factoryId)
          // this.factoryOptions.push(res.data)
        } catch {}
      }

      await this.fetchPurchaseOptions()
      if (!this.purchaseOptions.find(p => p.purchase_id === this.form.purchaseId)) {
        try {
          // 同理，查询单个进货单接口，示例：
          // const res = await getPurchaseById(this.form.purchaseId)
          // this.purchaseOptions.push(res.data)
        } catch {}
      }

      // 更新库存显示
      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 = '') {
      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 = '') {
      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 = '') {
      this.purchaseLoading = true
      try {
        const res = await listPurchases({ purchaseId: query, pageNum: 1, pageSize: 20 })
        this.purchaseOptions = res.rows || []
      } catch (error) {
        this.purchaseOptions = []
      }
      this.purchaseLoading = false
    },

    // 根据选中的药品ID，更新库存显示
    updateStockDisplay() {
      if (!this.form.drugId) {
        this.stockDisplay = ""
        return
      }
      const drug = this.drugOptions.find((d) => d.drug_id === this.form.drugId)
      if (drug && drug.num !== undefined) {
        this.stockDisplay = drug.num
      } else {
        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>