<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" placeholder="请选择药品" clearable>
          <el-option v-for="item in drugList" :key="item.drugId" :label="item.drugName" :value="item.drugId" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产厂家" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择生产厂家" clearable>
          <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName" :value="item.factoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="进货时间" prop="purchaseTime">
        <el-date-picker clearable
                        v-model="queryParams.purchaseTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择进货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="进货单价" prop="purchasePrice">
        <el-input
          v-model="queryParams.purchasePrice"
          placeholder="请输入进货单价"
          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-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:purchase: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:purchase: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:purchase: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:purchase:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="进货单ID" align="center" prop="purchaseId" />
      <el-table-column label="药品名称" align="center" prop="drugName" />
      <el-table-column label="生产厂家" align="center" prop="factoryName" />
      <el-table-column label="进货时间" align="center" prop="purchaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进货单价" align="center" prop="purchasePrice" />
      <el-table-column label="进货数量" align="center" prop="purchaseNum" />
      <el-table-column label="进货备注" align="center" prop="remark" />
      <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:purchase:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pill:purchase: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="药品名称" prop="drugId">
          <el-select v-model="form.drugId" placeholder="请选择药品" clearable>
            <el-option v-for="item in drugList" :key="item.drugId" :label="item.drugName" :value="item.drugId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂家" prop="factoryId">
          <el-select v-model="form.factoryId" placeholder="请选择生产厂家" clearable>
            <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName" :value="item.factoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="进货时间" prop="purchaseTime">
          <el-date-picker clearable
                          v-model="form.purchaseTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择进货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进货单价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进货单价" />
        </el-form-item>
        <el-form-item label="进货数量" prop="purchaseNum">
          <el-input v-model="form.purchaseNum" placeholder="请输入进货数量" />
        </el-form-item>
        <el-form-item label="进货备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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 { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/pill/purchase"
import { listDrug } from "@/api/pill/drug" // 新增药品API
import { listFactory } from "@/api/pill/factory" // 新增厂家API

export default {
  name: "Purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品进货记录表格数据
      purchaseList: [],
      // 药品列表
      drugList: [],
      // 厂家列表
      factoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drugId: null,
        factoryId: null,
        purchaseTime: null,
        purchasePrice: null,
        purchaseNum: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        drugId: [
          { required: true, message: "请选择药品", trigger: "change" }
        ],
        factoryId: [
          { required: true, message: "请选择生产厂家", trigger: "change" }
        ],
        purchaseTime: [
          { required: true, message: "请选择进货时间", trigger: "blur" }
        ],
        purchasePrice: [
         { required: true, message: "请输入进货单价", trigger: "blur" },
         { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字值', trigger: 'blur' }
       ],
       purchaseNum: [
         { required: true, message: "请输入进货数量", trigger: "blur" },
         { pattern: /^\d+$/, message: '请输入有效的数字值', trigger: 'blur' }
       ]
       ,
      }
    }
  },
  created() {
    this.getList()
    this.getDrugList()
    this.getFactoryList()
  },
  methods: {

    /** 查询药品进货记录列表 */
    getList() {
      this.loading = true
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 获取药品列表 */
    getDrugList() {
      listDrug().then(response => {
        this.drugList = response.rows
      })
    },

    /** 获取厂家列表 */
    getFactoryList() {
      listFactory().then(response => {
        this.factoryList = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        drugId: null,
        factoryId: null,
        purchaseTime: null,
        purchasePrice: null,
        purchaseNum: null,
        remark: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加药品进货记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const purchaseId = row.purchaseId || this.ids
      getPurchase(purchaseId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改药品进货记录"
      })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updatePurchase(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 不要调用updateDrugStock，因为后端库存会自动更新
            });
          } else {
            addPurchase(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 不要调用updateDrugStock，因为后端库存会自动更新
            });
          }
        }
      });
    },
    // 更新药品库存
    updateDrugStock(drugId, purchaseNum) {
      // 调用获取药品信息的接口
      getDrug(drugId).then(response => {
        const drug = response.data;
        // 确保 drug.num 是数字类型
        drug.num = Number(drug.num) + Number(purchaseNum);
        // 调用更新药品信息的接口
        updateDrug(drug).then(() => {
          this.$modal.msgSuccess("库存更新成功");
        });
      });
    },




    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids
      this.$modal.confirm('是否确认删除药品进货记录？').then(function() {
        return delPurchase(purchaseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pill/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
为什么这个代码支持下拉框获取药品名称和生产厂家