<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品编号" prop="medica">
        <el-input v-model="queryParams.medica" placeholder="请输入药品编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="药品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入药品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="药品类型" prop="medicType">
        <el-select v-model="queryParams.medicType" placeholder="请选择药品类型" clearable style="width: 180px">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用方法" prop="usageId">
        <el-select v-model="queryParams.usageId" placeholder="请选择药品使用方法" clearable style="width: 180px">
          <el-option v-for="item in usageOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus" @click="handleAdd"
          v-hasPermi="['system:medicine:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:medicine:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:medicine:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="medicineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="药品编号" align="center" prop="medica" />
      <el-table-column label="药品名称" align="center" prop="name" />
      <el-table-column label="药品类型" align="center" prop="medicType" :formatter="formatType" />
      <el-table-column label="使用方法" align="center" prop="usageId" :formatter="formatUsage" />
      <el-table-column label="备注" align="center" prop="comment" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:medicine:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:medicine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]" @pagination="getList" />

    <!-- 添加或修改药品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="medicineRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品编号" prop="medica">
          <el-input v-model="form.medica" placeholder="请输入药品编号" />
        </el-form-item>
        <el-form-item label="药品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品类型" prop="medicType">
          <el-select v-model="form.medicType" placeholder="请选择药品类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用方法" prop="usageId">
          <el-select v-model="form.usageId" placeholder="请选择药品使用方法">
            <el-option v-for="item in usageOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" placeholder="请输入备注" :rows="3" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Medicine">
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine } from "@/api/biosafety/medicine"
import { listType } from "@/api/biosafety/type"
import { listUsage } from "@/api/biosafety/usage"
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()

const medicineList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    medica: null,
    name: null,
    medicType: null,
    usageId: null,
  },
  rules: {}
})

const { queryParams, form, rules } = toRefs(data)

// ✅ 默认为空数组，避免 undefined
const typeOptions = ref([])
const usageOptions = ref([])

/* 查询药品类型 */
function getTypeOptions() {
  listType().then(response => {
    typeOptions.value = response.rows?.map(item => ({
      value: item.id,
      label: item.name
    })) || []
  })
}

/* 查询药品使用方法 */
function getUsageOptions() {
  listUsage().then(response => {
    usageOptions.value = response.rows?.map(item => ({
      value: item.id,
      label: item.name
    })) || []
  })
}

/* ✅ 安全的 formatter */
const formatType = (row) =>
  (typeOptions.value || []).find(item => item.value === row.medicType)?.label ?? row.medicType

const formatUsage = (row) =>
  (usageOptions.value || []).find(item => item.value === row.usageId)?.label ?? row.usageId

/** 查询药品列表 */
function getList() {
  loading.value = true
  listMedicine(queryParams.value).then(response => {
    medicineList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = { id: null, medica: null, name: null, medicType: null, usageId: null, comment: null }
  proxy.resetForm("medicineRef")
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = "添加药品"
}

function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMedicine(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改药品"
  })
}

function submitForm() {
  proxy.$refs["medicineRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMedicine(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMedicine(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除药品编号为"' + _ids + '"的数据项？')
    .then(() => delMedicine(_ids))
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}

function handleExport() {
  proxy.download('system/medicine/export', { ...queryParams.value }, `药品_${new Date().getTime()}.xlsx`)
}

getList()
getTypeOptions()
getUsageOptions()
</script>